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
chengpo/number-speller
appHelper/src/main/java/com/monkeyapp/numbers/apphelpers/ContextHelper.kt
1
2574
/* MIT License Copyright (c) 2017 - 2021 Po Cheng 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.monkeyapp.numbers.apphelpers import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import androidx.annotation.ColorRes import androidx.annotation.DrawableRes import androidx.core.content.ContextCompat import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat import java.lang.Exception private const val INTENT_ACTION_OCR_CAPTURE = "com.monkeyapp.numbers.intent.OCR_CAPTURE" inline val Context.isOcrAvailable:Boolean get() { return applicationContext .packageManager .getApplicationInfo(packageName, PackageManager.GET_META_DATA) .metaData .getBoolean("is_ocr_supported") } val Context.ocrIntent get()= Intent(INTENT_ACTION_OCR_CAPTURE).apply { `package` = packageName } inline fun Context.browse(url: String, newTask: Boolean, onError: (e: Exception) -> Unit = {}) { try { startActivity(Intent(Intent.ACTION_VIEW).apply { data = Uri.parse(url) if (newTask) { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } }) } catch (e: ActivityNotFoundException) { onError(e) } } fun Context.getVectorDrawable(@DrawableRes drawableId: Int) = VectorDrawableCompat.create(resources, drawableId, theme) fun Context.getCompatColor(@ColorRes colorId: Int) = ContextCompat.getColor(this, colorId)
mit
d5e6e733ed59f4afc9604117220f80a5
37.432836
119
0.750194
4.56383
false
false
false
false
RadiationX/ForPDA
app/src/main/java/forpdateam/ru/forpda/presentation/theme/ThemeJsInterface.kt
1
3491
package forpdateam.ru.forpda.presentation.theme import android.webkit.JavascriptInterface import forpdateam.ru.forpda.ui.fragments.BaseJsInterface /** * Created by radiationx on 17.03.18. */ class ThemeJsInterface( private val presenter: IThemePresenter ) : BaseJsInterface() { @JavascriptInterface fun firstPage() = runInUiThread(Runnable { presenter.onFirstPageClick() }) @JavascriptInterface fun prevPage() = runInUiThread(Runnable { presenter.onPrevPageClick() }) @JavascriptInterface fun nextPage() = runInUiThread(Runnable { presenter.onNextPageClick() }) @JavascriptInterface fun lastPage() = runInUiThread(Runnable { presenter.onLastPageClick() }) @JavascriptInterface fun selectPage() = runInUiThread(Runnable { presenter.onSelectPageClick() }) @JavascriptInterface fun showUserMenu(postId: String) = runInUiThread(Runnable { presenter.onUserMenuClick(postId.toInt()) }) @JavascriptInterface fun showReputationMenu(postId: String) = runInUiThread(Runnable { presenter.onReputationMenuClick(postId.toInt()) }) @JavascriptInterface fun showPostMenu(postId: String) = runInUiThread(Runnable { presenter.onPostMenuClick(postId.toInt()) }) @JavascriptInterface fun reportPost(postId: String) = runInUiThread(Runnable { presenter.onReportPostClick(postId.toInt()) }) @JavascriptInterface fun reply(postId: String) = runInUiThread(Runnable { presenter.onReplyPostClick(postId.toInt()) }) @JavascriptInterface fun quotePost(text: String, postId: String) = runInUiThread(Runnable { presenter.onQuotePostClick(postId.toInt(), text) }) @JavascriptInterface fun deletePost(postId: String) = runInUiThread(Runnable { presenter.onDeletePostClick(postId.toInt()) }) @JavascriptInterface fun editPost(postId: String) = runInUiThread(Runnable { presenter.onEditPostClick(postId.toInt()) }) @JavascriptInterface fun votePost(postId: String, type: Boolean) = runInUiThread(Runnable { presenter.onVotePostClick(postId.toInt(), type) }) @JavascriptInterface fun setHistoryBody(index: String, body: String) = runInUiThread(Runnable { presenter.setHistoryBody(index.toInt(), body) }) @JavascriptInterface fun copySelectedText(text: String) = runInUiThread(Runnable { presenter.copyText(text) }) @JavascriptInterface fun toast(text: String) = runInUiThread(Runnable { presenter.toast(text) }) @JavascriptInterface fun log(text: String) = runInUiThread(Runnable { presenter.log(text) }) @JavascriptInterface fun showPollResults() = runInUiThread(Runnable { presenter.onPollResultsClick() }) @JavascriptInterface fun showPoll() = runInUiThread(Runnable { presenter.onPollClick() }) @JavascriptInterface fun copySpoilerLink(postId: String, spoilNumber: String) = runInUiThread(Runnable { presenter.onSpoilerCopyLinkClick(postId.toInt(), spoilNumber) }) @JavascriptInterface fun setPollOpen(bValue: String) = runInUiThread(Runnable { presenter.onPollHeaderClick(bValue.toBoolean()) }) @JavascriptInterface fun setHatOpen(bValue: String) = runInUiThread(Runnable { presenter.onHatHeaderClick(bValue.toBoolean()) }) @JavascriptInterface fun shareSelectedText(text: String) = runInUiThread(Runnable { presenter.shareText(text) }) @JavascriptInterface fun anchorDialog(postId: String, name: String) = runInUiThread(Runnable { presenter.onAnchorClick(postId.toInt(), name) }) }
gpl-3.0
57fe0f724fb82ae125c051e1d0f57f7a
38.681818
152
0.749928
4.504516
false
false
false
false
ingokegel/intellij-community
platform/build-scripts/groovy/org/jetbrains/intellij/build/GradleRunner.kt
1
4251
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplacePutWithAssignment") package org.jetbrains.intellij.build import com.intellij.diagnostic.telemetry.useWithScope import com.intellij.openapi.util.SystemInfoRt import org.jetbrains.intellij.build.TraceManager.spanBuilder import org.jetbrains.intellij.build.dependencies.BuildDependenciesCommunityRoot import org.jetbrains.intellij.build.dependencies.JdkDownloader import java.io.File import java.nio.file.Path class GradleRunner( private val gradleProjectDir: Path, private val options: BuildOptions, private val communityRoot: BuildDependenciesCommunityRoot, private val additionalParams: List<String> = emptyList(), ) { /** * Invokes Gradle tasks on {@link #gradleProjectDir} project. * Logs error and stops the build process if Gradle process is failed. */ fun run(title: String, vararg tasks: String) = runInner(title = title, buildFile = null, force = false, parallel = false, tasks = tasks.asList()) fun runInParallel(title: String, vararg tasks: String) = runInner(title = title, buildFile = null, force = false, parallel = true, tasks = tasks.asList()) /** * Invokes Gradle tasks on {@code buildFile} project. * However, gradle wrapper from project {@link #gradleProjectDir} is used. * Logs error and stops the build process if Gradle process is failed. */ fun run(title: String, buildFile: File, vararg tasks: String) = runInner(title = title, buildFile = buildFile, force = false, parallel = false, tasks = tasks.asList()) private fun runInner(title: String, buildFile: File?, force: Boolean, parallel: Boolean, tasks: List<String>): Boolean { spanBuilder("gradle $tasks").setAttribute("title", title).useWithScope { span -> if (runInner(buildFile = buildFile, parallel = parallel, tasks = tasks)) { return true } val errorMessage = "Failed to complete `gradle ${tasks.joinToString(separator = " ")}`" if (force) { span.addEvent(errorMessage) } else { throw RuntimeException(errorMessage) } return false } } private fun runInner(buildFile: File?, parallel: Boolean, tasks: List<String>): Boolean { val gradleScript = if (SystemInfoRt.isWindows) "gradlew.bat" else "gradlew" val command = ArrayList<String>() command.add("${gradleProjectDir}/$gradleScript") command.add("-Djava.io.tmpdir=${System.getProperty("java.io.tmpdir")}") command.add("-Dorg.gradle.internal.repository.max.tentatives=${options.resolveDependenciesMaxAttempts}") command.add("-Dorg.gradle.internal.repository.initial.backoff=${options.resolveDependenciesDelayMs}") command.add("--stacktrace") if (System.getProperty("intellij.build.use.gradle.daemon", "false").toBoolean()) { command.add("--daemon") } else { command.add("--no-daemon") } if (parallel) { command.add("--parallel") } if (buildFile != null) { command.add("-b") command.add(buildFile.absolutePath) } command.addAll(additionalParams) command.addAll(tasks) val processBuilder = ProcessBuilder(command).directory(gradleProjectDir.toFile()) processBuilder.environment().put("JAVA_HOME", JdkDownloader.getJdkHome(communityRoot).toString()) processBuilder.inheritIO() return processBuilder.start().waitFor() == 0 } }
apache-2.0
5bae90a713a478b5ed72dab788473dab
44.223404
122
0.579628
5.360656
false
false
false
false
mdaniel/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/savedPatches/SavedPatchesTree.kt
2
7779
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.vcs.changes.savedPatches import com.intellij.ide.DataManager import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.actionSystem.ex.ActionUtil.performActionDumbAwareWithCallbacks import com.intellij.openapi.project.Project import com.intellij.openapi.util.ClearableLazyValue import com.intellij.openapi.util.TextRange import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.changes.savedPatches.SavedPatchesUi.Companion.SAVED_PATCHES_UI_PLACE import com.intellij.openapi.vcs.changes.ui.* import com.intellij.ui.SimpleTextAttributes import com.intellij.ui.TreeSpeedSearch import com.intellij.ui.speedSearch.SpeedSearchSupply import com.intellij.ui.speedSearch.SpeedSearchUtil import com.intellij.util.EditSourceOnDoubleClickHandler import com.intellij.util.FontUtil import com.intellij.util.Processor import com.intellij.util.ui.tree.TreeUtil import org.jetbrains.annotations.Nls import java.awt.Component import java.awt.Graphics import java.awt.Graphics2D import java.util.stream.Stream import javax.swing.JTree import javax.swing.tree.TreePath class SavedPatchesTree(project: Project, private val savedPatchesProviders: List<SavedPatchesProvider<*>>, parentDisposable: Disposable) : ChangesTree(project, false, false, false) { internal val speedSearch: SpeedSearchSupply init { val nodeRenderer = ChangesBrowserNodeRenderer(myProject, { isShowFlatten }, false) setCellRenderer(MyTreeRenderer(nodeRenderer)) isKeepTreeState = true isScrollToSelection = false setEmptyText(VcsBundle.message("saved.patch.empty.text")) speedSearch = MySpeedSearch(this) doubleClickHandler = Processor { e -> if (EditSourceOnDoubleClickHandler.isToggleEvent(this, e)) return@Processor false val diffAction = ActionManager.getInstance().getAction(IdeActions.ACTION_SHOW_DIFF_COMMON) val dataContext = DataManager.getInstance().getDataContext(this) val event = AnActionEvent.createFromAnAction(diffAction, e, SAVED_PATCHES_UI_PLACE, dataContext) val isEnabled = ActionUtil.lastUpdateAndCheckDumb(diffAction, event, true) if (isEnabled) performActionDumbAwareWithCallbacks(diffAction, event) isEnabled } savedPatchesProviders.forEach { provider -> provider.subscribeToPatchesListChanges(parentDisposable, ::rebuildTree) } } override fun rebuildTree() { val wasEmpty = VcsTreeModelData.all(this).iterateUserObjects().isEmpty val modelBuilder = TreeModelBuilder(project, groupingSupport.grouping) if (savedPatchesProviders.any { !it.isEmpty() }) { savedPatchesProviders.forEach { provider -> provider.buildPatchesTree(modelBuilder) } } updateTreeModel(modelBuilder.build()) if (!VcsTreeModelData.all(this).iterateUserObjects().isEmpty && wasEmpty) { expandDefaults() } if (selectionCount == 0) { TreeUtil.selectFirstNode(this) } } override fun installGroupingSupport(): ChangesGroupingSupport { return object : ChangesGroupingSupport(myProject, this, false) { override fun isAvailable(groupingKey: String): Boolean = false } } override fun getData(dataId: String): Any? { val selectedObjects = selectedPatchObjects() val data = savedPatchesProviders.firstNotNullOfOrNull { provider -> provider.getData(dataId, selectedObjects) } if (data != null) return data if (CommonDataKeys.PROJECT.`is`(dataId)) return myProject return super.getData(dataId) } internal fun selectedPatchObjects(): Stream<SavedPatchesProvider.PatchObject<*>> { return VcsTreeModelData.selected(this) .iterateUserObjects(SavedPatchesProvider.PatchObject::class.java) .toStream() } override fun getToggleClickCount(): Int = 2 class TagWithCounterChangesBrowserNode(text: @Nls String, expandByDefault: Boolean = true, private val sortWeight: Int? = null) : TagChangesBrowserNode(TagImpl(text), SimpleTextAttributes.REGULAR_ATTRIBUTES, expandByDefault) { private val stashCount = ClearableLazyValue.create { VcsTreeModelData.children(this).userObjects(SavedPatchesProvider.PatchObject::class.java).size } init { markAsHelperNode() } override fun getCountText() = FontUtil.spaceAndThinSpace() + stashCount.value override fun resetCounters() { super.resetCounters() stashCount.drop() } override fun getSortWeight(): Int { return sortWeight ?: super.getSortWeight() } } private class MyTreeRenderer(renderer: ChangesBrowserNodeRenderer) : ChangesTreeCellRenderer(renderer) { private var painter: SavedPatchesProvider.PatchObject.Painter? = null override fun paint(g: Graphics) { super.paint(g) painter?.paint(g as Graphics2D) } override fun getTreeCellRendererComponent(tree: JTree, value: Any, selected: Boolean, expanded: Boolean, leaf: Boolean, row: Int, hasFocus: Boolean): Component { val rendererComponent = super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus) val node = value as ChangesBrowserNode<*> painter = customizePainter(tree as ChangesTree, node, row, selected) val speedSearch = SpeedSearchSupply.getSupply(tree) if (speedSearch != null) { val patchObject = node.userObject as? SavedPatchesProvider.PatchObject<*> if (patchObject != null) { val text = textRenderer.getCharSequence(false).toString() if (speedSearch.matchingFragments(text) == null && speedSearch.matches(patchObject)) { SpeedSearchUtil.applySpeedSearchHighlighting(textRenderer, listOf(TextRange.allOf(text)), selected) } } } return rendererComponent } private fun customizePainter(tree: ChangesTree, node: ChangesBrowserNode<*>, row: Int, selected: Boolean): SavedPatchesProvider.PatchObject.Painter? { if (tree.expandableItemsHandler.expandedItems.contains(row)) { return null } val patchObject = node.userObject as? SavedPatchesProvider.PatchObject<*> ?: return null return patchObject.createPainter(tree, this, row, selected) } } private class MySpeedSearch(tree: JTree) : TreeSpeedSearch(tree, ChangesBrowserNode.TO_TEXT_CONVERTER, true) { override fun isMatchingElement(element: Any?, pattern: String?): Boolean { val isMatching = super.isMatchingElement(element, pattern) if (isMatching) return true val node = (element as? TreePath)?.lastPathComponent as? ChangesBrowserNode<*> ?: return false val patchObject = node.userObject as? SavedPatchesProvider.PatchObject<*> ?: return false return matches(patchObject) } } companion object { private fun SpeedSearchSupply.matches(patchObject: SavedPatchesProvider.PatchObject<*>): Boolean { val changes = patchObject.cachedChanges() ?: return false return changes.any { matchingFragments(it.filePath.name) != null } } } }
apache-2.0
8ae24e90038a32abbf09bbe212db1edf
40.604278
131
0.712688
4.883239
false
false
false
false
ingokegel/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/impl/callReferenceImpl.kt
13
1649
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.resolve.impl import com.intellij.psi.PsiElement import com.intellij.psi.PsiType import com.intellij.psi.ResolveState import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.rValueProcessor import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.resolveKinds import org.jetbrains.plugins.groovy.lang.resolve.api.Argument import org.jetbrains.plugins.groovy.lang.resolve.api.Arguments import org.jetbrains.plugins.groovy.lang.resolve.processReceiver import org.jetbrains.plugins.groovy.lang.resolve.processors.MethodProcessor fun resolveWithArguments(receiver: Argument, methodName: String, arguments: Arguments?, place: PsiElement): List<GroovyResolveResult> { val state = ResolveState.initial() val methodProcessor = MethodProcessor(methodName, place, arguments, PsiType.EMPTY_ARRAY) receiver.processReceiver(methodProcessor, state, place) methodProcessor.applicableCandidates?.let { return it } val propertyProcessor = rValueProcessor(methodName, place, resolveKinds(true)) receiver.processReceiver(propertyProcessor, state, place) val properties = propertyProcessor.results if (properties.size == 1) { return properties } val methods = filterBySignature(filterByArgumentsCount(methodProcessor.allCandidates, arguments)) return methods + properties }
apache-2.0
6a357af6754a1ce33bda4a66fb5cb484
46.114286
140
0.781686
4.468835
false
false
false
false
icela/FriceEngine
src/org/frice/platform/adapter/JvmImage.kt
1
1904
package org.frice.platform.adapter import org.frice.platform.FriceImage import org.frice.resource.graphics.ColorResource import org.frice.util.* import java.awt.geom.AffineTransform import java.awt.image.AffineTransformOp import java.awt.image.BufferedImage open class JvmImage(val image: BufferedImage) : FriceImage { constructor(width: Int, height: Int) : this(BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB)) override val width = image.width override val height = image.height override operator fun get(x: Int, y: Int) = ColorResource(image.getRGB(x, y)) override operator fun set(x: Int, y: Int, color: Int) = image.setRGB(x, y, color) override fun scale(x: Double, y: Double) = JvmImage(scaleImpl(x, y)) protected fun scaleImpl(x: Double, y: Double): BufferedImage = AffineTransformOp( AffineTransform().apply { scale(x, y) }, AffineTransformOp.TYPE_BILINEAR).filter(image, null) override fun part(x: Int, y: Int, width: Int, height: Int) = JvmImage(partImpl(x, y, width, height)) protected fun partImpl(x: Int, y: Int, width: Int, height: Int): BufferedImage = image.getSubimage(x, y, width, height) override fun clone() = JvmImage(cloneImpl()) protected fun cloneImpl() = BufferedImage(width, height, image.type).apply { [email protected] = [email protected] } override fun flip(orientation: Boolean) = JvmImage(flipImpl(orientation)) protected fun flipImpl(orientation: Boolean): BufferedImage = AffineTransformOp( if (orientation) AffineTransform.getScaleInstance(-1.0, 1.0).apply { translate((-width).toDouble(), 0.0) } // horizontal else AffineTransform.getScaleInstance(1.0, -1.0).apply { translate(0.0, (-height).toDouble()) }, // vertical AffineTransformOp.TYPE_NEAREST_NEIGHBOR).filter(image, null) override fun fx() = JfxImage(image) fun greenify() = image.greenify() fun redify() = image.redify() fun bluify() = image.bluify() }
agpl-3.0
00bf66cd71d2b175ab5452ce16b09c26
41.311111
122
0.743172
3.334501
false
false
false
false
shogo4405/HaishinKit.java
haishinkit/src/main/java/com/haishinkit/flv/FlvVideoCodec.kt
1
387
package com.haishinkit.flv /** * The type of flv supports video codecs. */ @Suppress("unused") object FlvVideoCodec { const val SORENSON_H263: Byte = 0x02 const val SCREEN1: Byte = 0x03 const val ON2_VP6: Byte = 0x04 const val ON2_VP6_ALPHA: Byte = 0x05 const val SCREEN_2: Byte = 0x06 const val AVC: Byte = 0x07 const val UNKNOWN: Byte = Byte.MAX_VALUE }
bsd-3-clause
e5af304092869d65bb35c777aa250afc
24.8
44
0.671835
3
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/containers/BidirectionalSetMap.kt
2
2639
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.storage.impl.containers import com.intellij.util.containers.CollectionFactory import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap import kotlin.collections.component1 import kotlin.collections.component2 internal class BidirectionalSetMap<K, V> private constructor(private val keyToValueMap: MutableMap<K, V>, private val valueToKeysMap: MutableMap<V, MutableSet<K>>) : MutableMap<K, V> { constructor() : this(CollectionFactory.createSmallMemoryFootprintMap(), HashMap<V, MutableSet<K>>()) override fun put(key: K, value: V): V? { val oldValue = keyToValueMap.put(key, value) if (oldValue != null) { if (oldValue == value) { return oldValue } val array = valueToKeysMap[oldValue]!! array.remove(key) if (array.isEmpty()) { valueToKeysMap.remove(oldValue) } } val array = valueToKeysMap.computeIfAbsent(value) { HashSet() } array.add(key) return oldValue } override fun clear() { keyToValueMap.clear() valueToKeysMap.clear() } fun getKeysByValue(value: V): Set<K>? { return valueToKeysMap[value] } override val keys: MutableSet<K> get() = keyToValueMap.keys override val size: Int get() = keyToValueMap.size override fun isEmpty(): Boolean { return keyToValueMap.isEmpty() } override fun containsKey(key: K): Boolean { return keyToValueMap.containsKey(key) } override fun containsValue(value: V): Boolean { return valueToKeysMap.containsKey(value) } override operator fun get(key: K): V? = keyToValueMap[key] fun removeValue(v: V) { val ks: MutableSet<K>? = valueToKeysMap.remove(v) if (ks != null) { for (k in ks) { keyToValueMap.remove(k) } } } override fun remove(key: K): V? { val value = keyToValueMap.remove(key) val ks: MutableSet<K>? = valueToKeysMap[value] if (ks != null) { if (ks.size > 1) { ks.remove(key) } else { valueToKeysMap.remove(value) } } return value } override fun putAll(from: Map<out K, V>) { for ((key, value) in from) { put(key, value) } } override val values: MutableSet<V> get() = valueToKeysMap.keys override val entries: MutableSet<MutableMap.MutableEntry<K, V>> get() = keyToValueMap.entries override fun toString(): String { return keyToValueMap.toString() } }
apache-2.0
872f797c792eddcf1eaf0725571fcc26
25.39
140
0.650625
4.155906
false
false
false
false
GunoH/intellij-community
python/testSrc/com/jetbrains/env/conda/CondaYamlFileRule.kt
2
2129
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.jetbrains.env.conda import com.intellij.execution.processTools.getResultStdoutStr import com.intellij.execution.processTools.mapFlat import com.intellij.execution.target.TargetProgressIndicator import com.intellij.execution.target.TargetedCommandLineBuilder import com.intellij.execution.target.local.LocalTargetEnvironmentRequest import com.intellij.util.io.delete import com.jetbrains.python.psi.LanguageLevel import com.jetbrains.python.sdk.flavors.conda.NewCondaEnvRequest import com.jetbrains.python.sdk.flavors.conda.PyCondaCommand import com.jetbrains.python.sdk.flavors.conda.PyCondaEnv import kotlinx.coroutines.runBlocking import org.junit.rules.ExternalResource import java.io.File import java.nio.file.Path /** */ internal class CondaYamlFileRule(private val condaRule: LocalCondaRule, private val languageLevel: LanguageLevel = LanguageLevel.PYTHON39) : ExternalResource() { lateinit var yamlFilePath: Path private set val envName: String = "file_${Math.random()}.yaml" override fun before() { val fullPathOnTarget = condaRule.condaPathOnTarget val command = PyCondaCommand(fullPathOnTarget, null, null) val condaEnvRequest = NewCondaEnvRequest.EmptyNamedEnv(languageLevel, envName) runBlocking { PyCondaEnv.createEnv(command, condaEnvRequest).mapFlat { it.getResultStdoutStr() } } val targetReq = LocalTargetEnvironmentRequest() val builder = TargetedCommandLineBuilder(targetReq).apply { setExePath(fullPathOnTarget) addParameter("env") addParameter("export") addParameter("-n") addParameter(envName) } val targetEnv = targetReq.prepareEnvironment(TargetProgressIndicator.EMPTY) val yaml = targetEnv.createProcess(builder.build()).let { runBlocking { it.getResultStdoutStr() } }.getOrThrow() val file = File.createTempFile("ijconda", ".yaml") file.writeText(yaml) yamlFilePath = file.toPath() } override fun after() { yamlFilePath.delete() } }
apache-2.0
5a1f195ba53ecbbf0521121cf3fa17af
39.961538
122
0.771254
4.327236
false
false
false
false
GunoH/intellij-community
platform/webSymbols/src/com/intellij/webSymbols/webTypes/impl/WebTypesJsonContributionWrapper.kt
2
19253
// 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.webSymbols.webTypes.impl import com.intellij.model.Pointer import com.intellij.model.Symbol import com.intellij.openapi.util.IconLoader import com.intellij.openapi.util.UserDataHolderBase import com.intellij.openapi.util.UserDataHolderEx import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElement import com.intellij.util.containers.Stack import com.intellij.util.ui.EmptyIcon import com.intellij.webSymbols.* import com.intellij.webSymbols.WebSymbol.Companion.KIND_HTML_ATTRIBUTES import com.intellij.webSymbols.WebSymbol.Priority import com.intellij.webSymbols.completion.WebSymbolCodeCompletionItem import com.intellij.webSymbols.html.WebSymbolHtmlAttributeValue import com.intellij.webSymbols.patterns.WebSymbolsPattern import com.intellij.webSymbols.query.WebSymbolsCodeCompletionQueryParams import com.intellij.webSymbols.query.WebSymbolsNameMatchQueryParams import com.intellij.webSymbols.query.WebSymbolsQueryExecutor import com.intellij.webSymbols.query.impl.WebSymbolsQueryExecutorImpl.Companion.asSymbolNamespace import com.intellij.webSymbols.utils.merge import com.intellij.webSymbols.webTypes.WebTypesJsonOrigin import com.intellij.webSymbols.webTypes.WebTypesSymbol import com.intellij.webSymbols.webTypes.WebTypesSymbolsScopeBase import com.intellij.webSymbols.webTypes.json.* import javax.swing.Icon internal abstract class WebTypesJsonContributionWrapper private constructor(protected val contribution: BaseContribution, private val jsonOrigin: WebTypesJsonOrigin, protected val cacheHolder: UserDataHolderEx, protected val rootScope: WebTypesSymbolsScopeBase, val namespace: SymbolNamespace, val kind: String) { companion object { fun BaseContribution.wrap(origin: WebTypesJsonOrigin, rootScope: WebTypesSymbolsScopeBase, root: SymbolNamespace, kind: SymbolKind): WebTypesJsonContributionWrapper = if (pattern != null) { Pattern(this, origin, UserDataHolderBase(), rootScope, root, kind) } else if ((name != null && name.startsWith(VUE_DIRECTIVE_PREFIX)) && origin.framework == VUE_FRAMEWORK && kind == KIND_HTML_ATTRIBUTES) { LegacyVueDirective(this, origin, UserDataHolderBase(), rootScope, root) } else if (name != null && kind == KIND_HTML_VUE_LEGACY_COMPONENTS && this is HtmlElement) { LegacyVueComponent(this, origin, UserDataHolderBase(), rootScope, root) } else { Static(this, origin, UserDataHolderBase(), rootScope, root, kind) } } val framework: String? get() = jsonOrigin.framework val icon get() = contribution.icon?.let { IconLoader.createLazy { jsonOrigin.loadIcon(it) ?: EmptyIcon.ICON_0 } } abstract val name: String open val contributionName: String = contribution.name ?: "<no-name>" abstract val jsonPattern: NamePatternRoot? val pattern: WebSymbolsPattern? get() = jsonPattern?.wrap(contribution.name) open val contributionForQuery: GenericContributionsHost get() = contribution private var exclusiveContributions: Set<Pair<SymbolNamespace, String>>? = null fun isExclusiveFor(namespace: SymbolNamespace, kind: SymbolKind): Boolean = (exclusiveContributions ?: when { contribution.exclusiveContributions.isEmpty() -> emptySet() else -> contribution.exclusiveContributions .asSequence() .mapNotNull { path -> if (!path.startsWith('/')) return@mapNotNull null val slash = path.indexOf('/', 1) if (path.lastIndexOf('/') != slash) return@mapNotNull null val n = path.substring(1, slash).asSymbolNamespace() ?: return@mapNotNull null val k = path.substring(slash + 1, path.length) Pair(n, k) } .toSet() }.also { exclusiveContributions = it } ) .takeIf { it.isNotEmpty() } ?.contains(Pair(namespace, kind)) == true fun withQueryExecutorContext(queryExecutor: WebSymbolsQueryExecutor): WebTypesSymbolImpl = WebTypesSymbolImpl(this, queryExecutor) internal class WebTypesSymbolImpl(private val base: WebTypesJsonContributionWrapper, private val queryExecutor: WebSymbolsQueryExecutor) : WebTypesSymbol { private var _superContributions: List<WebSymbol>? = null private val superContributions: List<WebSymbol> get() = _superContributions ?: base.contribution.extends .also { _superContributions = emptyList() } ?.resolve(null, listOf(), queryExecutor, true, true) ?.toList() ?.also { contributions -> _superContributions = contributions } ?: emptyList() override fun getSymbols(namespace: SymbolNamespace?, kind: String, name: String?, params: WebSymbolsNameMatchQueryParams, scope: Stack<WebSymbolsScope>): List<WebSymbolsScope> = base.rootScope .getSymbols(base.contributionForQuery, this.namespace, base.jsonOrigin, namespace, kind, name, params, scope) .toList() override fun getCodeCompletions(namespace: SymbolNamespace?, kind: String, name: String?, params: WebSymbolsCodeCompletionQueryParams, scope: Stack<WebSymbolsScope>): List<WebSymbolCodeCompletionItem> = base.rootScope .getCodeCompletions(base.contributionForQuery, this.namespace, base.jsonOrigin, namespace, kind, name, params, scope) .toList() override val kind: SymbolKind get() = base.kind override val origin: WebTypesJsonOrigin get() = base.jsonOrigin override val namespace: SymbolNamespace get() = base.namespace override val nameSegments: List<WebSymbolNameSegment> get() = listOf(WebSymbolNameSegment(0, if (base is Pattern) 0 else matchedName.length, this)) override val name: String get() = base.contributionName override val description: String? get() = base.contribution.description ?.let { base.jsonOrigin.renderDescription(base.contribution.description) } ?: superContributions.asSequence().mapNotNull { it.description }.firstOrNull() override val descriptionSections: Map<String, String> get() = (base.contribution.descriptionSections?.additionalProperties?.asSequence() ?: emptySequence()) .plus(superContributions.asSequence().flatMap { it.descriptionSections.asSequence() }) .distinctBy { it.key } .associateBy({ it.key }, { it.value }) override val docUrl: String? get() = base.contribution.docUrl ?: superContributions.asSequence().mapNotNull { it.docUrl }.firstOrNull() override val icon: Icon? get() = base.icon ?: superContributions.asSequence().mapNotNull { it.icon }.firstOrNull() override val location: WebTypesSymbol.Location? // Should not reach to super contributions, because it can lead to stack overflow // when special containers are trying to merge symbols get() = base.contribution.source ?.let { base.jsonOrigin.resolveSourceLocation(it) } override val source: PsiElement? // Should not reach to super contributions, because it can lead to stack overflow // when special containers are trying to merge symbols get() = base.contribution.source ?.let { base.jsonOrigin.resolveSourceSymbol(it, base.cacheHolder) } override val attributeValue: WebSymbolHtmlAttributeValue? get() = (base.contribution.attributeValue?.let { sequenceOf(HtmlAttributeValueImpl(it)) } ?: emptySequence()) .plus(superContributions.asSequence().map { it.attributeValue }) .merge() override val type: Any? get() = (base.contribution.type) ?.let { base.jsonOrigin.typeSupport?.resolve(it.mapToTypeReferences()) } ?: superContributions.asSequence().mapNotNull { it.type }.firstOrNull() override val deprecated: Boolean get() = base.contribution.deprecated == true override val experimental: Boolean get() = base.contribution.experimental == true override val virtual: Boolean get() = base.contribution.virtual == true override val extension: Boolean get() = base.contribution.extension == true override val priority: Priority? get() = base.contribution.priority?.wrap() ?: superContributions.firstOrNull()?.priority override val proximity: Int? get() = base.contribution.proximity ?: superContributions.firstOrNull()?.proximity override val abstract: Boolean get() = base.contribution.abstract == true override val required: Boolean? get() = (base.contribution as? GenericContribution)?.required ?: (base.contribution as? HtmlAttribute)?.required ?: superContributions.firstOrNull()?.required override val defaultValue: String? get() = (base.contribution as? GenericContribution)?.default ?: (base.contribution as? HtmlAttribute)?.default ?: superContributions.firstOrNull()?.defaultValue override val pattern: WebSymbolsPattern? get() = base.jsonPattern?.wrap(base.contribution.name) override val matchedName: String get() = base.name override fun createPointer(): Pointer<WebTypesSymbolImpl> { val queryExecutorPtr = this.queryExecutor.createPointer() val basePtr = this.base.createPointer() return Pointer<WebTypesSymbolImpl> { val queryExecutor = queryExecutorPtr.dereference() ?: return@Pointer null val base = basePtr.dereference() ?: return@Pointer null base.withQueryExecutorContext(queryExecutor) } } override val queryScope: Sequence<WebSymbolsScope> get() = superContributions.asSequence() .flatMap { it.queryScope } .plus(this) override val properties: Map<String, Any> get() = base.contribution.genericProperties override fun isExclusiveFor(namespace: SymbolNamespace?, kind: SymbolKind): Boolean = namespace != null && namespace == this.namespace && (base.isExclusiveFor(namespace, kind) || superContributions.any { it.isExclusiveFor(namespace, kind) }) override fun toString(): String = base.toString() override fun isEquivalentTo(symbol: Symbol): Boolean = (symbol is WebTypesSymbolImpl && symbol.base == this.base) || super.isEquivalentTo(symbol) private inner class HtmlAttributeValueImpl(private val value: HtmlAttributeValue) : WebSymbolHtmlAttributeValue { override val kind: WebSymbolHtmlAttributeValue.Kind? get() = value.kind?.wrap() override val type: WebSymbolHtmlAttributeValue.Type? get() = value.type?.wrap() override val required: Boolean? get() = value.required override val default: String? get() = value.default override val langType: Any? get() = value.type?.toLangType() ?.let { base.jsonOrigin.typeSupport?.resolve(it.mapToTypeReferences()) } } } abstract fun createPointer(): Pointer<out WebTypesJsonContributionWrapper> private class Static(contribution: BaseContribution, context: WebTypesJsonOrigin, cacheHolder: UserDataHolderEx, rootScope: WebTypesSymbolsScopeBase, namespace: SymbolNamespace, kind: String) : WebTypesJsonContributionWrapper(contribution, context, cacheHolder, rootScope, namespace, kind) { override val name: String get() = contribution.name ?: "<no-name>" override fun toString(): String = "$kind/$name <static>" override val jsonPattern: NamePatternRoot? get() = null override fun createPointer(): Pointer<Static> = object : WebTypesJsonContributionWrapperPointer<Static>(this) { override fun dereference(): Static? = rootScope.dereference()?.let { Static(contribution, jsonContext, cacheHolder, it, namespace, kind) } } } private class Pattern(contribution: BaseContribution, context: WebTypesJsonOrigin, cacheHolder: UserDataHolderEx, rootScope: WebTypesSymbolsScopeBase, namespace: SymbolNamespace, kind: String) : WebTypesJsonContributionWrapper(contribution, context, cacheHolder, rootScope, namespace, kind) { override val jsonPattern: NamePatternRoot? get() = contribution.pattern override val name: String = "<pattern>" override fun toString(): String = "$kind/${jsonPattern?.wrap("")?.getStaticPrefixes()?.toSet() ?: "[]"}... <pattern>" override fun createPointer(): Pointer<Pattern> = object : WebTypesJsonContributionWrapperPointer<Pattern>(this) { override fun dereference(): Pattern? = rootScope.dereference()?.let { Pattern(contribution, jsonContext, cacheHolder, it, namespace, kind) } } } private class LegacyVueDirective(contribution: BaseContribution, context: WebTypesJsonOrigin, cacheHolder: UserDataHolderEx, rootScope: WebTypesSymbolsScopeBase, root: SymbolNamespace) : WebTypesJsonContributionWrapper(contribution, context, cacheHolder, rootScope, root, KIND_HTML_VUE_DIRECTIVES) { override val name: String = contribution.name.substring(2) override val contributionName: String get() = name override fun toString(): String = "$kind/${this.name} <static-legacy>" override val jsonPattern: NamePatternRoot? get() = null override fun createPointer(): Pointer<LegacyVueDirective> = object : WebTypesJsonContributionWrapperPointer<LegacyVueDirective>(this) { override fun dereference(): LegacyVueDirective? = rootScope.dereference()?.let { LegacyVueDirective(contribution, jsonContext, cacheHolder, it, namespace) } } } private class LegacyVueComponent(contribution: HtmlElement, context: WebTypesJsonOrigin, cacheHolder: UserDataHolderEx, rootScope: WebTypesSymbolsScopeBase, root: SymbolNamespace) : WebTypesJsonContributionWrapper(contribution, context, cacheHolder, rootScope, root, KIND_HTML_VUE_COMPONENTS) { private var _contributionForQuery: GenericContributionsHost? = null override val name: String = contribution.name.let { if (it.contains('-')) toVueComponentPascalName(contribution.name) else it } override fun toString(): String = "$kind/$name <legacy static>" override val jsonPattern: NamePatternRoot? get() = null override val contributionForQuery: GenericContributionsHost get() = _contributionForQuery ?: (contribution as HtmlElement).convertToComponentContribution().also { _contributionForQuery = it } override fun createPointer(): Pointer<LegacyVueComponent> = object : WebTypesJsonContributionWrapperPointer<LegacyVueComponent>(this) { override fun dereference(): LegacyVueComponent? = rootScope.dereference()?.let { LegacyVueComponent(contribution as HtmlElement, jsonContext, cacheHolder, it, namespace) } } companion object { private fun toVueComponentPascalName(name: String): String { val result = StringBuilder() var nextCapitalized = true for (ch in name) { when { ch == '-' -> nextCapitalized = true nextCapitalized -> { result.append(StringUtil.toUpperCase(ch)) nextCapitalized = false } else -> result.append(ch) } } return result.toString() } fun HtmlElement.convertToComponentContribution(): GenericContributionsHost { val result = GenericHtmlContribution() val map = result.additionalProperties map.putAll(this.additionalProperties) val scopedSlots = result.genericContributions["vue-scoped-slots"] if (!scopedSlots.isNullOrEmpty()) { scopedSlots.mapTo(map.computeIfAbsent("slots") { GenericHtmlContributions() }) { contribution -> GenericHtmlContributionOrProperty().also { it.value = contribution.convertToSlot() } } map.remove("vue-scoped-slots") } map[KIND_HTML_VUE_COMPONENT_PROPS] = GenericHtmlContributions().also { contributions -> this.attributes.mapTo(contributions) { attribute -> GenericHtmlContributionOrProperty().also { it.value = attribute.convertToPropsContribution() } } } result.events.addAll(this.events) return result } fun HtmlAttribute.convertToPropsContribution(): GenericContribution { val result = GenericHtmlContribution() result.copyLegacyFrom(this) result.required = this.required if (this.attributeValue != null || this.default != null) { result.attributeValue = HtmlAttributeValue().also { attributeValue?.let { other -> it.required = other.required it.default = other.default it.type = other.type } if (it.default == null) { it.default = this.default } } } return result } fun GenericContribution.convertToSlot(): GenericHtmlContribution { val result = GenericHtmlContribution() result.copyLegacyFrom(this) result.additionalProperties["vue-properties"] = result.additionalProperties["properties"] return result } } } private abstract class WebTypesJsonContributionWrapperPointer<T : WebTypesJsonContributionWrapper>(wrapper: T) : Pointer<T> { val contribution = wrapper.contribution val jsonContext = wrapper.jsonOrigin val cacheHolder = wrapper.cacheHolder val rootScope = wrapper.rootScope.createPointer() val namespace = wrapper.namespace val kind = wrapper.kind } }
apache-2.0
d1b54b95f560a6218f8d598eea51c718
39.280335
136
0.646237
5.221861
false
false
false
false
himikof/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/ext/RsModItem.kt
1
1752
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.psi.ext import com.intellij.lang.ASTNode import com.intellij.psi.PsiDirectory import com.intellij.psi.stubs.IStubElementType import com.intellij.psi.util.PsiTreeUtil import org.rust.ide.icons.RsIcons import org.rust.lang.core.psi.* import org.rust.lang.core.stubs.RsModItemStub import javax.swing.Icon abstract class RsModItemImplMixin : RsStubbedNamedElementImpl<RsModItemStub>, RsModItem { constructor(node: ASTNode) : super(node) constructor(stub: RsModItemStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType) override fun getIcon(flags: Int): Icon = iconWithVisibility(flags, RsIcons.MODULE) override val isPublic: Boolean get() = RustPsiImplUtil.isPublic(this, stub) override val `super`: RsMod get() = containingMod override val modName: String? get() = name override val crateRelativePath: String? get() = RustPsiImplUtil.modCrateRelativePath(this) override val ownsDirectory: Boolean = true // Any inline nested mod owns a directory override val ownedDirectory: PsiDirectory? get() { val name = name ?: return null return `super`.ownedDirectory?.findSubdirectory(name) } override val isCrateRoot: Boolean = false override val innerAttrList: List<RsInnerAttr> get() = PsiTreeUtil.getStubChildrenOfTypeAsList(this, RsInnerAttr::class.java) override val outerAttrList: List<RsOuterAttr> get() = PsiTreeUtil.getStubChildrenOfTypeAsList(this, RsOuterAttr::class.java) } val RsModItem.hasMacroUse: Boolean get() = queryAttributes.hasAttribute("macro_use")
mit
ccd0f1647c17a212b0aa9403f6b70731
32.056604
94
0.730594
4.38
false
false
false
false
RayBa82/DVBViewerController
dvbViewerController/src/main/java/org/dvbviewer/controller/ui/fragments/StatusList.kt
1
9065
/* * Copyright © 2012 dvbviewer-controller 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 org.dvbviewer.controller.ui.fragments import android.content.res.Resources import android.os.Bundle import android.view.* import android.widget.TextView import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import org.apache.commons.lang3.math.NumberUtils import org.dvbviewer.controller.R import org.dvbviewer.controller.data.api.ApiResponse import org.dvbviewer.controller.data.api.ApiStatus import org.dvbviewer.controller.data.entities.DVBViewerPreferences import org.dvbviewer.controller.data.entities.Status import org.dvbviewer.controller.data.entities.Status.Folder import org.dvbviewer.controller.data.entities.Status.StatusItem import org.dvbviewer.controller.data.status.StatusViewModel import org.dvbviewer.controller.data.status.StatusViewModelFactory import org.dvbviewer.controller.data.version.VersionRepository import org.dvbviewer.controller.ui.base.BaseListFragment import org.dvbviewer.controller.utils.ArrayListAdapter import org.dvbviewer.controller.utils.CategoryAdapter import org.dvbviewer.controller.utils.DateUtils import org.dvbviewer.controller.utils.FileUtils class StatusList : BaseListFragment() { private val TAG = "StatusList" private lateinit var mAdapter: CategoryAdapter private lateinit var mRes: Resources private lateinit var versionRepository: VersionRepository private lateinit var prefs: DVBViewerPreferences private lateinit var statusViewModel: StatusViewModel private var mStatusAdapter: StatusAdapter? = null /* (non-Javadoc) * @see android.support.v4.app.Fragment#onCreate(android.os.Bundle) */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) mStatusAdapter = StatusAdapter() mAdapter = CategoryAdapter(context) mRes = resources prefs = DVBViewerPreferences(activity!!.applicationContext) versionRepository = VersionRepository(activity!!.applicationContext, getDmsInterface()) } /* * (non-Javadoc) * * @see android.support.v4.app.Fragment#onActivityCreated(android.os.Bundle) */ override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) val statusObserver = Observer<ApiResponse<Status>> { response -> onStatusLoaded(response!!) } val statusViewModelFactory = StatusViewModelFactory(prefs, versionRepository) statusViewModel = ViewModelProvider(this, statusViewModelFactory) .get(StatusViewModel::class.java) statusViewModel.getStatus().observe(this, statusObserver) setListShown(isResumed) } private fun onStatusLoaded(apiResponse: ApiResponse<Status>) { if (apiResponse.status == ApiStatus.SUCCESS) { mStatusAdapter!!.items = apiResponse.data?.items val folderAdapter = FolderAdapter() folderAdapter.items = apiResponse.data?.folders mAdapter.addSection(getString(R.string.status), mStatusAdapter) mAdapter.addSection(getString(R.string.recording_folder), folderAdapter) mAdapter.notifyDataSetChanged() } else if (apiResponse.status == ApiStatus.ERROR) { catchException(TAG, apiResponse.e) } listAdapter = mAdapter setListShown(true) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.status, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.menuRefresh -> { refresh() true } else -> false } } private class StatusHolder { internal var title: TextView? = null internal var statusText: TextView? = null internal var free: TextView? = null internal var size: TextView? = null } inner class FolderAdapter : ArrayListAdapter<Folder>() { /* * (non-Javadoc) * * @see android.widget.ArrayAdapter#getView(int, android.view.View, * android.view.ViewGroup) */ override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { var convertView = convertView val holder: StatusHolder if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.list_item_status, parent, false) holder = StatusHolder() holder.title = convertView!!.findViewById(R.id.title) holder.statusText = convertView.findViewById(R.id.statusText) holder.size = convertView.findViewById(R.id.size) holder.free = convertView.findViewById(R.id.free) convertView.tag = holder } else { holder = convertView.tag as StatusHolder } holder.title!!.text = mItems[position].path holder.statusText!!.visibility = View.GONE holder.size!!.visibility = View.VISIBLE holder.free!!.visibility = View.VISIBLE holder.size!!.text = mRes.getString(R.string.status_folder_total) + mRes.getString(R.string.common_colon) + FileUtils.byteToHumanString(mItems[position].size) holder.free!!.text = mRes.getString(R.string.status_folder_free) + mRes.getString(R.string.common_colon) + FileUtils.byteToHumanString(mItems[position].free) super.getViewTypeCount() return convertView } } inner class StatusAdapter : ArrayListAdapter<StatusItem>() { /* * (non-Javadoc) * * @see android.widget.ArrayAdapter#getView(int, android.view.View, * android.view.ViewGroup) */ override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { var convertView = convertView val holder: StatusHolder if (convertView == null || convertView.tag !is StatusHolder) { convertView = LayoutInflater.from(context).inflate(R.layout.list_item_status, parent, false) holder = StatusHolder() holder.title = convertView!!.findViewById(R.id.title) holder.statusText = convertView.findViewById(R.id.statusText) holder.size = convertView.findViewById(R.id.size) holder.free = convertView.findViewById(R.id.free) convertView.tag = holder } else { holder = convertView.tag as StatusHolder } holder.title!!.visibility = View.VISIBLE holder.title!!.text = resources.getString(mItems[position].nameRessource) holder.statusText!!.visibility = View.VISIBLE when (mItems[position].nameRessource) { R.string.status_epg_update_running, R.string.status_standby_blocked -> holder.statusText!!.setText(if (NumberUtils.toInt(mItems[position].value) == 0) R.string.no else R.string.yes) R.string.status_epg_before, R.string.status_epg_after -> holder.statusText!!.text = mItems[position].value + " " + mRes.getString(R.string.minutes) R.string.status_timezone -> { val timezone = NumberUtils.toInt(mItems[position].value) / 60 holder.statusText!!.text = mRes.getString(R.string.gmt) + (if (timezone > 0) " +" else "") + timezone } R.string.status_def_after_record -> holder.statusText!!.text = mRes.getStringArray(R.array.postRecoridngActions)[NumberUtils.toInt(mItems[position].value)] R.string.status_last_ui_access -> holder.statusText!!.text = DateUtils.secondsToReadableFormat(NumberUtils.toLong(mItems[position].value) * -1L) R.string.status_next_Rec, R.string.status_next_timer -> holder.statusText!!.text = DateUtils.secondsToReadableFormat(NumberUtils.toLong(mItems[position].value)) else -> holder.statusText!!.text = mItems[position].value } holder.size!!.visibility = View.GONE holder.free!!.visibility = View.GONE return convertView } } private fun refresh() { statusViewModel.getStatus(true) setListShown(false) } }
apache-2.0
8332dd7b7553e72f0b8da4cf12780570
43
197
0.669793
4.684238
false
false
false
false
abertschi/ad-free
app/src/main/java/ch/abertschi/adfree/model/TrackRepository.kt
1
1481
/* * Ad Free * Copyright (c) 2017 by abertschi, www.abertschi.ch * See the file "LICENSE" for the full license governing this code. */ package ch.abertschi.adfree.model import android.content.Context import android.content.SharedPreferences import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.info /** * Created by abertschi on 15.04.17. */ open class TrackRepository: AnkoLogger { private val context: Context private val TRACKS: String = "tracks" private var sharedPreferences: SharedPreferences constructor(context: Context, sharedPreferences: PreferencesFactory) { this.context = context this.sharedPreferences = sharedPreferences.getPreferences() } private fun getTracks(): MutableSet<String> { return sharedPreferences.getStringSet(TRACKS, HashSet<String>()) } open fun addTrack(content: String) { info("storing track: " + content) val tracks = getTracks() tracks.add(content) sharedPreferences.edit().putStringSet(TRACKS, tracks).apply() } open fun removeTrack(content: String) { val tracks = getTracks() tracks.remove(content) sharedPreferences.edit().putStringSet(TRACKS, tracks).apply() } open fun getAllTracks(): Set<String> { val tracks = getTracks() return tracks } open fun setAllTracks(tracks: Set<String>) { sharedPreferences.edit().putStringSet(TRACKS, tracks).apply() } }
apache-2.0
20d3e9304dd3ef198a3f27746e89aff1
26.444444
74
0.686698
4.515244
false
false
false
false
linheimx/ZimuDog
app/src/main/java/com/linheimx/zimudog/utils/Utils.kt
1
7478
package com.linheimx.zimudog.utils import android.Manifest import android.app.Application import android.content.Context import android.content.SharedPreferences import android.content.pm.PackageManager import android.content.res.AssetManager import android.graphics.Bitmap import android.graphics.Canvas import android.net.ConnectivityManager import android.net.NetworkInfo import android.os.Build import android.os.Environment import android.text.TextUtils import android.util.Log import android.view.View import com.linheimx.zimudog.App import com.linheimx.zimudog.m.bean.DirChange import com.linheimx.zimudog.utils.rxbus.RxBus_Behavior import com.liulishuo.filedownloader.FileDownloader import com.liulishuo.filedownloader.connection.FileDownloadUrlConnection import java.io.BufferedReader import java.io.ByteArrayOutputStream import java.io.File import java.io.FileInputStream import java.io.FileNotFoundException import java.io.FileReader import java.io.IOException import java.io.InputStream import java.lang.reflect.Method import java.net.Proxy /** * Created by x1c on 2017/5/4. */ object Utils { lateinit var rootDirPath: String /** * 检测网络是否连接 * * @return */ // 当前网络是连接的 // 当前所连接的网络可用 val isNetConnected: Boolean get() { val connectivity = App.get()!! .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager if (connectivity != null) { val info = connectivity.activeNetworkInfo if (info != null && info.isConnected) { if (info.state == NetworkInfo.State.CONNECTED) { return true } } } return false } fun setDefaultPath(context: Application, filePath: String) { val sp = context.getSharedPreferences("default_path", Context.MODE_PRIVATE) sp.edit().putString("root_dir", filePath).commit() rootDirPath = filePath RxBus_Behavior.post(DirChange()) } fun init(context: Application) { try { val dp = Environment.getExternalStorageDirectory().toString() + "/ZimuDog" val sp = context.getSharedPreferences("default_path", Context.MODE_PRIVATE) val filePath = sp.getString("root_dir", dp) rootDirPath = filePath Log.e("===>", filePath) val file = File(filePath) if (!file.exists()) { file.mkdir() } initRxDownloader(App.get()!!, filePath) } catch (e: Exception) { e.printStackTrace() } } fun initRxDownloader(context: Application, basePath: String) { FileDownloader.setupOnApplicationOnCreate(context) .connectionCreator(FileDownloadUrlConnection.Creator(FileDownloadUrlConnection.Configuration() .connectTimeout(15000) // set connection timeout. .readTimeout(15000) // set read timeout. .proxy(Proxy.NO_PROXY) // set proxy )) .commit() } /** * 文件大小---》显示 * * @param size * @return */ fun convertFileSize(size: Long): String { val kb: Long = 1024 val mb = kb * 1024 val gb = mb * 1024 if (size >= gb) { return String.format("%.1f GB", size.toFloat() / gb) } else if (size >= mb) { val f = size.toFloat() / mb return String.format(if (f > 100) "%.0f MB" else "%.1f MB", f) } else if (size >= kb) { val f = size.toFloat() / kb return String.format(if (f > 100) "%.0f KB" else "%.1f KB", f) } else return String.format("%d B", size) } fun loadBitmapFromView(v: View): Bitmap { val b = Bitmap.createBitmap(v.layoutParams.width, v.layoutParams.height, Bitmap.Config.ARGB_8888) val c = Canvas(b) v.layout(v.left, v.top, v.right, v.bottom) v.draw(c) return b } /** * Draw the view into a bitmap. */ fun getViewBitmap(v: View): Bitmap? { v.clearFocus() v.isPressed = false val willNotCache = v.willNotCacheDrawing() v.setWillNotCacheDrawing(false) // Reset the drawing cache background color to fully transparent // for the duration of this operation val color = v.drawingCacheBackgroundColor v.drawingCacheBackgroundColor = 0 if (color != 0) { v.destroyDrawingCache() } v.buildDrawingCache() val cacheBitmap = v.drawingCache if (cacheBitmap == null) { Log.e("v---> bm", "failed getViewBitmap($v)", RuntimeException()) return null } val bitmap = Bitmap.createBitmap(cacheBitmap) // Restore the view v.destroyDrawingCache() v.setWillNotCacheDrawing(willNotCache) v.drawingCacheBackgroundColor = color return bitmap } fun checkPermission(context: Context, permission: String): Boolean { var result = false if (Build.VERSION.SDK_INT >= 23) { try { val clazz = Class.forName("android.content.Context") val method = clazz.getMethod("checkSelfPermission", String::class.java) val rest = method.invoke(context, permission) as Int if (rest == PackageManager.PERMISSION_GRANTED) { result = true } else { result = false } } catch (e: Exception) { result = false } } else { val pm = context.packageManager if (pm.checkPermission(permission, context.packageName) == PackageManager.PERMISSION_GRANTED) { result = true } } return result } @Throws(IOException::class) fun getStringFromInputStream(ins: InputStream): String { val baos = ByteArrayOutputStream() val buffer = ByteArray(1024) var length: Int = ins.read(buffer) while (length != -1) { length = ins.read(buffer) baos.write(buffer, 0, length) } return baos.toString("UTF-8") } fun getStringFromAssetFile(asset: AssetManager, filename: String): String { var ins: InputStream? = null try { ins = asset.open(filename) return ins.bufferedReader().readText() } catch (e: Exception) { e.printStackTrace() return "" } finally { if (ins != null) { try { ins.close() } catch (e: IOException) { e.printStackTrace() } } } } fun getStringFromFile(file: File): String { var `is`: InputStream? = null try { `is` = FileInputStream(file) return getStringFromInputStream(`is`) } catch (e: Exception) { e.printStackTrace() return "" } finally { if (`is` != null) { try { `is`.close() } catch (e: IOException) { e.printStackTrace() } } } } }
apache-2.0
0e7afaafd209012b226b377e3d95a3a3
28.648
110
0.564355
4.514007
false
false
false
false
AntonovAlexander/activecore
designs/coregen/ariele/src/slave_pipe.kt
1
3305
package ariele import hwast.* import cyclix.STAGE_FC_MODE import pipex.* class slave_pipe(name : String, num_masters : Int, req_vartype : hw_type, resp_vartype : hw_type, rob_size : Int) : pipex.Pipeline(name, PIPELINE_FC_MODE.STALLABLE) { var master_ifs = ArrayList<hw_scopipe_if>() var master_handle = scopipe_handle("master", req_vartype, resp_vartype) var slave_if = mcopipe_if("slave", req_vartype, resp_vartype, 4) var slave_handle = mcopipe_handle(slave_if) var mreq_we = ulocal("mreq_we", 0, 0, "0") var mreq_wdata = local("mreq_wdata", req_vartype, "0") var rr_arb = uglobal("rr_arb", (GetWidthToContain(num_masters)-1), 0, "0") var rdata = local("rdata", resp_vartype, "0") var mcmd_accepted = ulocal("mcmd_accepted", 0, 0, "0") var scmd_accepted = ulocal("scmd_accepted", 0, 0, "0") init { for (mnum in 0 until num_masters) { master_ifs.add(scopipe_if("master" + mnum, req_vartype, resp_vartype)) } var ARB = stage_handler("ARB", STAGE_FC_MODE.BUFFERED) var REQ = stage_handler("REQ", STAGE_FC_MODE.BUFFERED) var RESP = stage_handler("RESP", STAGE_FC_MODE.BUFFERED, rob_size) ARB.begin() run { clrif() for (mnum in 0 until num_masters) { begelsif(eq2(rr_arb, mnum)) run { clrif() for (mnum_internal in mnum until (mnum + num_masters)) { var mnum_rr = mnum_internal if (mnum_rr >= num_masters) mnum_rr -= num_masters var mnum_rr_next = mnum_rr + 1 if (mnum_rr_next >= num_masters) mnum_rr_next -= num_masters begif(!mcmd_accepted) run { mcmd_accepted.accum(master_ifs[mnum_rr].req(master_handle, mreq_we, mreq_wdata)) mreq_we.accum(mreq_we) mreq_wdata.accum(mreq_wdata) begif(mcmd_accepted) run { rr_arb.assign(mnum_rr_next) }; endif() }; endif() } }; endif() } begif(!mcmd_accepted) run { pstall() }; endif() }; endstage() REQ.begin() run { // sending command begif(!scmd_accepted) run { scmd_accepted.accum(slave_if.req(slave_handle, mreq_we, mreq_wdata)) }; endif() begif(!scmd_accepted) run { pstall() }; endif() begif(mreq_we) run { pkill() }; endif() }; endstage() RESP.begin() run { begif(slave_handle.resp(rdata)) run { master_handle.resp(rdata) }; endif() begelse() run { pstall() }; endif() }; endstage() } }
apache-2.0
68e1820235d7b7fe3495f10aa5e1f026
30.47619
108
0.445386
3.764237
false
false
false
false
google/android-fhir
catalog/src/main/java/com/google/android/fhir/catalog/DemoQuestionnaireViewModel.kt
1
2778
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.fhir.catalog import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.viewModelScope import ca.uhn.fhir.context.FhirContext import ca.uhn.fhir.context.FhirVersionEnum import com.google.android.fhir.catalog.DemoQuestionnaireFragment.Companion.QUESTIONNAIRE_FILE_PATH_KEY import com.google.android.fhir.catalog.DemoQuestionnaireFragment.Companion.QUESTIONNAIRE_FILE_WITH_VALIDATION_PATH_KEY import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.hl7.fhir.r4.model.QuestionnaireResponse class DemoQuestionnaireViewModel(application: Application, private val state: SavedStateHandle) : AndroidViewModel(application) { private val backgroundContext = viewModelScope.coroutineContext private var questionnaireJson: String? = null private var questionnaireWithValidationJson: String? = null init { viewModelScope.launch { getQuestionnaireJson() // TODO remove check once all files are added if (!state.get<String>(QUESTIONNAIRE_FILE_WITH_VALIDATION_PATH_KEY).isNullOrEmpty()) { getQuestionnaireWithValidationJson() } } } fun getQuestionnaireResponseJson(response: QuestionnaireResponse) = FhirContext.forCached(FhirVersionEnum.R4).newJsonParser().encodeResourceToString(response) suspend fun getQuestionnaireJson(): String { return withContext(backgroundContext) { if (questionnaireJson == null) { questionnaireJson = readFileFromAssets(state[QUESTIONNAIRE_FILE_PATH_KEY]!!) } questionnaireJson!! } } suspend fun getQuestionnaireWithValidationJson(): String { return withContext(backgroundContext) { if (questionnaireWithValidationJson == null) { questionnaireWithValidationJson = readFileFromAssets(state[QUESTIONNAIRE_FILE_WITH_VALIDATION_PATH_KEY]!!) } questionnaireWithValidationJson!! } } private suspend fun readFileFromAssets(filename: String) = withContext(backgroundContext) { getApplication<Application>().assets.open(filename).bufferedReader().use { it.readText() } } }
apache-2.0
cab481faf3f09de32a553066d084bc27
37.054795
118
0.766019
4.676768
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/core/src/templates/kotlin/core/macos/templates/ObjC.kt
4
57805
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package core.macos.templates import org.lwjgl.generator.* import core.macos.* val objc_runtime = "ObjCRuntime".nativeClass( Module.CORE_MACOS, nativeSubPath = "macos", binding = simpleBinding(Module.CORE_MACOS, "objc") ) { nativeImport("<objc/objc-runtime.h>") documentation = """ Native bindings to the Objective-C Runtime. Due to the nature of the {@code objc_msgSend*} functions, they are not directly exposed in this binding. Advanced users with good understanding of the complexity involved with using these functions, may access them via the ObjCRuntime#getLibrary() method: ${codeBlock(""" SharedLibrary objc = ObjCRuntime.getLibrary(); long objc_msgSend = objc.getFunctionAddress("objc_msgSend"); // example usage long NSThread = objc_getClass("NSThread"); long currentThread = invokePPP(NSThread, sel_getUid("currentThread"), objc_msgSend);""")} The safe way to use objc_msgSend in C code is to cast it to an appropriate function pointer. This is exactly what the {@link org.lwjgl.system.JNI JNI} class does. If a particular function signature is not available, {@link org.lwjgl.system.libffi.LibFFI LibFFI} may be used to invoke it. The functions not exposed are: ${ul( "objc_msgSend", "objc_msgSend_stret", "objc_msgSendSuper", "objc_msgSendSuper_stret" )} """ LongConstant( "Nil value.", "nil"..0L ) ByteConstant( "Boolean values.", "YES".."1", "NO".."0" ) CharConstant( "Types.", "_C_ID"..'@', "_C_CLASS"..'#', "_C_SEL"..':', "_C_CHR"..'c', "_C_UCHR"..'C', "_C_SHT"..'s', "_C_USHT"..'S', "_C_INT"..'i', "_C_UINT"..'I', "_C_LNG"..'l', "_C_ULNG"..'L', "_C_LNG_LNG"..'q', "_C_ULNG_LNG"..'Q', "_C_FLT"..'f', "_C_DBL"..'d', "_C_BFLD"..'b', "_C_BOOL"..'B', "_C_VOID"..'v', "_C_UNDEF"..'?', "_C_PTR"..'^', "_C_CHARPTR"..'*', "_C_ATOM"..'%', "_C_ARY_B"..'[', "_C_ARY_E"..']', "_C_UNION_B"..'(', "_C_UNION_E"..')', "_C_STRUCT_B"..'{', "_C_STRUCT_E"..'}', "_C_VECTOR"..'!', "_C_CONST"..'r' ) // Working with Instances id( "object_copy", "Returns a copy of a given object.", id("obj", "an Objective-C object"), size_t("size", "the size of the object {@code obj}"), returnDoc = "a copy of obj" ) id( "object_dispose", "Frees the memory occupied by a given object.", id("obj", "an Objective-C object"), returnDoc = "#nil" ) Class( "object_getClass", "Returns the class of an object.", nullable..id("obj", "an Objective-C object"), returnDoc = "the class object of which object is an instance, or Nil if {@code obj} is #nil" ) Class( "object_setClass", "Sets the class of an object.", nullable..id("obj", "the object to modify"), Class("cls", "a class object"), returnDoc = "the previous value of object's class, or Nil if {@code obj} is #nil" ) charUTF8.const.p( "object_getClassName", "Returns the class name of a given object.", nullable..id("obj", "an Objective-C object"), returnDoc = "the name of the class of which {@code obj} is an instance" ) opaque_p( "object_getIndexedIvars", """ This function returns a pointer to any extra bytes allocated with the instance (as specified by #class_createInstance() with extraBytes&gt;0). This memory follows the object's ordinary ivars, but may not be adjacent to the last ivar. The returned pointer is guaranteed to be pointer-size aligned, even if the area following the object's last ivar is less aligned than that. Alignment greater than pointer-size is never guaranteed, even if the area following the object's last ivar is more aligned than that. In a garbage-collected environment, the memory is scanned conservatively. """, id("obj", "an Objective-C object"), returnDoc = """ a pointer to any extra bytes allocated with {@code obj}. If {@code obj} was not allocated with any extra bytes, then dereferencing the returned pointer is undefined. """ ) id( "object_getIvar", "Reads the value of an instance variable in an object.", nullable..id("obj", "the object containing the instance variable whose value you want to read"), Ivar("ivar", "the Ivar describing the instance variable whose value you want to read"), returnDoc = "the value of the instance variable specified by {@code ivar}, or #nil if {@code obj} is #nil" ) void( "object_setIvar", """ Sets the value of an instance variable in an object. object_setIvar is faster than #object_setInstanceVariable() if the Ivar for the instance variable is already known. """, id("obj", "the object containing the instance variable whose value you want to set"), Ivar("ivar", "the Ivar describing the instance variable whose value you want to set"), id("value", "the new value for the instance variable") ) Ivar( "object_setInstanceVariable", "Changes the value of an instance variable of a class instance.", id("obj", "a pointer to an instance of a class. Pass the object containing the instance variable whose value you wish to modify"), charUTF8.const.p("name", "a C string. Pass the name of the instance variable whose value you wish to modify"), Unsafe..void.p("value", "the new value for the instance variable"), returnDoc = "a pointer to the Ivar data structure that defines the type and name of the instance variable specified by name" ) Ivar( "object_getInstanceVariable", "Obtains the value of an instance variable of a class instance.", id("obj", "a pointer to an instance of a class. Pass the object containing the instance variable whose value you wish to obtain"), charUTF8.const.p("name", "a C string. Pass the name of the instance variable whose value you wish to obtain"), Check(1)..void.p.p("outValue", "on return, contains a pointer to the value of the instance variable"), returnDoc = "a pointer to the Ivar data structure that defines the type and name of the instance variable specified by name" ) // Obtaining Class Definitions Class( "objc_getClass", """ Returns the class definition of a specified class. objc_getClass is different from #objc_lookUpClass() in that if the class is not registered, objc_getClass calls the class handler callback and then checks a second time to see whether the class is registered. objc_lookUpClass does not call the class handler callback. """, charUTF8.const.p("name", "the name of the class to look up"), returnDoc = "the Class object for the named class, or #nil if the class is not registered with the Objective-C runtime" ) Class( "objc_getMetaClass", """ Returns the metaclass definition of a specified class. If the definition for the named class is not registered, this function calls the class handler callback and then checks a second time to see if the class is registered. However, every class definition must have a valid metaclass definition, and so the metaclass definition is always returned, whether it’s valid or not. """, charUTF8.const.p("name", "the name of the class to look up"), returnDoc = "the Class object for the metaclass of the named class, or #nil if the class is not registered with the Objective-C runtime" ) Class( "objc_lookUpClass", """ Returns the class definition of a specified class. #objc_getClass() is different from this function in that if the class is not registered, objc_getClass calls the class handler callback and then checks a second time to see whether the class is registered. This function does not call the class handler callback. """, charUTF8.const.p("name", "the name of the class to look up"), returnDoc = "the Class object for the named class, or #nil if the class is not registered with the Objective-C runtime" ) Class( "objc_getRequiredClass", """ Returns the class definition of a specified class. This function is the same as #objc_getClass(), but kills the process if the class is not found. This function is used by ZeroLink, where failing to find a class would be a compile-time link error without ZeroLink. """, charUTF8.const.p("name", "the name of the class to look up"), returnDoc = "the Class object for the named class" ) int( "objc_getClassList", """ Obtains the list of registered class definitions. The Objective-C runtime library automatically registers all the classes defined in your source code. You can create class definitions at runtime and register them with the #objc_allocateClassPair() and #objc_registerClassPair() functions. <h5>Special Considerations</h5> You cannot assume that class objects you get from this function are classes that inherit from NSObject, so you cannot safely call any methods on such classes without detecting that the method is implemented first. """, nullable..Class.p( "buffer", """ an array of Class values. On output, each Class value points to one class definition, up to either {@code bufferCount} or the total number of registered classes, whichever is less. You can pass #NULL to obtain the total number of registered class definitions without actually retrieving any class definitions. """ ), AutoSize("buffer")..int( "bufferCount", """ the number of pointers for which you have allocated space in buffer. On return, this function fills in only this number of elements. If this number is less than the number of registered classes, this function returns an arbitrary subset of the registered classes. """ ), returnDoc = "an integer value indicating the total number of registered classes" ) Class.p( "objc_copyClassList", "Creates and returns a list of pointers to all registered class definitions.", AutoSizeResult..unsigned_int.p( "outCount", "an integer pointer used to store the number of classes returned by this function in the list. This parameter may be #nil" ), returnDoc = "a #nil terminated array of classes. You must free the array with free()" ) // Working with Classes charUTF8.const.p( "class_getName", "Returns the name of a class.", nullable..Class("cls", "a class object"), returnDoc = "the name of the class, or the empty string if cls is Nil" ) BOOL( "class_isMetaClass", "Returns a Boolean value that indicates whether a class object is a metaclass.", nullable..Class("cls", "a class object"), returnDoc = "#YES if cls is a metaclass, #NO if cls is a non-meta class, #NO if cls is Nil" ) Class( "class_getSuperclass", "Returns the superclass of a class.", nullable..Class("cls", "a class object"), returnDoc = "the superclass of the class, or Nil if cls is a root class, or Nil if cls is Nil" ) // class_setSuperclass int( "class_getVersion", """ Returns the version number of a class definition. You can use the version number of the class definition to provide versioning of the interface that your class represents to other classes. This is especially useful for object serialization (that is, archiving of the object in a flattened form), where it is important to recognize changes to the layout of the instance variables in different class-definition versions. Classes derived from the Foundation framework NSObject class can obtain the class-definition version number using the getVersion class method, which is implemented using the class_getVersion function. """, Class("cls", "a pointer to an Class data structure. Pass the class definition for which you wish to obtain the version"), returnDoc = "an integer indicating the version number of the class definition" ) void( "class_setVersion", """ Sets the version number of a class definition. You can use the version number of the class definition to provide versioning of the interface that your class represents to other classes. This is especially useful for object serialization (that is, archiving of the object in a flattened form), where it is important to recognize changes to the layout of the instance variables in different class-definition versions. Classes derived from the Foundation framework NSObject class can set the class-definition version number using the setVersion: class method, which is implemented using the class_setVersion function. """, Class("cls", "a pointer to an Class data structure. Pass the class definition for which you wish to set the version"), int("version", "the new version number of the class definition") ) size_t( "class_getInstanceSize", "Returns the size of instances of a class.", nullable..Class("cls", "a class object"), returnDoc = "the size in bytes of instances of the class {@code cls}, or 0 if {@code cls} is Nil" ) Ivar( "class_getInstanceVariable", "Returns the Ivar for a specified instance variable of a given class.", Class("cls", "the class whose instance variable you wish to obtain"), charUTF8.const.p("name", "the name of the instance variable definition to obtain"), returnDoc = "a pointer to an Ivar data structure containing information about the instance variable specified by name" ) Ivar( "class_getClassVariable", "Returns the Ivar for a specified class variable of a given class.", Class("cls", "the class definition whose class variable you wish to obtain"), charUTF8.const.p("name", "the name of the class variable definition to obtain"), returnDoc = "a pointer to an Ivar data structure containing information about the class variable specified by name" ) Ivar.p( "class_copyIvarList", "Describes the instance variables declared by a class.", nullable..Class("cls", "the class to inspect"), AutoSizeResult..unsigned_int.p( "outCount", "on return, contains the length of the returned array. If {@code outCount} is #NULL, the length is not returned" ), returnDoc = """ an array of pointers of type Ivar describing the instance variables declared by the class. Any instance variables declared by superclasses are not included. The array contains {@code *outCount} pointers followed by a #NULL terminator. You must free the array with free(). If the class declares no instance variables, or {@code cls} is Nil, #NULL is returned and {@code *outCount} is 0. """ ) Method( "class_getInstanceMethod", """ Returns a specified instance method for a given class. Note that this function searches superclasses for implementations, whereas #class_copyMethodList() does not. """, Class("cls", "the class you want to inspect"), SEL("name", "the selector of the method you want to retrieve"), returnDoc = """ the method that corresponds to the implementation of the selector specified by aSelector for the class specified by {@code cls}, or #NULL if the specified class or its superclasses do not contain an instance method with the specified selector. """ ) Method( "class_getClassMethod", """ Returns a pointer to the data structure describing a given class method for a given class. Note that this function searches superclasses for implementations, whereas #class_copyMethodList() does not. """, Class("cls", "a pointer to a class definition. Pass the class that contains the method you want to retrieve"), SEL("name", "a pointer of type SEL. Pass the selector of the method you want to retrieve"), returnDoc = """ a pointer to the Method data structure that corresponds to the implementation of the selector specified by {@code name} for the class specified by {@code cls}, or #NULL if the specified class or its superclasses do not contain a class method with the specified selector. """ ) IMP( "class_getMethodImplementation", """ Returns the function pointer that would be called if a particular message were sent to an instance of a class. class_getMethodImplementation may be faster than {@code method_getImplementation(class_getInstanceMethod(cls, name))}. The function pointer returned may be a function internal to the runtime instead of an actual method implementation. For example, if instances of the class do not respond to the selector, the function pointer returned will be part of the runtime's message forwarding machinery. """, nullable..Class("cls", "the class you want to inspect"), SEL("name", "a selector"), returnDoc = "the function pointer that would be called if {@code [object name]} were called with an instance of the class, or #NULL if {@code cls} is Nil" ) // class_getMethodImplementation_stret BOOL( "class_respondsToSelector", """ Returns a Boolean value that indicates whether instances of a class respond to a particular selector. You should usually use NSObject's respondsToSelector: or instancesRespondToSelector: methods instead of this function. """, Class("cls", "the class you want to inspect"), SEL("name", "a selector"), returnDoc = "#YES if instances of the class respond to the selector, otherwise #NO" ) Method.p( "class_copyMethodList", "Describes the instance methods implemented by a class.", nullable..Class("cls", "the class you want to inspect"), AutoSizeResult..unsigned_int.p( "outCount", "on return, contains the length of the returned array. If {@code outCount} is #NULL, the length is not returned" ), returnDoc = """ an array of pointers of type Method describing the instance methods implemented by the class—any instance methods implemented by superclasses are not included. The array contains {@code *outCount} pointers followed by a #NULL terminator. You must free the array with free(). If {@code cls} implements no instance methods, or {@code cls} is Nil, returns #NULL and {@code *outCount} is 0. """ ) BOOL( "class_conformsToProtocol", """ Returns a Boolean value that indicates whether a class conforms to a given protocol. You should usually use NSObject's conformsToProtocol: method instead of this function. """, Class("cls", "the class you want to inspect"), Protocol.p("protocol", "a protocol"), returnDoc = "#YES if {@code cls} conforms to {@code protocol}, otherwise #NO" ) Protocol.p.p( "class_copyProtocolList", "Describes the protocols adopted by a class.", nullable..Class("cls", "the class you want to inspect"), AutoSizeResult..unsigned_int.p( "outCount", "on return, contains the length of the returned array. If {@code outCount} is #NULL, the length is not returned" ), returnDoc = """ an array of pointers of type Protocol* describing the protocols adopted by the class. Any protocols adopted by superclasses or other protocols are not included. The array contains {@code *outCount} pointers followed by a #NULL terminator. You must free the array with free(). If {@code cls} adopts no protocols, or {@code cls} is Nil, returns #NULL and {@code *outCount} is 0. """ ) objc_property_t( "class_getProperty", "Returns a property with a given name of a given class.", nullable..Class("cls", "the class you want to inspect"), charUTF8.const.p("name", "a C string. Pass the name of the instance variable whose value you wish to modify."), returnDoc = """ a pointer of type {@code objc_property_t} describing the property, or #NULL if the class does not declare a property with that name, or #NULL if {@code cls} is Nil. """ ) objc_property_t.p( "class_copyPropertyList", "Describes the properties declared by a class.", nullable..Class("cls", "the class you want to inspect"), AutoSizeResult..unsigned_int.p( "outCount", "on return, contains the length of the returned array. If {@code outCount} is #NULL, the length is not returned" ), returnDoc = """ an array of pointers of type {@code objc_property_t} describing the properties declared by the class. Any properties declared by superclasses are not included. The array contains {@code *outCount} pointers followed by a #NULL terminator. You must free the array with free(). If {@code cls} declares no properties, or {@code cls} is Nil, returns #NULL and {@code *outCount} is 0. """ ) uint8_tASCII.const.p( "class_getIvarLayout", "Returns a description of the Ivar layout for a given class.", Class("cls", "the class to inspect"), returnDoc = "a description of the Ivar layout for {@code cls}" ) uint8_tASCII.const.p( "class_getWeakIvarLayout", "Returns a description of the layout of weak Ivars for a given class.", Class("cls", "the class to inspect"), returnDoc = "a description of the layout of the weak Ivars for {@code cls}" ) BOOL( "class_addMethod", """ Adds a new method to a class with a given name and implementation. <h5>Discussion</h5> class_addMethod will add an override of a superclass's implementation, but will not replace an existing implementation in this class. To change an existing implementation, use #method_setImplementation(). An Objective-C method is simply a C function that takes at least two arguments &ndash; {@code self} and {@code _cmd}. For example, given the following function: ${codeBlock(""" void myMethodIMP(id self, SEL _cmd) { // implementation .... }""")} you can dynamically add it to a class as a method (called {@code resolveThisMethodDynamically}) like this: ${codeBlock("""class_addMethod([self class], @selector(resolveThisMethodDynamically), (IMP) myMethodIMP, "v@:");""")} """, Class("cls", "the class to which to add a method"), SEL("name", "a selector that specifies the name of the method being added"), IMP( "imp", "a function which is the implementation of the new method. The function must take at least two arguments &ndash; {@code self} and {@code _cmd}." ), charUTF8.const.p( "types", """ an array of characters that describe the types of the arguments to the method. For possible values, see <em>Objective-C Runtime Programming Guide</em> &gt; Type Encodings in Objective-C Runtime Programming Guide. Since the function must take at least two arguments &ndash; {@code self} and {@code _cmd}, the second and third characters must be “@:” (the first character is the return type). """ ), returnDoc = "#YES if the method was added successfully, otherwise #NO (for example, the class already contains a method implementation with that name)" ) IMP( "class_replaceMethod", """ Replaces the implementation of a method for a given class. <h5>Discussion</h5> This function behaves in two different ways: ${ul( """ If the method identified by name does not yet exist, it is added as if class_addMethod were called. The type encoding specified by types is used as given. """, """ If the method identified by name does exist, its IMP is replaced as if method_setImplementation were called. The type encoding specified by types is ignored. """ )} """, Class("cls", "the class you want to modify"), SEL("name", "a selector that identifies the method whose implementation you want to replace"), IMP( "imp", "the new implementation for the method identified by {@code name} for the class identified by {@code cls}" ), charUTF8.const.p( "types", """ an array of characters that describe the types of the arguments to the method. For possible values, see <em>Objective-C Runtime Programming Guide</em> &gt; Type Encodings in Objective-C Runtime Programming Guide. Since the function must take at least two arguments &ndash; {@code self} and {@code _cmd}, the second and third characters must be “@:” (the first character is the return type). """ ), returnDoc = "the previous implementation of the method identified by {@code name} for the class identified by {@code cls}" ) BOOL( "class_addIvar", """ Adds a new instance variable to a class. This function may only be called after #objc_allocateClassPair() and before #objc_registerClassPair(). Adding an instance variable to an existing class is not supported. The class must not be a metaclass. Adding an instance variable to a metaclass is not supported. The instance variable's minimum alignment in bytes is {@code 1<<align}. The minimum alignment of an instance variable depends on the ivar's type and the machine architecture. For variables of any pointer type, pass {@code log2(sizeof(pointer_type))}. """, Class("cls", ""), charUTF8.const.p("name", ""), size_t("size", ""), uint8_t("alignment", ""), charUTF8.const.p("types", ""), returnDoc = "#YES if the instance variable was added successfully, otherwise #NO (for example, the class already contains an instance variable with that name)" ) BOOL( "class_addProtocol", "Adds a protocol to a class.", Class("cls", "the class to modify"), Protocol.p("protocol", "the protocol to add to {@code cls}"), returnDoc = "#YES if the protocol was added successfully, otherwise #NO (for example, the class already conforms to that protocol)" ) BOOL( "class_addProperty", "Adds a property to a class.", Class("cls", "the class to modify"), charUTF8.const.p("name", "the name of the property"), objc_property_attribute_t.const.p("attributes", "an array of property attributes"), AutoSize("attributes")..unsigned_int("attributeCount", "the number of attributes in {@code attributes}"), returnDoc = "#YES if the property was added successfully; otherwise #NO (for example, this function returns #NO if the class already has that property)" ) void( "class_replaceProperty", "Replaces a property of a class.", Class("cls", "the class to modify"), charUTF8.const.p("name", "the name of the property"), objc_property_attribute_t.const.p("attributes", "an array of property attributes"), AutoSize("attributes")..unsigned_int("attributeCount", "the number of attributes in {@code attributes}") ) void( "class_setIvarLayout", "Sets the Ivar layout for a given class.", Class("cls", "the class to modify"), uint8_tASCII.const.p("layout", "the layout of the Ivars for {@code cls}") ) void( "class_setWeakIvarLayout", "Sets the layout for weak Ivars for a given class.", Class("cls", "the class to modify"), uint8_tASCII.const.p("layout", "the layout of the weak Ivars for {@code cls}") ) // Instantiating Classes id( "class_createInstance", "Creates an instance of a class, allocating memory for the class in the default malloc memory zone.", Class("cls", "the class that you want to allocate an instance of"), size_t( "extraBytes", """ an integer indicating the number of extra bytes to allocate. The additional bytes can be used to store additional instance variables beyond those defined in the class definition. """ ), returnDoc = "an instance of the class {@code cls}" ) id( "objc_constructInstance", "Creates an instance of a class at the specified location.", nullable..Class("cls", "the class that you want to allocate an instance of"), Check("class_getInstanceSize(cls)", debug = true)..nullable..void.p( "bytes", """ the location at which to allocate an instance of the {@code cls} class. {@code bytes} must point to at least {@code class_getInstanceSize(cls)} bytes of well-aligned, zero-filled memory. """ ), returnDoc = "an instance of the class {@code cls} at {@code bytes}, if successful; otherwise #nil (for example, if {@code cls} or {@code bytes} are themselves #nil)" ) opaque_p( "objc_destructInstance", """ Destroys an instance of a class without freeing memory and removes any of its associated references. This method does nothing if obj is #nil. <h5>Important</h5> The garbage collector does not call this function. As a result, if you edit this function, you should also edit finalize. That said, Core Foundation and other clients do call this function under garbage collection. """, id("obj", "the instance to destroy") ) // Adding Classes Class( "objc_allocateClassPair", """ Creates a new class and metaclass. You can get a pointer to the new metaclass by calling {@code object_getClass(newClass)}. To create a new class, start by calling objc_allocateClassPair. Then set the class's attributes with functions like #class_addMethod() and #class_addIvar(). When you are done building the class, call #objc_registerClassPair(). The new class is now ready for use. Instance methods and instance variables should be added to the class itself. Class methods should be added to the metaclass. """, nullable..Class("superclass", "the class to use as the new class's superclass, or Nil to create a new root class"), charUTF8.const.p("name", "the string to use as the new class's name. The string will be copied."), size_t("extraBytes", "the number of bytes to allocate for indexed ivars at the end of the class and metaclass objects. This should usually be 0."), returnDoc = "the new class, or Nil if the class could not be created (for example, the desired name is already in use)" ) void( "objc_registerClassPair", "Registers a class that was allocated using #objc_allocateClassPair().", Class("cls", "the class you want to register") ) void( "objc_disposeClassPair", """ Destroys a class and its associated metaclass. Do not call this function if instances of the {@code cls} class or any subclass exist. """, Class("cls", "the class to be destroyed. This class must have been allocated using #objc_allocateClassPair().") ) // Working with Methods SEL( "method_getName", """ Returns the name of a method. To get the method name as a C string, call {@code sel_getName(method_getName(method))}. """, Method("m", "the method to inspect"), returnDoc = "a pointer of type SEL" ) IMP( "method_getImplementation", "Returns the implementation of a method.", Method("m", "the method to inspect"), returnDoc = "a function pointer of type IMP" ) charUTF8.const.p( "method_getTypeEncoding", "Returns a string describing a method's parameter and return types.", Method("m", "the method to inspect"), returnDoc = "a C string. The string may be #NULL" ) unsigned_int( "method_getNumberOfArguments", "Returns the number of arguments accepted by a method.", Method("m", "a pointer to a Method data structure. Pass the method in question."), returnDoc = "an integer containing the number of arguments accepted by the given method" ) charUTF8.p( "method_copyReturnType", "Returns a string describing a method's return type.", Method("m", "the method to inspect"), returnDoc = "a C string describing the return type. You must free the string with free()." ) Code( javaFinally = statement(" if ($RESULT != NULL) org.lwjgl.system.libc.LibCStdlib.nfree($RESULT);") )..charUTF8.p( "method_copyArgumentType", "Returns a string describing a single parameter type of a method.", Method("m", "the method to inspect"), unsigned_int("index", "the index of the parameter to inspect"), returnDoc = """ a C string describing the type of the parameter at index {@code index}, or #NULL if method has no parameter index {@code index}. You must free the string with free(). """ ) void( "method_getReturnType", """ Returns by reference a string describing a method's return type. The method's return type string is copied to {@code dst}. {@code dst} is filled as if {@code strncpy(dst, parameter_type, dst_len)} were called. """, Method("m", "the method to inspect"), ReturnParam..charUTF8.p("dst", "the reference string to store the description"), AutoSize("dst")..size_t("dst_len", "the maximum number of characters that can be stored in {@code dst}") ) void( "method_getArgumentType", """ Returns by reference a string describing a single parameter type of a method. The parameter type string is copied to {@code dst}. {@code dst} is filled as if {@code strncpy(dst, parameter_type, dst_len)} were called. If the method contains no parameter with that index, {@code dst} is filled as if {@code strncpy(dst, "", dst_len)} were called. """, Method("m", "the method you want to inquire about"), unsigned_int("index", "the index of the parameter you want to inquire about"), ReturnParam..charUTF8.p("dst", "the reference string to store the description"), AutoSize("dst")..size_t("dst_len", "the maximum number of characters that can be stored in {@code dst}") ) IMP( "method_setImplementation", "Sets the implementation of a method.", Method("m", "the method for which to set an implementation"), IMP("imp", "the implemention to set to this method"), returnDoc = "the previous implementation of the method" ) void( "method_exchangeImplementations", "Exchanges the implementations of two methods.", Method("m1", "the method to exchange with second method"), Method("m2", "the method to exchange with first method") ) // Working with Instance Variables charUTF8.const.p( "ivar_getName", "Returns the name of an instance variable.", Ivar("v", "the instance variable"), returnDoc = "a C string containing the instance variable's name" ) charUTF8.const.p( "ivar_getTypeEncoding", "Returns the type string of an instance variable.", Ivar("v", "the instance variable"), returnDoc = "a C string containing the instance variable's type encoding" ) ptrdiff_t( "ivar_getOffset", """ Returns the offset of an instance variable. For instance variables of type {@code id} or other object types, call #object_getIvar() and #object_setIvar() instead of using this offset to access the instance variable data directly. """, Ivar("v", "the instance variable"), returnDoc = "the offset of {@code v}" ) // Working with Properties charUTF8.const.p( "property_getName", "Returns the name of a property.", objc_property_t("property", "the property you want to inquire about"), returnDoc = "a C string containing the property's name" ) charUTF8.const.p( "property_getAttributes", "Returns the attribute string of a property.", objc_property_t("property", "a property"), returnDoc = "a C string containing the property's attributes" ) objc_property_attribute_t.p( "property_copyAttributeList", "Returns an array of property attributes for a given property.", objc_property_t("property", "the property whose attributes you want to copy"), AutoSizeResult..unsigned_int.p("outCount", "the number of attributes returned in the array"), returnDoc = "an array of property attributes. You must free the array with free()." ) Code( javaFinally = statement(" if ($RESULT != NULL) org.lwjgl.system.libc.LibCStdlib.nfree($RESULT);") )..charUTF8.p( "property_copyAttributeValue", "Returns the value of a property attribute given the attribute name.", objc_property_t("property", "the property whose value you are interested in"), charUTF8.const.p("attributeName", "a C string representing the name of the attribute"), returnDoc = """ The value string of the {@code attributeName} attribute, if one exists in {@code property}; otherwise, #nil. You must free the returned value string with free(). """ ) // Working with Protocols Protocol.p( "objc_getProtocol", """ Returns a specified protocol. This function acquires the runtime lock. """, charUTF8.const.p("name", "the name of a protocol"), returnDoc = "the protocol named {@code name}{, or #NULL if no protocol named name could be found" ) Protocol.p.p( "objc_copyProtocolList", "Returns an array of all the protocols known to the runtime.", AutoSizeResult..unsigned_int.p("outCount", "upon return, contains the number of protocols in the returned array"), returnDoc = """ a C array of all the protocols known to the runtime. The array contains {@code *outCount} pointers followed by a #NULL terminator. You must free the list with free(). """ ) BOOL( "protocol_conformsToProtocol", """ Returns a Boolean value that indicates whether one protocol conforms to another protocol. <h5>Discussion</h5> One protocol can incorporate other protocols using the same syntax that classes use to adopt a protocol: {@code @protocol ProtocolName < protocol list >} All the protocols listed between angle brackets are considered part of the {@code ProtocolName} protocol. """, Protocol.p("proto", "a protocol"), Protocol.p("other", "a protocol"), returnDoc = "#YES if {@code proto} conforms to {@code other}, otherwise #NO" ) BOOL( "protocol_isEqual", "Returns a Boolean value that indicates whether two protocols are equal.", Protocol.p("proto", "a protocol"), Protocol.p("other", "a protocol"), returnDoc = "#YES if proto is the same as other, otherwise #NO" ) charUTF8.const.p( "protocol_getName", "Returns a the name of a protocol.", Protocol.p("p", "a protocol"), returnDoc = "the name of the protocol {@code p} as a C string" ) objc_method_description( "protocol_getMethodDescription", "Returns a method description structure for a specified method of a given protocol.", Protocol.p("p", "a protocol"), SEL("aSel", "a selector"), BOOL("isRequiredMethod", "a Boolean value that indicates whether {@code aSel} is a required method"), BOOL("isInstanceMethod", "a Boolean value that indicates whether {@code aSel} is a instance method"), returnDoc = """ an objc_method_description structure that describes the method specified by {@code aSel}, {@code isRequiredMethod}, and {@code isInstanceMethod} for the protocol {@code p}. If the protocol does not contain the specified method, returns an objc_method_description structure with the value {@code {NULL, NULL}}. """ ) objc_method_description.p( "protocol_copyMethodDescriptionList", """ Returns an array of method descriptions of methods meeting a given specification for a given protocol. Methods in other protocols adopted by this protocol are not included. """, Protocol.p("p", "a protocol"), BOOL("isRequiredMethod", "a Boolean value that indicates whether returned methods should be required methods (pass #YES to specify required methods)"), BOOL("isInstanceMethod", "a Boolean value that indicates whether returned methods should be instance methods (pass #YES to specify instance methods)"), AutoSizeResult..unsigned_int.p("outCount", "upon return, contains the number of method description structures in the returned array"), returnDoc = """ a C array of objc_method_description structures containing the names and types of {@code p}'s methods specified by {@code isRequiredMethod} and {@code isInstanceMethod}. The array contains {@code *outCount} pointers followed by a #NULL terminator. You must free the list with free(). If the protocol declares no methods that meet the specification, #NULL is returned and {@code *outCount} is 0. """ ) objc_property_t( "protocol_getProperty", "Returns the specified property of a given protocol.", Protocol.p("proto", "a protocol"), charUTF8.const.p("name", "the name of a property"), BOOL("isRequiredProperty", "a Boolean value that indicates whether {@code name} is a required property"), BOOL("isInstanceProperty", "a Boolean value that indicates whether {@code name} is a instance property"), returnDoc = """ the property specified by {@code name}, {@code isRequiredProperty}, and {@code isInstanceProperty} for {@code proto}, or #NULL if none of {@code proto}'s properties meets the specification """ ) objc_property_t.p( "protocol_copyPropertyList", "Returns an array of the properties declared by a protocol.", Protocol.p("proto", "a protocol"), AutoSizeResult..unsigned_int.p("outCount", "upon return, contains the number of elements in the returned array"), returnDoc = """ a C array of pointers of type objc_property_t describing the properties declared by {@code proto}. Any properties declared by other protocols adopted by this protocol are not included. The array contains {@code *outCount} pointers followed by a #NULL terminator. You must free the array with free(). If the protocol declares no properties, #NULL is returned and {@code *outCount} is 0. """ ) Protocol.p.p( "protocol_copyProtocolList", "eturns an array of the protocols adopted by a protocol.", Protocol.p("proto", "a protocol"), AutoSizeResult..unsigned_int.p("outCount", "upon return, contains the number of elements in the returned array"), returnDoc = """ a C array of protocols adopted by {@code proto}. The array contains {@code *outCount} pointers followed by a #NULL terminator. You must free the array with free(). If the protocol declares no properties, #NULL is returned and {@code *outCount} is 0. """ ) Protocol.p( "objc_allocateProtocol", """ Creates a new protocol instance. You must register the returned protocol instance with the #objc_registerProtocol() function before you can use it. There is no dispose method associated with this function. """, charUTF8.const.p("name", "the name of the protocol you want to create"), returnDoc = "a new protocol instance or #nil if a protocol with the same name as {@code name} already exists" ) void( "objc_registerProtocol", """ Registers a newly created protocol with the Objective-C runtime. When you create a new protocol using the #objc_allocateProtocol(), you then register it with the Objective-C runtime by calling this function. After a protocol is successfully registered, it is immutable and ready to use. """, Protocol.p("proto", "the protocol you want to register with the Objective-C runtime") ) void( "protocol_addMethodDescription", """ Adds a method to a protocol. To add a method to a protocol using this function, the protocol must be under construction. That is, you must add any methods to proto before you register it with the Objective-C runtime (via the #objc_registerProtocol() function). """, Protocol.p("proto", "the protocol you want to add a method to"), SEL("name", "the name of the method you want to add"), charUTF8.const.p("types", "a C string representing the signature of the method you want to add"), BOOL( "isRequiredMethod", """ a Boolean indicating whether the method is a required method of the {@code proto} protocol. If #YES, the method is a required method; if #NO, the method is an optional method. """ ), BOOL( "isInstanceMethod", "a Boolean indicating whether the method is an instance method. If #YES, the method is an instance method; if #NO, the method is a class method." ) ) void( "protocol_addProtocol", """ Adds a registered protocol to another protocol that is under construction. The protocol you want to add to ({@code proto}) must be under construction &ndash; allocated but not yet registered with the Objective-C runtime. The protocol you want to add ({@code addition}) must be registered already. """, Protocol.p("proto", "the protocol you want to add the registered protocol to"), Protocol.p("addition", "the registered protocol you want to add to {@code proto}") ) void( "protocol_addProperty", """ Adds a property to a protocol that is under construction. The protocol you want to add the property to must be under construction &ndash; allocated but not yet registered with the Objective-C runtime (via the #objc_registerProtocol() function). """, Protocol.p("proto", "the protocol you want to add a property to"), charUTF8.const.p("name", "the name of the property you want to add."), objc_property_attribute_t.const.p("attributes", "an array of property attributes"), AutoSize("attributes")..unsigned_int("attributeCount", "the number of properties in {@code attributes}"), BOOL( "isRequiredProperty", """ a Boolean indicating whether the property's accessor methods are required methods of the {@code proto} protocol. If #YES, the property's accessor methods are required methods; if #NO, the property's accessor methods are optional methods. """ ), BOOL( "isInstanceProperty", """ a Boolean indicating whether the property's accessor methods are instance methods. If #YES, the property's accessor methods are instance methods. #YES is the only value allowed for a property. As a result, if you set this value to #NO, the property will not be added to the protocol. """ ) ) // Working with Libraries charUTF8.const.p.p( "objc_copyImageNames", "Returns the names of all the loaded Objective-C frameworks and dynamic libraries.", AutoSizeResult..unsigned_int.p("outCount", "the number of names in the returned array"), returnDoc = "an array of C strings representing the names of all the loaded Objective-C frameworks and dynamic libraries" ) charUTF8.const.p( "class_getImageName", "Returns the name of the dynamic library a class originated from.", Class("cls", "the class you are inquiring about"), returnDoc = "a C string representing the name of the library containing the {@code cls} class." ) charUTF8.const.p.p( "objc_copyClassNamesForImage", "Returns the names of all the classes within a specified library or framework.", charUTF8.const.p("image", "the library or framework you are inquiring about"), AutoSizeResult..unsigned_int.p("outCount", "the number of names in the returned array"), returnDoc = "an array of C strings representing all of the class names within the specified library or framework" ) // Working with Selectors charUTF8.const.p( "sel_getName", "Returns the name of the method specified by a given selector.", SEL("sel", "a pointer of type SEL. Pass the selector whose name you wish to determine."), returnDoc = "a C string indicating the name of the selector" ) SEL( "sel_getUid", """ Registers a method name with the Objective-C runtime system. The implementation of this method is identical to the implementation of #sel_registerName(). """, charUTF8.const.p("str", "a pointer to a C string. Pass the name of the method you wish to register"), returnDoc = "a pointer of type SEL specifying the selector for the named method" ) SEL( "sel_registerName", """ Registers a method with the Objective-C runtime system, maps the method name to a selector, and returns the selector value. You must register a method name with the Objective-C runtime system to obtain the method’s selector before you can add the method to a class definition. If the method name has already been registered, this function simply returns the selector. """, charUTF8.const.p("str", "a pointer to a C string. Pass the name of the method you wish to register"), returnDoc = "a pointer of type SEL specifying the selector for the named method" ) BOOL( "sel_isEqual", """ Returns a Boolean value that indicates whether two selectors are equal. sel_isEqual is equivalent to {@code ==}. """, SEL("lhs", "the selector to compare with {@code rhs}"), SEL("rhs", "the selector to compare with {@code lhs}"), returnDoc = "#YES if rhs and rhs are equal, otherwise #NO" ) // Objective-C Language Features void( "objc_enumerationMutation", """ Inserted by the compiler when a mutation is detected during a foreach iteration. The compiler inserts this function when it detects that an object is mutated during a foreach iteration. The function is called when a mutation occurs, and the enumeration mutation handler is enacted if it is set up (via the #objc_setEnumerationMutationHandler() function). If the handler is not set up, a fatal error occurs. """, id("obj", "the object being mutated") ) void( "objc_setEnumerationMutationHandler", "Sets the current mutation handler.", EnumerationMutationHandler("handler", "a function pointer to the new mutation handler") ) IMP( "imp_implementationWithBlock", "Creates a pointer to a function that calls the specified block when the method is called.", id( "block", """ the block that implements this method. The signature of {@code block} should be {@code method_return_type ^(id self, self, method_args …)}. The selector of the method is not available to {@code block}. {@code block} is copied with {@code Block_copy()}. """ ), returnDoc = "the IMP that calls {@code block}. You must dispose of the returned IMP using the function." ) id( "imp_getBlock", "Returns the block associated with an IMP that was created using #imp_implementationWithBlock().", IMP("anImp", "the IMP that calls this block"), returnDoc = "the block called by {@code anImp}" ) BOOL( "imp_removeBlock", "Disassociates a block from an IMP that was created using #imp_implementationWithBlock(), and releases the copy of the block that was created.", IMP("anImp", "an IMP that was created using the #imp_implementationWithBlock() function."), returnDoc = """ #YES if the block was released successfully; otherwise, #NO (for example, the function returns #NO if the block was not used to create {@code anImp} previously). """ ) id( "objc_loadWeak", """ Loads the object referenced by a weak pointer and returns it. This function loads the object referenced by a weak pointer and returns it after retaining and autoreleasing the object. As a result, the object stays alive long enough for the caller to use it. This function is typically used anywhere a {@code __weak} variable is used in an expression. """, Check(1)..nullable..id.p("location", "the address of the weak pointer"), returnDoc = "the object pointed to by location, or #nil if location is #nil" ) id( "objc_storeWeak", """ Stores a new value in a {@code __weak} variable. This function is typically used anywhere a {@code __weak} variable is the target of an assignment. """, Check(1)..id.p("location", "the address of the weak pointer"), id("obj", "the new object you want the weak pointer to now point to"), returnDoc = "the value stored in location (that is, {@code obj})" ) // Associative References val AssociationPolicies = IntConstant( "Policies related to associative references.", "OBJC_ASSOCIATION_ASSIGN".."0", "OBJC_ASSOCIATION_RETAIN_NONATOMIC".."1", "OBJC_ASSOCIATION_COPY_NONATOMIC".."3", "OBJC_ASSOCIATION_RETAIN".."1401", "OBJC_ASSOCIATION_COPY".."1403" ).javaDocLinks void( "objc_setAssociatedObject", "Sets an associated value for a given object using a given key and association policy.", id("object", "the source object for the association"), opaque_const_p("key", "the key for the association"), id("value", "the value to associate with the key {@code key} for {@code object}. Pass #nil to clear an existing association."), objc_AssociationPolicy("policy", "the policy for the association", AssociationPolicies) ) id( "objc_getAssociatedObject", "Returns the value associated with a given object for a given key.", id("object", "the source object for the association"), opaque_const_p("key", "the key for the association"), returnDoc = "the value associated with the key {@code key} for {@code object}." ) void( "objc_removeAssociatedObjects", """ Removes all associations for a given object. The main purpose of this function is to make it easy to return an object to a "pristine state". You should not use this function for general removal of associations from objects, since it also removes associations that other clients may have added to the object. Typically you should use #objc_setAssociatedObject() with a #nil value to clear an association. """, id("object", "an object that maintains associated objects") ) }
bsd-3-clause
5b33af2d94ca9c88ec12e956d2a8203b
37.707301
161
0.637838
4.626081
false
false
false
false
olegz/spring-cloud-function
spring-cloud-function-kotlin/src/test/kotlin/org/springframework/cloud/function/kotlin/web/HeadersToMessageTests.kt
1
3874
/* * Copyright 2020-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.function.kotlin.web import org.assertj.core.api.Assertions import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.autoconfigure.EnableAutoConfiguration import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.context.SpringBootTest.WebEnvironment import org.springframework.boot.test.web.client.TestRestTemplate import org.springframework.cloud.function.web.RestApplication import org.springframework.context.annotation.Bean import org.springframework.http.MediaType import org.springframework.http.RequestEntity import org.springframework.messaging.Message import org.springframework.messaging.support.MessageBuilder import org.springframework.test.context.ContextConfiguration import java.lang.Exception import java.net.URI /** * @author Dave Syer * @author Oleg Zhurakousky */ @SpringBootTest( webEnvironment = WebEnvironment.RANDOM_PORT, properties = ["spring.cloud.function.web.path=/functions", "spring.main.web-application-type=reactive"] ) @ContextConfiguration(classes = [RestApplication::class, HeadersToMessageTests.TestConfiguration::class]) class HeadersToMessageTests { @Autowired private val rest: TestRestTemplate? = null @Test @Throws(Exception::class) fun testBodyAndCustomHeaderFromMessagePropagation() { // test POJO paylod var postForEntity = rest!! .exchange( RequestEntity.post(URI("/functions/employee")) .contentType(MediaType.APPLICATION_JSON) .body("{\"name\":\"Bob\",\"age\":25}"), String::class.java ) Assertions.assertThat(postForEntity.body).isEqualTo("{\"name\":\"Bob\",\"age\":25}") Assertions.assertThat(postForEntity.headers.containsKey("x-content-type")).isTrue Assertions.assertThat(postForEntity.headers["x-content-type"]!![0]) .isEqualTo("application/xml") Assertions.assertThat(postForEntity.headers["foo"]!![0]).isEqualTo("bar") // test simple type payload postForEntity = rest.postForEntity( URI("/functions/string"), "{\"name\":\"Bob\",\"age\":25}", String::class.java ) Assertions.assertThat(postForEntity.body).isEqualTo("{\"name\":\"Bob\",\"age\":25}") Assertions.assertThat(postForEntity.headers.containsKey("x-content-type")).isTrue Assertions.assertThat(postForEntity.headers["x-content-type"]!![0]) .isEqualTo("application/xml") Assertions.assertThat(postForEntity.headers["foo"]!![0]).isEqualTo("bar") } @EnableAutoConfiguration @org.springframework.boot.test.context.TestConfiguration class TestConfiguration { @Bean("string") fun functiono(): (message: Message<String?>) -> Message<String> = { request: Message<String?> -> val message = MessageBuilder.withPayload(request.payload) .setHeader("X-Content-Type", "application/xml") .setHeader("foo", "bar").build() message } @Bean("employee") fun function1(): (employee: Message<Employee>) -> Message<Employee> = { request -> val message = MessageBuilder .withPayload(request.payload) .setHeader("X-Content-Type", "application/xml") .setHeader("foo", "bar").build() message } } // used by json converter class Employee { var name: String? = null var age = 0 } }
apache-2.0
4c867b3a4c8dc298bfb354492b4cb6c7
36.61165
105
0.749871
3.961145
false
true
false
false
techlung/MortalityDayAndroid
app/src/main/java/com/techlung/android/mortalityday/settings/Preferences.kt
1
1582
package com.techlung.android.mortalityday.settings import android.content.Context import android.content.ContextWrapper import com.pixplicity.easyprefs.library.Prefs import com.techlung.android.mortalityday.enums.Frequency import com.techlung.android.mortalityday.enums.Theme object Preferences { private const val FIRST_START = "FIRST_START" private const val NOTIFY = "KEY_NOTIFY" private const val THEME = "KEY_THEME" private const val FREQUENCY = "KEY_FREQENCY" private const val DAY1 = "KEY_DAY1" private const val DAY2 = "KEY_DAY2" private var isInited = false val isNotifyEnabled: Boolean get() = Prefs.getBoolean(NOTIFY, true) val frequency: Frequency get() = Frequency.valueOf(Prefs.getString(FREQUENCY, Frequency.ONCE_A_WEEK.name)) val theme: Theme get() = Theme.valueOf(Prefs.getString(THEME, Theme.LIGHT.name)) val day1: Int get() = Integer.parseInt(Prefs.getString(DAY1, "7")) val day2: Int get() = Integer.parseInt(Prefs.getString(DAY2, "5")) var firstStart: Boolean get() = Prefs.getBoolean(FIRST_START, true) set(firstStart) = Prefs.putBoolean(FIRST_START, firstStart) fun initPreferences(context: Context) { if (isInited) { return } isInited = true Prefs.Builder() .setContext(context) .setMode(ContextWrapper.MODE_PRIVATE) .setPrefsName(context.packageName) .setUseDefaultSharedPreference(true) .build() } }
apache-2.0
291381ccedf80bc9655cacfcc3c803b1
27.25
89
0.659924
4.015228
false
false
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/notifications/NotificationActivity.kt
1
27142
package org.wikipedia.notifications import android.content.Context import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import android.view.View.OnLongClickListener import android.view.ViewGroup import android.widget.TextView import androidx.appcompat.view.ActionMode import androidx.appcompat.widget.AppCompatImageView import androidx.core.content.ContextCompat import androidx.core.graphics.drawable.DrawableCompat import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.schedulers.Schedulers import org.wikipedia.R import org.wikipedia.WikipediaApp import org.wikipedia.activity.BaseActivity import org.wikipedia.analytics.NotificationFunnel import org.wikipedia.databinding.ActivityNotificationsBinding import org.wikipedia.dataclient.Service import org.wikipedia.dataclient.ServiceFactory import org.wikipedia.dataclient.WikiSite import org.wikipedia.history.HistoryEntry import org.wikipedia.history.SearchActionModeCallback import org.wikipedia.page.ExclusiveBottomSheetPresenter import org.wikipedia.page.PageActivity import org.wikipedia.page.PageTitle import org.wikipedia.settings.NotificationSettingsActivity import org.wikipedia.settings.Prefs import org.wikipedia.util.DateUtil.getFeedCardDateString import org.wikipedia.util.DeviceUtil.setContextClickAsLongClick import org.wikipedia.util.FeedbackUtil import org.wikipedia.util.ResourceUtil import org.wikipedia.util.StringUtil import org.wikipedia.util.log.L import org.wikipedia.views.DrawableItemDecoration import org.wikipedia.views.MultiSelectActionModeCallback import org.wikipedia.views.SwipeableItemTouchHelperCallback import java.util.* import java.util.concurrent.TimeUnit class NotificationActivity : BaseActivity(), NotificationItemActionsDialog.Callback { private lateinit var binding: ActivityNotificationsBinding private val notificationList = mutableListOf<Notification>() private val notificationContainerList = mutableListOf<NotificationListItemContainer>() private val disposables = CompositeDisposable() private val dbNameMap = mutableMapOf<String, WikiSite>() private var currentContinueStr: String? = null private var actionMode: ActionMode? = null private val multiSelectActionModeCallback = MultiSelectCallback() private val searchActionModeCallback = SearchCallback() private val bottomSheetPresenter = ExclusiveBottomSheetPresenter() private var displayArchived = false var currentSearchQuery: String? = null override val isShowingArchived get() = displayArchived public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityNotificationsBinding.inflate(layoutInflater) setContentView(binding.root) setNavigationBarColor(ResourceUtil.getThemedColor(this, android.R.attr.windowBackground)) binding.notificationsErrorView.retryClickListener = View.OnClickListener { beginUpdateList() } binding.notificationsErrorView.backClickListener = View.OnClickListener { onBackPressed() } binding.notificationsRecyclerView.layoutManager = LinearLayoutManager(this) binding.notificationsRecyclerView.addItemDecoration(DrawableItemDecoration(this, R.attr.list_separator_drawable)) val touchCallback = SwipeableItemTouchHelperCallback(this, ResourceUtil.getThemedAttributeId(this, R.attr.chart_shade5), R.drawable.ic_archive_white_24dp, ResourceUtil.getThemedAttributeId(this, R.attr.secondary_text_color)) touchCallback.swipeableEnabled = true val itemTouchHelper = ItemTouchHelper(touchCallback) itemTouchHelper.attachToRecyclerView(binding.notificationsRecyclerView) binding.notificationsRefreshView.setOnRefreshListener { binding.notificationsRefreshView.isRefreshing = false beginUpdateList() } binding.notificationsViewArchivedButton.setOnClickListener { onViewArchivedClick() } beginUpdateList() NotificationSettingsActivity.promptEnablePollDialog(this) } public override fun onDestroy() { disposables.clear() super.onDestroy() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_notifications, menu) return true } override fun onPrepareOptionsMenu(menu: Menu): Boolean { val itemArchived = menu.findItem(R.id.menu_notifications_view_archived) val itemUnread = menu.findItem(R.id.menu_notifications_view_unread) itemArchived.isVisible = !displayArchived itemUnread.isVisible = displayArchived return super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.menu_notifications_view_archived -> { onViewArchivedClick() true } R.id.menu_notifications_view_unread -> { displayArchived = false beginUpdateList() true } R.id.menu_notifications_prefs -> { startActivity(NotificationSettingsActivity.newIntent(this)) true } R.id.menu_notifications_search -> { startSupportActionMode(searchActionModeCallback) true } else -> super.onOptionsItemSelected(item) } } override fun onBackPressed() { if (displayArchived) { displayArchived = false beginUpdateList() return } super.onBackPressed() } private fun onViewArchivedClick() { displayArchived = true beginUpdateList() } private fun beginUpdateList() { binding.notificationsErrorView.visibility = View.GONE binding.notificationsRecyclerView.visibility = View.GONE binding.notificationsEmptyContainer.visibility = View.GONE binding.notificationsProgressBar.visibility = View.VISIBLE supportActionBar?.setTitle(if (displayArchived) R.string.notifications_activity_title_archived else R.string.notifications_activity_title) currentContinueStr = null disposables.clear() // if we're not checking for unread notifications, then short-circuit straight to fetching them. if (displayArchived) { orContinueNotifications return } disposables.add(ServiceFactory.get(WikiSite(Service.COMMONS_URL)).unreadNotificationWikis .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ response -> val wikiMap = response.query()!!.unreadNotificationWikis() dbNameMap.clear() for (key in wikiMap!!.keys) { if (wikiMap[key]!!.source != null) { dbNameMap[key] = WikiSite(wikiMap[key]!!.source!!.base) } } orContinueNotifications }) { t -> setErrorState(t) }) } private val orContinueNotifications: Unit get() { binding.notificationsProgressBar.visibility = View.VISIBLE disposables.add(ServiceFactory.get(WikiSite(Service.COMMONS_URL)).getAllNotifications("*", if (displayArchived) "read" else "!read", currentContinueStr) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ response -> onNotificationsComplete(response.query()!!.notifications()!!.list()!!, !currentContinueStr.isNullOrEmpty()) currentContinueStr = response.query()!!.notifications()!!.getContinue() }) { t -> setErrorState(t) }) } private fun setErrorState(t: Throwable) { L.e(t) binding.notificationsProgressBar.visibility = View.GONE binding.notificationsRecyclerView.visibility = View.GONE binding.notificationsEmptyContainer.visibility = View.GONE binding.notificationsErrorView.setError(t) binding.notificationsErrorView.visibility = View.VISIBLE } private fun setSuccessState() { binding.notificationsProgressBar.visibility = View.GONE binding.notificationsErrorView.visibility = View.GONE binding.notificationsRecyclerView.visibility = View.VISIBLE } private fun onNotificationsComplete(notifications: List<Notification>, fromContinuation: Boolean) { setSuccessState() if (!fromContinuation) { notificationList.clear() binding.notificationsRecyclerView.adapter = NotificationItemAdapter() } for (n in notifications) { if (notificationList.none { it.id() == n.id() }) { notificationList.add(n) } } postprocessAndDisplay() } private fun postprocessAndDisplay() { // Sort them by descending date... notificationList.sortWith { n1: Notification, n2: Notification -> n2.timestamp.compareTo(n1.timestamp) } // Build the container list, and punctuate it by date granularity, while also applying the // current search query. notificationContainerList.clear() var millis = Long.MAX_VALUE for (n in notificationList) { // TODO: remove this condition when the time is right. if (n.category().startsWith(Notification.CATEGORY_SYSTEM) && Prefs.notificationWelcomeEnabled() || n.category() == Notification.CATEGORY_EDIT_THANK && Prefs.notificationThanksEnabled() || n.category() == Notification.CATEGORY_THANK_YOU_EDIT && Prefs.notificationMilestoneEnabled() || n.category() == Notification.CATEGORY_REVERTED && Prefs.notificationRevertEnabled() || n.category() == Notification.CATEGORY_EDIT_USER_TALK && Prefs.notificationUserTalkEnabled() || n.category() == Notification.CATEGORY_LOGIN_FAIL && Prefs.notificationLoginFailEnabled() || n.category().startsWith(Notification.CATEGORY_MENTION) && Prefs.notificationMentionEnabled() || Prefs.showAllNotifications()) { if (!currentSearchQuery.isNullOrEmpty() && n.contents != null && !n.contents!!.header.contains(currentSearchQuery!!)) { continue } if (millis - n.timestamp.time > TimeUnit.DAYS.toMillis(1)) { notificationContainerList.add(NotificationListItemContainer(n.timestamp)) millis = n.timestamp.time } notificationContainerList.add(NotificationListItemContainer(n)) } } binding.notificationsRecyclerView.adapter!!.notifyDataSetChanged() if (notificationContainerList.isEmpty()) { binding.notificationsEmptyContainer.visibility = View.VISIBLE binding.notificationsViewArchivedButton.visibility = if (displayArchived) View.GONE else View.VISIBLE } else { binding.notificationsEmptyContainer.visibility = View.GONE } } private fun deleteItems(items: List<NotificationListItemContainer>, markUnread: Boolean) { val notificationsPerWiki: MutableMap<WikiSite, MutableList<Notification>> = HashMap() val selectionKey = if (items.size > 1) Random().nextLong() else null for (item in items) { val wiki = if (dbNameMap.containsKey(item.notification!!.wiki())) dbNameMap[item.notification!!.wiki()]!! else WikipediaApp.getInstance().wikiSite if (!notificationsPerWiki.containsKey(wiki)) { notificationsPerWiki[wiki] = ArrayList() } notificationsPerWiki[wiki]!!.add(item.notification!!) if (markUnread && !displayArchived) { notificationList.add(item.notification!!) } else { notificationList.remove(item.notification) NotificationFunnel(WikipediaApp.getInstance(), item.notification!!).logMarkRead(selectionKey) } } for (wiki in notificationsPerWiki.keys) { if (markUnread) { NotificationPollBroadcastReceiver.markRead(wiki, notificationsPerWiki[wiki]!!, true) } else { NotificationPollBroadcastReceiver.markRead(wiki, notificationsPerWiki[wiki]!!, false) showDeleteItemsUndoSnackbar(items) } } postprocessAndDisplay() } private fun showDeleteItemsUndoSnackbar(items: List<NotificationListItemContainer>) { val snackbar = FeedbackUtil.makeSnackbar(this, resources.getQuantityString(R.plurals.notification_archive_message, items.size, items.size), FeedbackUtil.LENGTH_DEFAULT) snackbar.setAction(R.string.notification_archive_undo) { deleteItems(items, true) } snackbar.show() } private fun finishActionMode() { actionMode?.finish() } private fun beginMultiSelect() { if (SearchActionModeCallback.`is`(actionMode)) { finishActionMode() } if (!MultiSelectActionModeCallback.isTagType(actionMode)) { startSupportActionMode(multiSelectActionModeCallback) } } private fun toggleSelectItem(container: NotificationListItemContainer) { container.selected = !container.selected val selectedCount = selectedItemCount if (selectedCount == 0) { finishActionMode() } else if (actionMode != null) { actionMode!!.title = resources.getQuantityString(R.plurals.multi_items_selected, selectedCount, selectedCount) } binding.notificationsRecyclerView.adapter?.notifyDataSetChanged() } private val selectedItemCount get() = notificationContainerList.count { it.selected } private fun unselectAllItems() { for (item in notificationContainerList) { item.selected = false } binding.notificationsRecyclerView.adapter?.notifyDataSetChanged() } private val selectedItems: List<NotificationListItemContainer> get() { val result: MutableList<NotificationListItemContainer> = ArrayList() for (item in notificationContainerList) { if (item.selected) { result.add(item) } } return result } override fun onArchive(notification: Notification) { bottomSheetPresenter.dismiss(supportFragmentManager) for (c in notificationContainerList) { if (c.notification != null && c.notification!!.key() == notification.key()) { deleteItems(listOf(c), displayArchived) break } } } override fun onActionPageTitle(pageTitle: PageTitle) { startActivity(PageActivity.newIntentForCurrentTab(this, HistoryEntry(pageTitle, HistoryEntry.SOURCE_NOTIFICATION), pageTitle)) } @Suppress("LeakingThis") private open inner class NotificationItemHolder constructor(view: View) : RecyclerView.ViewHolder(view), View.OnClickListener, OnLongClickListener { lateinit var container: NotificationListItemContainer private val titleView: TextView private val descriptionView: TextView private val wikiCodeView: TextView private val secondaryActionHintView: TextView private val tertiaryActionHintView: TextView private val wikiCodeBackgroundView: AppCompatImageView private val wikiCodeImageView: AppCompatImageView private val imageContainerView: View private val imageSelectedView: View private val imageView: AppCompatImageView private val imageBackgroundView: AppCompatImageView fun bindItem(container: NotificationListItemContainer) { this.container = container val n = container.notification!! var iconResId = R.drawable.ic_speech_bubbles var iconBackColor = R.color.accent50 val s = n.category() when { Notification.CATEGORY_EDIT_USER_TALK == s -> { iconResId = R.drawable.ic_edit_user_talk iconBackColor = R.color.accent50 } Notification.CATEGORY_REVERTED == s -> { iconResId = R.drawable.ic_revert iconBackColor = R.color.base20 } Notification.CATEGORY_EDIT_THANK == s -> { iconResId = R.drawable.ic_user_talk iconBackColor = R.color.green50 } Notification.CATEGORY_THANK_YOU_EDIT == s -> { iconResId = R.drawable.ic_edit_progressive iconBackColor = R.color.accent50 } s.startsWith(Notification.CATEGORY_MENTION) -> { iconResId = R.drawable.ic_mention iconBackColor = R.color.accent50 } Notification.CATEGORY_LOGIN_FAIL == s -> { iconResId = R.drawable.ic_user_avatar iconBackColor = R.color.base0 } } imageView.setImageResource(iconResId) DrawableCompat.setTint(imageBackgroundView.drawable, ContextCompat.getColor(this@NotificationActivity, iconBackColor)) n.contents?.let { titleView.text = StringUtil.fromHtml(it.header) if (it.body.trim().isNotEmpty()) { descriptionView.text = StringUtil.fromHtml(it.body) descriptionView.visibility = View.VISIBLE } else { descriptionView.visibility = View.GONE } it.links?.secondary?.let { secondary -> if (secondary.size > 0) { secondaryActionHintView.text = secondary[0].label secondaryActionHintView.visibility = View.VISIBLE if (secondary.size > 1) { tertiaryActionHintView.text = secondary[1].label tertiaryActionHintView.visibility = View.VISIBLE } } } } val wikiCode = n.wiki() when { wikiCode.contains("wikidata") -> { wikiCodeView.visibility = View.GONE wikiCodeBackgroundView.visibility = View.GONE wikiCodeImageView.visibility = View.VISIBLE wikiCodeImageView.setImageResource(R.drawable.ic_wikidata_logo) } wikiCode.contains("commons") -> { wikiCodeView.visibility = View.GONE wikiCodeBackgroundView.visibility = View.GONE wikiCodeImageView.visibility = View.VISIBLE wikiCodeImageView.setImageResource(R.drawable.ic_commons_logo) } else -> { wikiCodeBackgroundView.visibility = View.VISIBLE wikiCodeView.visibility = View.VISIBLE wikiCodeImageView.visibility = View.GONE wikiCodeView.text = n.wiki().replace("wiki", "") } } if (container.selected) { imageSelectedView.visibility = View.VISIBLE imageContainerView.visibility = View.INVISIBLE itemView.setBackgroundColor(ResourceUtil.getThemedColor(this@NotificationActivity, R.attr.multi_select_background_color)) } else { imageSelectedView.visibility = View.INVISIBLE imageContainerView.visibility = View.VISIBLE itemView.setBackgroundColor(ResourceUtil.getThemedColor(this@NotificationActivity, R.attr.paper_color)) } } override fun onClick(v: View) { if (MultiSelectActionModeCallback.isTagType(actionMode)) { toggleSelectItem(container) } else { bottomSheetPresenter.show(supportFragmentManager, NotificationItemActionsDialog.newInstance(container.notification!!)) } } override fun onLongClick(v: View): Boolean { beginMultiSelect() toggleSelectItem(container) return true } init { itemView.setOnClickListener(this) itemView.setOnLongClickListener(this) titleView = view.findViewById(R.id.notification_item_title) descriptionView = view.findViewById(R.id.notification_item_description) secondaryActionHintView = view.findViewById(R.id.notification_item_secondary_action_hint) tertiaryActionHintView = view.findViewById(R.id.notification_item_tertiary_action_hint) wikiCodeView = view.findViewById(R.id.notification_wiki_code) wikiCodeImageView = view.findViewById(R.id.notification_wiki_code_image) wikiCodeBackgroundView = view.findViewById(R.id.notification_wiki_code_background) imageContainerView = view.findViewById(R.id.notification_item_image_container) imageBackgroundView = view.findViewById(R.id.notification_item_image_background) imageSelectedView = view.findViewById(R.id.notification_item_selected_image) imageView = view.findViewById(R.id.notification_item_image) setContextClickAsLongClick(itemView) } } private inner class NotificationItemHolderSwipeable constructor(v: View) : NotificationItemHolder(v), SwipeableItemTouchHelperCallback.Callback { override fun onSwipe() { deleteItems(listOf(container), false) } } private inner class NotificationDateHolder constructor(view: View) : RecyclerView.ViewHolder(view) { private val dateView: TextView = view.findViewById(R.id.notification_date_text) fun bindItem(date: Date?) { dateView.text = getFeedCardDateString(date!!) } } private inner class NotificationItemAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() { override fun getItemCount(): Int { return notificationContainerList.size } override fun getItemViewType(position: Int): Int { return notificationContainerList[position].type } override fun onCreateViewHolder(parent: ViewGroup, type: Int): RecyclerView.ViewHolder { if (type == NotificationListItemContainer.ITEM_DATE_HEADER) { return NotificationDateHolder(layoutInflater.inflate(R.layout.item_notification_date, parent, false)) } return if (displayArchived) { NotificationItemHolder(layoutInflater.inflate(R.layout.item_notification, parent, false)) } else { NotificationItemHolderSwipeable(layoutInflater.inflate(R.layout.item_notification, parent, false)) } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, pos: Int) { when (holder) { is NotificationDateHolder -> holder.bindItem(notificationContainerList[pos].date) is NotificationItemHolderSwipeable -> holder.bindItem(notificationContainerList[pos]) is NotificationItemHolder -> holder.bindItem(notificationContainerList[pos]) } // if we're at the bottom of the list, and we have a continuation string, then execute it. if (pos == notificationContainerList.size - 1 && !currentContinueStr.isNullOrEmpty()) { orContinueNotifications } } } private inner class SearchCallback : SearchActionModeCallback() { override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { actionMode = mode return super.onCreateActionMode(mode, menu) } override fun onQueryChange(s: String) { currentSearchQuery = s.trim() postprocessAndDisplay() } override fun onDestroyActionMode(mode: ActionMode) { super.onDestroyActionMode(mode) actionMode = null currentSearchQuery = null postprocessAndDisplay() } override fun getSearchHintString(): String { return getString(R.string.notifications_search) } override fun getParentContext(): Context { return this@NotificationActivity } } private inner class MultiSelectCallback : MultiSelectActionModeCallback() { override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { super.onCreateActionMode(mode, menu) mode.menuInflater.inflate(R.menu.menu_action_mode_notifications, menu) menu.findItem(R.id.menu_delete_selected).isVisible = !displayArchived menu.findItem(R.id.menu_unarchive_selected).isVisible = displayArchived actionMode = mode return true } override fun onActionItemClicked(mode: ActionMode, menuItem: MenuItem): Boolean { when (menuItem.itemId) { R.id.menu_delete_selected, R.id.menu_unarchive_selected -> { onDeleteSelected() finishActionMode() return true } } return false } override fun onDeleteSelected() { deleteItems(selectedItems, displayArchived) } override fun onDestroyActionMode(mode: ActionMode) { unselectAllItems() actionMode = null super.onDestroyActionMode(mode) } } private class NotificationListItemContainer { val type: Int var notification: Notification? = null var date: Date? = null var selected = false constructor(date: Date) { this.date = date type = ITEM_DATE_HEADER } constructor(notification: Notification) { this.notification = notification type = ITEM_NOTIFICATION } companion object { const val ITEM_DATE_HEADER = 0 const val ITEM_NOTIFICATION = 1 } } companion object { fun newIntent(context: Context): Intent { return Intent(context, NotificationActivity::class.java) } } }
apache-2.0
2136fe0cdd8241b18a2fc7650316138f
42.848142
176
0.643947
5.427315
false
false
false
false
android/project-replicator
plugin/src/main/kotlin/com/android/gradle/replicator/collectors/AndroidCollector.kt
1
8232
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.gradle.replicator.collectors import com.android.build.api.dsl.ApplicationBuildFeatures import com.android.build.api.dsl.DynamicFeatureBuildFeatures import com.android.build.api.dsl.LibraryBuildFeatures import com.android.build.api.dsl.TestBuildFeatures import com.android.build.gradle.BaseExtension import com.android.build.gradle.internal.plugins.BasePlugin import com.android.gradle.replicator.model.internal.DefaultAndroidInfo import com.android.gradle.replicator.model.internal.DefaultBuildFeaturesInfo import org.gradle.api.Project import org.gradle.api.file.ConfigurableFileCollection import org.gradle.api.provider.Property import org.gradle.api.tasks.* import javax.inject.Inject /** * A collector that can look at a project and collect Android information. * * In the future there may be more than one depending on AGP APIs */ interface AndroidCollector { fun collectInfo(project: Project) : AndroidInfoInputs? } /** * Basic implementation of collector to start with. */ class DefaultAndroidCollector : AndroidCollector { private lateinit var project: Project override fun collectInfo(project: Project): AndroidInfoInputs? { // load the BasePlugin by reflection in case it does not exist so that we dont fail with ClassNotFoundException return project.plugins.withType(BasePlugin::class.java).firstOrNull()?.let { this.project = project // if we are here there is indeed an Android plugin applied val baseExtension = project.extensions.getByName("android") as BaseExtension val buildFeatures = getBuildFeatures(baseExtension) val inputs = project.objects.newInstance( AndroidInfoInputs::class.java, baseExtension.compileSdkVersion ?: "", baseExtension.defaultConfig.minSdkVersion?.apiLevel ?: 0, //FIXME baseExtension.defaultConfig.targetSdkVersion?.apiLevel ?: 0, //FIXME buildFeatures ) // FIXME when we get to provide flavor/build type info, then we can augment this. val mainSrcSet = baseExtension.sourceSets.findByName("main") mainSrcSet?.java?.srcDirs?.let { inputs.javaFolders.from(it) } mainSrcSet?.res?.srcDirs?.let { inputs.androidResourceFolders.from(it) } mainSrcSet?.resources?.srcDirs?.let { inputs.javaResourceFolders.from(it) } mainSrcSet?.assets?.srcDirs?.let { inputs.assetFolders.from(it) } inputs } } @Suppress("UnstableApiUsage") private fun getBuildFeatures(extension: BaseExtension): BuildFeaturesInput = project.objects.newInstance(BuildFeaturesInput::class.java).also { buildFeaturesInput -> try { val buildFeatures = extension.buildFeatures buildFeaturesInput.aidl.lenientSet { buildFeatures.aidl } buildFeaturesInput.buildConfig.lenientSet { buildFeatures.buildConfig } buildFeaturesInput.compose.lenientSet { buildFeatures.compose } buildFeaturesInput.prefab.lenientSet { buildFeatures.prefab } buildFeaturesInput.renderScript.lenientSet { buildFeatures.renderScript } buildFeaturesInput.resValues.lenientSet { buildFeatures.resValues } buildFeaturesInput.shaders.lenientSet { buildFeatures.shaders } buildFeaturesInput.viewBinding.lenientSet { buildFeatures.viewBinding } when (buildFeatures) { is ApplicationBuildFeatures -> { buildFeaturesInput.dataBinding.lenientSet { buildFeatures.dataBinding } buildFeaturesInput.mlModelBinding.lenientSet { buildFeatures.mlModelBinding } } is LibraryBuildFeatures -> { buildFeaturesInput.androidResources.lenientSet { buildFeatures.androidResources } buildFeaturesInput.dataBinding.lenientSet { buildFeatures.dataBinding } buildFeaturesInput.mlModelBinding.lenientSet { buildFeatures.mlModelBinding } buildFeaturesInput.prefabPublishing.lenientSet { buildFeatures.prefabPublishing } } is DynamicFeatureBuildFeatures -> { buildFeaturesInput.dataBinding.lenientSet { buildFeatures.dataBinding } buildFeaturesInput.mlModelBinding.lenientSet { buildFeatures.mlModelBinding } } is TestBuildFeatures -> { } } } catch (e: Throwable) { // older AGP don't have buildFeatures } } } private fun <T> Property<T>.lenientSet(access: () -> T?) = try { set(access()) } catch (e: Throwable) { // do nothing } abstract class AndroidInfoInputs @Inject constructor( @get:Input val compileSdkVersion: String, @get:Input val minSdkVersion: Int, @get:Input val targetSdkVersion: Int, @get:Nested val buildFeatures: BuildFeaturesInput ) { @get:InputFiles @get:PathSensitive(PathSensitivity.RELATIVE) abstract val javaFolders: ConfigurableFileCollection @get:InputFiles @get:PathSensitive(PathSensitivity.RELATIVE) abstract val androidResourceFolders: ConfigurableFileCollection @get:InputFiles @get:PathSensitive(PathSensitivity.RELATIVE) abstract val javaResourceFolders: ConfigurableFileCollection @get:InputFiles @get:PathSensitive(PathSensitivity.RELATIVE) abstract val assetFolders: ConfigurableFileCollection fun toInfo(): DefaultAndroidInfo { return DefaultAndroidInfo(compileSdkVersion, minSdkVersion, targetSdkVersion, buildFeatures.toInfo()) } } abstract class BuildFeaturesInput { @get:Input @get:Optional abstract val aidl: Property<Boolean> @get:Input @get:Optional abstract val androidResources: Property<Boolean> @get:Input @get:Optional abstract val buildConfig: Property<Boolean> @get:Input @get:Optional abstract val compose: Property<Boolean> @get:Input @get:Optional abstract val dataBinding: Property<Boolean> @get:Input @get:Optional abstract val mlModelBinding: Property<Boolean> @get:Input @get:Optional abstract val prefab: Property<Boolean> @get:Input @get:Optional abstract val prefabPublishing: Property<Boolean> @get:Input @get:Optional abstract val renderScript: Property<Boolean> @get:Input @get:Optional abstract val resValues: Property<Boolean> @get:Input @get:Optional abstract val shaders: Property<Boolean> @get:Input @get:Optional abstract val viewBinding: Property<Boolean> fun toInfo(): DefaultBuildFeaturesInfo = DefaultBuildFeaturesInfo( aidl.orNull, androidResources.orNull, buildConfig.orNull, compose.orNull, dataBinding.orNull, mlModelBinding.orNull, prefab.orNull, prefabPublishing.orNull, renderScript.orNull, resValues.orNull, shaders.orNull, viewBinding.orNull ) }
apache-2.0
8b14d4da3665c57cb30fae0338d4933c
36.589041
119
0.655369
5.122589
false
true
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveEmptyParenthesesFromLambdaCallIntention.kt
1
2532
// 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.intentions import com.intellij.codeInspection.CleanupLocalInspectionTool import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection import org.jetbrains.kotlin.idea.refactoring.getLineNumber import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtQualifiedExpression import org.jetbrains.kotlin.psi.KtValueArgumentList import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments @Suppress("DEPRECATION") class RemoveEmptyParenthesesFromLambdaCallInspection : IntentionBasedInspection<KtValueArgumentList>( RemoveEmptyParenthesesFromLambdaCallIntention::class ), CleanupLocalInspectionTool class RemoveEmptyParenthesesFromLambdaCallIntention : SelfTargetingRangeIntention<KtValueArgumentList>( KtValueArgumentList::class.java, KotlinBundle.lazyMessage("remove.unnecessary.parentheses.from.function.call.with.lambda") ) { override fun applicabilityRange(element: KtValueArgumentList): TextRange? = Companion.applicabilityRange(element) override fun applyTo(element: KtValueArgumentList, editor: Editor?) = Companion.applyTo(element) companion object { fun isApplicable(list: KtValueArgumentList): Boolean = applicabilityRange(list) != null fun applyTo(list: KtValueArgumentList) = list.delete() fun applyToIfApplicable(list: KtValueArgumentList) { if (isApplicable(list)) { applyTo(list) } } private fun applicabilityRange(list: KtValueArgumentList): TextRange? { if (list.arguments.isNotEmpty()) return null val parent = list.parent as? KtCallExpression ?: return null if (parent.calleeExpression?.text == KtTokens.SUSPEND_KEYWORD.value) return null val singleLambdaArgument = parent.lambdaArguments.singleOrNull() ?: return null if (list.getLineNumber(start = false) != singleLambdaArgument.getLineNumber(start = true)) return null val prev = list.getPrevSiblingIgnoringWhitespaceAndComments() if (prev is KtCallExpression || (prev as? KtQualifiedExpression)?.callExpression != null) return null return list.textRange } } }
apache-2.0
56ea3025f30f2f2105f70cab78ecff22
48.647059
126
0.767773
5.456897
false
false
false
false
dahlstrom-g/intellij-community
plugins/git4idea/src/git4idea/repo/GitSilentFileAdderProvider.kt
8
2977
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.repo import com.intellij.openapi.GitSilentFileAdder import com.intellij.openapi.GitSilentFileAdderProvider import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.util.BackgroundTaskUtil import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.VcsFileListenerContextHelper import com.intellij.openapi.vfs.VirtualFile import com.intellij.vcsUtil.VcsUtil import git4idea.GitUtil import git4idea.GitVcs import git4idea.util.GitFileUtils import java.io.File import java.nio.file.Path class GitSilentFileAdderProviderImpl(private val project: Project) : GitSilentFileAdderProvider { override fun create(): GitSilentFileAdder = GitSilentFileAdderImpl(project) } class GitSilentFileAdderImpl(private val project: Project) : GitSilentFileAdder { private val gitVcs = GitVcs.getInstance(project) private val vcsManager = ProjectLevelVcsManager.getInstance(project) private val vcsFileListenerContextHelper = VcsFileListenerContextHelper.getInstance(project) private val pendingAddition: MutableSet<FilePath> = HashSet() override fun markFileForAdding(path: String, isDirectory: Boolean) { addFile(VcsUtil.getFilePath(path, isDirectory)) } override fun markFileForAdding(file: VirtualFile) { if (file.isInLocalFileSystem) { addFile(VcsUtil.getFilePath(file)) } } override fun markFileForAdding(file: File, isDirectory: Boolean) { addFile(VcsUtil.getFilePath(file, isDirectory)) } override fun markFileForAdding(path: Path, isDirectory: Boolean) { addFile(VcsUtil.getFilePath(path, isDirectory)) } private fun addFile(filePath: FilePath) { val vcsRoot = vcsManager.getVcsRootObjectFor(filePath) if (vcsRoot == null || vcsRoot.vcs != gitVcs) return if (filePath.isDirectory) { vcsFileListenerContextHelper.ignoreAddedRecursive(listOf(filePath)) } else { vcsFileListenerContextHelper.ignoreAdded(listOf(filePath)) } pendingAddition.add(filePath) } override fun finish() { vcsFileListenerContextHelper.clearContext() val filesToAdd = pendingAddition.toList() pendingAddition.clear() @Suppress("IncorrectParentDisposable") BackgroundTaskUtil.executeOnPooledThread(project) { addToVcs(filesToAdd) } } /** * Called on pooled thread when all operations are completed. */ private fun addToVcs(filePaths: Collection<FilePath>) { val map = GitUtil.sortFilePathsByGitRoot(project, filePaths) for ((root, rootPaths) in map) { try { GitFileUtils.addPaths(project, root, rootPaths) } catch (e: VcsException) { logger<GitSilentFileAdderImpl>().warn(e) } } } }
apache-2.0
24128546c20d6a1e8376a5fc4dc8ca3f
32.840909
140
0.768559
4.295815
false
false
false
false
alekratz/markov-bot
src/main/kotlin/edu/appstate/cs/markovbot/Main.kt
1
9138
package edu.appstate.cs.markovbot import org.pircbotx.Configuration import org.pircbotx.PircBotX import sun.misc.Signal import sun.misc.SignalHandler import java.io.File import java.util.* import javax.net.ssl.SSLSocketFactory var threads = ArrayList<Thread>() /** * @author Alek Ratzloff <[email protected]> * Catches a CTRL-C from the terminal. This only works for SIGINT as far as I am aware - if you send the process * some other signal (e.g. SIGKILL, SIGQUIT) to kill it, this will likely not get called. */ class CatchCtrlC : SignalHandler { override fun handle(p0: Signal?) { println() println("ctrl-c caught; shutting down") for(t in threads) t.interrupt() for(t in threads) t.join() } } fun installSIGINTHandler() { val ctrlC = Signal("INT") val handler = CatchCtrlC() Signal.handle(ctrlC, handler) } /** * @author Alek Ratzloff <[email protected]> * Loads the properties from the props file. For now, the props path is markov-bot.properties. This may change later. */ fun loadProperties(): Properties { val propsTemplate = """# Required. A comma-separated list of servers that the bot uses. These each have their own subsections. servers = freenode # Required for each server. A comma-separated list of channels that the bot will be a part of. freenode.channels = # Required. The nickname of the markov bot for the given server. freenode.nickname = markovbot # Required. The hostname of the server that you will be operating on. freenode.hostname = chat.freenode.net # Optional. Default 3600. The number of seconds in between markov chain saves. This can be set per-server or per-channel. # freenode.save-every = 3600 # freenode.#myroom.save-every = 1800 # Optional. Sets the order of the markov chain. Note that if you wish to chain the order of the markov chain, you must # delete the original file. # The order is recommended to be 1 or 2. A higher order makes sentences more coherent; too high of an order will just # parrot back original sentences to users. # freenode.order = 1 # Optional. Default servername/chains. The location to save markov chains to. This may be set per-server, or per-channel. # These directories may be shared among rooms. # freenode.save-directory = freenode/chains # freenode.#java.save-directory = freenode/chains # Optional. Default 0.01. The chance that every time a message is sent, the markov bot will come up with something random to say to the channel. # Must be less than 1.0 and greater than 0.0. # freenode.random-chance = 0.01 # Optional. Default false. Determines whether to use SSL or not for a server. # freenode.ssl = false # Optional. Default none. Defines a password to send to the nickserv for authentication. # If you don't want a password, DO NOT set this to blank; just comment it out. # freenode.password = """ val propsPath = "markov-bot.properties" val propsFile = File(propsPath) if(!propsFile.exists()) { println("Properties file not found, creating template in $propsPath") if(!propsFile.createNewFile()) { println("Could not create properties file. Exiting") System.exit(1) } val writer = propsFile.printWriter() writer.print(propsTemplate) writer.close() println("Exiting") System.exit(0) } val defaultProps = Properties() defaultProps.setProperty("should-save", "true") defaultProps.setProperty("save-every", "3600") val props = Properties(defaultProps) props.load(propsFile.bufferedReader()) fun checkProp(propName: String) { val prop = props.getProperty(propName) if(prop == null || prop.trim() == "") { println("$propName field in properties must be filled out") System.exit(1) } } checkProp("servers") val servers = props.getProperty("servers").split(",") for(serverName in servers) { // verify that all required properties exist checkProp("$serverName.nickname") checkProp("$serverName.hostname") checkProp("$serverName.channels") // I know this is kinda inefficient, but we can fix that later. Maybe make a custom overridden Properties method? val saveEvery = props.getProperty("$serverName.save-every") ?: props.getProperty("save-every") val saveDirectory = props.getProperty("$serverName.save-directory") ?: "chains/$serverName" val port = props.getProperty("$serverName.port") ?: "6667" val ssl = props.getProperty("$serverName.ssl") ?: "false" val randomChance = props.getProperty("$serverName.random-chance") ?: "0.01" val maxSentences = props.getProperty("$serverName.max-sentences") ?: "1" props.setProperty("$serverName.save-every", saveEvery) props.setProperty("$serverName.save-directory", saveDirectory) props.setProperty("$serverName.port", port) props.setProperty("$serverName.ssl", ssl) props.setProperty("$serverName.random-chance", randomChance) props.setProperty("$serverName.max-sentences", maxSentences) } return props } /** * @author Alek Ratzloff <[email protected]> * Main method. Sets up the CTRL-C shutdown hook, loads properties, and starts bot threads. */ fun main(args: Array<String>) { val props = loadProperties() val servers = props.getProperty("servers").split(",") // If we have any shared chain directories, those chains will be shared among the different listeners. data class SaveInfo(val saveEvery: Int, val chainMap: HashMap<String, MarkovChain>) val chainSaves: HashMap<String, SaveInfo> = HashMap() for(serverName in servers) { val configBuilder = Configuration.Builder<PircBotX>() .setName(props.getProperty("$serverName.nickname")) .setServerHostname(props.getProperty("$serverName.hostname")) .setServerPort(props.getProperty("$serverName.port").toInt()) if(props.getProperty("$serverName.ssl").toBoolean()) { val acceptInvalidCerts = props.getProperty("$serverName.ssl.accept-invalid-certs")?.toBoolean() ?: false if(acceptInvalidCerts) configBuilder.setSocketFactory(getNaiveSocketFactory()) else configBuilder.setSocketFactory(SSLSocketFactory.getDefault()) } // Set up listeners for each channel val channels = props.getProperty("$serverName.channels").split(",") for(channelName in channels) { val saveEvery = (props.getProperty("$serverName.$channelName.save-every") ?: props.getProperty("$serverName.save-every")).toInt() val saveDirectory = props.getProperty("$serverName.$channelName.save-directory") // basically, get the server directory and make a channel subdirectory inside of it ?: "${props.getProperty("$serverName.save-directory")}/${channelName.filterNot { c -> c == '#' }}" val randomChance = (props.getProperty("$serverName.$channelName.random-chance") ?: props.getProperty("$serverName.random-chance")).toDouble() val maxSentences = (props.getProperty("$serverName.$channelName.max-sentences") ?: props.getProperty("$serverName.max-sentences")).toInt() val order = (props.getProperty("$serverName.order") ?: "1").toInt() // Get if this is a shared chain; if not, create its sharedness chainSaves.putIfAbsent(saveDirectory, SaveInfo(saveEvery, HashMap())) val chainMap = chainSaves[saveDirectory]!! configBuilder .addAutoJoinChannel(channelName) .addListener(MessageListener( channelName, saveDirectory, randomChance, maxSentences, chainMap.chainMap, order )) .setMessageDelay(50) .setSocketTimeout(5000) println("Adding channel $channelName") } // Create the final config and start the bot val nickServPassword = props.getProperty("$serverName.password") val config = configBuilder .setNickservPassword(nickServPassword) .buildConfiguration() val bot = PircBotX(config) bot.stopBotReconnect() val botThread = Thread(PircBotRunner(bot)) // Add the bot thread threads.add(botThread) } // Add all of the savers for this bot for(dir in chainSaves.keys) { val chainMap = chainSaves[dir]!!.chainMap val saveEvery = chainSaves[dir]!!.saveEvery val saver = MessageSaver(chainMap, dir, saveEvery) threads.add(Thread(saver)) } // add jvm shutdown hook installSIGINTHandler() for(t in threads) t.start() // wait for all connections to close for(t in threads) t.join() }
bsd-2-clause
400505201fbae5368a8943af50a58e4d
40.352941
144
0.653754
4.357654
false
false
false
false
JuliaSoboleva/SmartReceiptsLibrary
app/src/main/java/co/smartreceipts/android/imports/locator/ActivityFileResultLocatorResponse.kt
2
658
package co.smartreceipts.android.imports.locator import android.net.Uri import com.hadisatrio.optional.Optional data class ActivityFileResultLocatorResponse private constructor( val throwable: Optional<Throwable>, val uri: Uri? = null, val requestCode: Int = 0, val resultCode: Int = 0 ) { companion object { @JvmStatic fun locatorError(throwable: Throwable) = ActivityFileResultLocatorResponse(Optional.of(throwable)) @JvmStatic fun locatorResponse(uri: Uri, requestCode: Int, resultCode: Int) = ActivityFileResultLocatorResponse(Optional.absent(), uri, requestCode, resultCode) } }
agpl-3.0
408e68df4728d86c5a6be56b3e35a71b
27.608696
106
0.720365
4.506849
false
false
false
false
paplorinc/intellij-community
python/python-community-configure/src/com/jetbrains/python/configuration/PySdkStatusBar.kt
1
6027
// 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.jetbrains.python.configuration import com.intellij.ProjectTopics import com.intellij.openapi.actionSystem.* import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtil import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.ModuleRootEvent import com.intellij.openapi.roots.ModuleRootListener import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.ListPopup import com.intellij.openapi.util.Condition import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.StatusBarWidget import com.intellij.openapi.wm.StatusBarWidgetProvider import com.intellij.openapi.wm.impl.status.EditorBasedStatusBarPopup import com.intellij.util.PlatformUtils import com.intellij.util.text.trimMiddle import com.jetbrains.python.inspections.PyInterpreterInspection import com.jetbrains.python.psi.LanguageLevel import com.jetbrains.python.sdk.* import com.jetbrains.python.sdk.add.PyAddSdkDialog import java.util.function.Consumer class PySdkStatusBarWidgetProvider : StatusBarWidgetProvider { override fun getWidget(project: Project): StatusBarWidget? = if (PlatformUtils.isPyCharm()) PySdkStatusBar(project) else null } class PySwitchSdkAction : AnAction("Switch Project Interpreter", null, null) { override fun update(e: AnActionEvent) { e.presentation.isVisible = e.getData(CommonDataKeys.VIRTUAL_FILE) != null && e.project != null } override fun actionPerformed(e: AnActionEvent) { val file = e.getData(CommonDataKeys.VIRTUAL_FILE) ?: return val project = e.project ?: return val module = ModuleUtil.findModuleForFile(file, project) ?: return val dataContext = e.dataContext PySdkPopupFactory(project, module).createPopup(dataContext)?.showInBestPositionFor(dataContext) } } private class PySdkStatusBar(project: Project) : EditorBasedStatusBarPopup(project) { private var module: Module? = null override fun getWidgetState(file: VirtualFile?): WidgetState { if (file == null) return WidgetState.HIDDEN module = ModuleUtil.findModuleForFile(file, project!!) ?: return WidgetState.HIDDEN val sdk = PythonSdkType.findPythonSdk(module) return if (sdk == null) { WidgetState("", noInterpreterMarker, true) } else { WidgetState("Current Interpreter: ${shortenNameAndPath(sdk)}]", shortenNameInBar(sdk), true) } } override fun registerCustomListeners() { project!! .messageBus .connect(this) .subscribe( ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener { override fun rootsChanged(event: ModuleRootEvent) = update() } ) } override fun createPopup(context: DataContext): ListPopup? = module?.let { PySdkPopupFactory(project!!, it).createPopup(context) } override fun ID(): String = "PythonInterpreter" override fun requiresWritableFile(): Boolean = false override fun createInstance(project: Project): StatusBarWidget = PySdkStatusBar(project) private fun shortenNameInBar(sdk: Sdk) = name(sdk).trimMiddle(50) } private class PySdkPopupFactory(val project: Project, val module: Module) { fun createPopup(context: DataContext): ListPopup? { val group = DefaultActionGroup() val moduleSdksByTypes = groupModuleSdksByTypes(PyConfigurableInterpreterList.getInstance(project).getAllPythonSdks(project), module) { PythonSdkType.isInvalid(it) || PythonSdkType.hasInvalidRemoteCredentials(it) || PythonSdkType.isIncompleteRemote(it) || !LanguageLevel.SUPPORTED_LEVELS.contains(PythonSdkType.getLanguageLevelForSdk(it)) } PyRenderedSdkType.values().forEachIndexed { index, type -> if (type in moduleSdksByTypes) { if (index != 0) group.addSeparator() group.addAll(moduleSdksByTypes.getValue(type).map { SwitchToSdkAction(it) }) } } if (moduleSdksByTypes.isNotEmpty()) group.addSeparator() group.add(InterpreterSettingsAction()) group.add(AddInterpreterAction()) val currentSdk = PythonSdkType.findPythonSdk(module) return JBPopupFactory.getInstance().createActionGroupPopup( "Project Interpreter", group, context, JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, false, null, -1, Condition { it is SwitchToSdkAction && it.sdk == currentSdk }, null ) } private fun shortenNameInPopup(sdk: Sdk) = name(sdk).trimMiddle(100) private inner class SwitchToSdkAction(val sdk: Sdk) : AnAction() { init { val presentation = templatePresentation presentation.setText(shortenNameInPopup(sdk), false) presentation.description = "Switch to ${shortenNameAndPath(sdk)}]" presentation.icon = icon(sdk) } override fun actionPerformed(e: AnActionEvent) { project.pythonSdk = sdk module.pythonSdk = sdk } } private inner class InterpreterSettingsAction : AnAction("Interpreter Settings...") { override fun actionPerformed(e: AnActionEvent) = PyInterpreterInspection.ConfigureInterpreterFix.showProjectInterpreterDialog(project) } private inner class AddInterpreterAction : AnAction("Add Interpreter...") { override fun actionPerformed(e: AnActionEvent) { val model = PyConfigurableInterpreterList.getInstance(project).model PyAddSdkDialog.show( project, module, model.sdks.asList(), Consumer { if (it != null && model.findSdk(it.name) == null) { model.addSdk(it) model.apply() } } ) } } } private fun shortenNameAndPath(sdk: Sdk) = "${name(sdk)} [${path(sdk)}]".trimMiddle(150) private fun name(sdk: Sdk): String { val (_, primary, secondary) = com.jetbrains.python.sdk.name(sdk) return if (secondary == null) primary else "$primary [$secondary]" }
apache-2.0
adb13c26a3b29970f6525de3c89329f3
34.251462
140
0.731873
4.548679
false
false
false
false
paplorinc/intellij-community
plugins/git4idea/src/git4idea/rebase/GitAutoSquashCommitAction.kt
2
2354
// 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 git4idea.rebase import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.changes.ChangeListManager import com.intellij.openapi.vcs.changes.ChangesUtil import com.intellij.openapi.vcs.changes.CommitExecutor import com.intellij.openapi.vcs.changes.CommitSession import com.intellij.openapi.vcs.changes.ui.CommitChangeListDialog import com.intellij.vcs.log.VcsShortCommitDetails import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryManager abstract class GitAutoSquashCommitAction : GitCommitEditingAction() { override fun actionPerformedAfterChecks(e: AnActionEvent) { val commit = getSelectedCommit(e) val project = e.project!! val changeList = ChangeListManager.getInstance(project).defaultChangeList val repository = getRepository(e) val gitRepositoryManager = GitRepositoryManager.getInstance(project) val changes = changeList.changes.filter { gitRepositoryManager.getRepositoryForFile(ChangesUtil.getFilePath(it)) == repository } val executors = repository.vcs.commitExecutors + if (getProhibitedStateMessage(e, "rebase") == null) listOf(GitRebaseAfterCommitExecutor(project, repository, commit.id.asString() + "~")) else listOf() CommitChangeListDialog.commitChanges(project, changes, changes, changeList, executors, true, null, getCommitMessage(commit), null, true) } protected abstract fun getCommitMessage(commit: VcsShortCommitDetails): String class GitRebaseAfterCommitExecutor(val project: Project, val repository: GitRepository, val hash: String) : CommitExecutor { override fun getActionText(): String = "Commit and Rebase..." override fun createCommitSession(): CommitSession = CommitSession.VCS_COMMIT override fun supportsPartialCommit() = true } }
apache-2.0
4796bd91c7a8faca4158f68d2d73ccbb
44.288462
140
0.671198
5.538824
false
false
false
false
paplorinc/intellij-community
platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ReprocessContentRootDataActivity.kt
1
2238
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.service.project.manage import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.externalSystem.model.ProjectKeys.CONTENT_ROOT import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProviderImpl import com.intellij.openapi.externalSystem.service.project.ProjectDataManager import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity class ReprocessContentRootDataActivity : StartupActivity, DumbAware { override fun runActivity(project: Project) { if (ApplicationManager.getApplication().isUnitTestMode) { return } val dataManager = ProjectDataManager.getInstance() val service = ContentRootDataService() val externalProjectsManager = ExternalProjectsManagerImpl.getInstance(project) externalProjectsManager.init() externalProjectsManager.runWhenInitialized { val haveModulesToProcess = ModuleManager.getInstance(project).modules.isNotEmpty() if (!haveModulesToProcess) { return@runWhenInitialized } val modifiableModelsProvider = lazy { IdeModifiableModelsProviderImpl(project) } try { ExternalSystemApiUtil.getAllManagers() .flatMap { dataManager.getExternalProjectsData(project, it.getSystemId()) } .mapNotNull { it.externalProjectStructure } .map { ExternalSystemApiUtil.findAllRecursively(it, CONTENT_ROOT) } .forEach { service.importData(it, null, project, modifiableModelsProvider.value) } } finally { if (modifiableModelsProvider.isInitialized()) { ExternalSystemApiUtil.doWriteAction { if (!project.isDisposed) { modifiableModelsProvider.value.commit() } else { modifiableModelsProvider.value.dispose() } } } } } } }
apache-2.0
f6ba23cfbe49a981a47ac4cd12a1ea7d
39.690909
140
0.736819
5.341289
false
false
false
false
jguerinet/android-utils
date/src/main/java/com/guerinet/suitcase/date/extensions/InstantExt.kt
2
1541
/* * Copyright 2016-2021 Julien Guerinet * * 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.guerinet.suitcase.date.extensions import kotlinx.datetime.Clock import kotlinx.datetime.Instant import kotlinx.datetime.LocalDate import kotlinx.datetime.TimeZone import kotlinx.datetime.toLocalDateTime /** * ZonedDateTime extensions * @author Julien Guerinet * @since 2.3.0 */ /** * Converts this instant into a [LocalDate] */ fun Instant.toLocalDate(): LocalDate = this.toLocalDateTime(TimeZone.currentSystemDefault()).date /** * True if this [Instant] is in the past, false otherwise (today would return false) */ val Instant.isPast: Boolean get() = Clock.System.now() > this /** * True if this [Instant] is today (regardless of the time), false otherwise */ val Instant.isToday: Boolean get() = this.toLocalDate() == LocalDate.today /** * True if this [Instant] is in the future, false otherwise (today would return false) */ val Instant.isFuture: Boolean get() = Clock.System.now() < this
apache-2.0
bc03b134bbdf4eb927c637db5173adfd
28.634615
97
0.734588
4.023499
false
false
false
false
google/intellij-community
plugins/kotlin/plugin-updater/src/org/jetbrains/kotlin/idea/versions/UnsupportedAbiVersionNotificationPanelProvider.kt
1
15483
// 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.versions import com.intellij.icons.AllIcons import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.compiler.CompilerManager import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.IndexNotReadyException import com.intellij.openapi.project.Project import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.PopupStep import com.intellij.openapi.ui.popup.util.BaseListPopupStep import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.* import com.intellij.ui.EditorNotificationProvider.* import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NotNull import org.jetbrains.kotlin.idea.* import org.jetbrains.kotlin.idea.base.util.createComponentActionLabel import org.jetbrains.kotlin.idea.compiler.configuration.KotlinIdePlugin import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout import org.jetbrains.kotlin.idea.projectConfiguration.KotlinNotConfiguredSuppressedModulesState import org.jetbrains.kotlin.idea.projectConfiguration.LibraryJarDescriptor import org.jetbrains.kotlin.idea.projectConfiguration.updateLibraries import org.jetbrains.kotlin.idea.update.KotlinPluginUpdaterBundle import org.jetbrains.kotlin.idea.util.application.invokeLater import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.isKotlinFileType import org.jetbrains.kotlin.metadata.deserialization.BinaryVersion import java.awt.event.ComponentAdapter import java.awt.event.ComponentEvent import java.util.function.Function import javax.swing.Icon import javax.swing.JComponent import javax.swing.JLabel import javax.swing.event.HyperlinkEvent class UnsupportedAbiVersionNotificationPanelProvider : EditorNotificationProvider { private fun doCreate(fileEditor: FileEditor, project: Project, badVersionedRoots: Collection<BinaryVersionedFile<BinaryVersion>>): EditorNotificationPanel { val answer = ErrorNotificationPanel(fileEditor) val badRootFiles = badVersionedRoots.map { it.file } val badRuntimeLibraries: List<Library> = ArrayList<Library>().also { list -> project.forEachAllUsedLibraries { library -> val runtimeJar = LibraryJarDescriptor.STDLIB_JAR.findExistingJar(library)?.let { VfsUtil.getLocalFile(it) } val jsLibJar = LibraryJarDescriptor.JS_STDLIB_JAR.findExistingJar(library)?.let { VfsUtil.getLocalFile(it) } if (badRootFiles.contains(runtimeJar) || badRootFiles.contains(jsLibJar)) { list.add(library) } return@forEachAllUsedLibraries true } } val isPluginOldForAllRoots = badVersionedRoots.all { it.supportedVersion < it.version } val isPluginNewForAllRoots = badVersionedRoots.all { it.supportedVersion > it.version } when { badRuntimeLibraries.isNotEmpty() -> { val badRootsInRuntimeLibraries = findBadRootsInRuntimeLibraries(badRuntimeLibraries, badVersionedRoots) val otherBadRootsCount = badVersionedRoots.size - badRootsInRuntimeLibraries.size val text = KotlinPluginUpdaterBundle.htmlMessage( "html.b.0.choice.0.1.1.some.kotlin.runtime.librar.0.choice.0.1.y.1.ies.b.1.choice.0.1.and.one.other.jar.1.and.1.other.jars.1.choice.0.has.0.have.an.unsupported.binary.format.html", badRuntimeLibraries.size, otherBadRootsCount ) answer.text = text if (isPluginOldForAllRoots) { createUpdatePluginLink(answer) } val isPluginOldForAllRuntimeLibraries = badRootsInRuntimeLibraries.all { it.supportedVersion < it.version } val isPluginNewForAllRuntimeLibraries = badRootsInRuntimeLibraries.all { it.supportedVersion > it.version } val updateAction = when { isPluginNewForAllRuntimeLibraries -> KotlinPluginUpdaterBundle.message("button.text.update.library") isPluginOldForAllRuntimeLibraries -> KotlinPluginUpdaterBundle.message("button.text.downgrade.library") else -> KotlinPluginUpdaterBundle.message("button.text.replace.library") } val actionLabelText = "$updateAction " + KotlinPluginUpdaterBundle.message( "0.choice.0.1.1.all.kotlin.runtime.librar.0.choice.0.1.y.1.ies", badRuntimeLibraries.size ) answer.createActionLabel(actionLabelText) { ApplicationManager.getApplication().invokeLater { val newArtifactVersion = KotlinPluginLayout.standaloneCompilerVersion.artifactVersion updateLibraries(project, newArtifactVersion, badRuntimeLibraries) } } } badVersionedRoots.size == 1 -> { val badVersionedRoot = badVersionedRoots.first() val presentableName = badVersionedRoot.file.presentableName when { isPluginOldForAllRoots -> { answer.text = KotlinPluginUpdaterBundle.htmlMessage( "html.kotlin.library.b.0.b.was.compiled.with.a.newer.kotlin.compiler.and.can.t.be.read.please.update.kotlin.plugin.html", presentableName ) createUpdatePluginLink(answer) } isPluginNewForAllRoots -> answer.text = KotlinPluginUpdaterBundle.htmlMessage( "html.kotlin.library.b.0.b.has.outdated.binary.format.and.can.t.be.read.by.current.plugin.please.update.the.library.html", presentableName ) else -> { throw IllegalStateException("Bad root with compatible version found: $badVersionedRoot") } } answer.createActionLabel(KotlinPluginUpdaterBundle.message("button.text.go.to.0", presentableName)) { navigateToLibraryRoot( project, badVersionedRoot.file ) } } isPluginOldForAllRoots -> { answer.text = KotlinPluginUpdaterBundle.message("some.kotlin.libraries.attached.to.this.project.were.compiled.with.a.newer.kotlin.compiler.and.can.t.be.read.please.update.kotlin.plugin") createUpdatePluginLink(answer) } isPluginNewForAllRoots -> answer.setText( KotlinPluginUpdaterBundle.message("some.kotlin.libraries.attached.to.this.project.have.outdated.binary.format.and.can.t.be.read.by.current.plugin.please.update.found.libraries") ) else -> answer.setText(KotlinPluginUpdaterBundle.message("some.kotlin.libraries.attached.to.this.project.have.unsupported.binary.format.please.update.the.libraries.or.the.plugin")) } createShowPathsActionLabel(project, badVersionedRoots, answer, KotlinPluginUpdaterBundle.message("button.text.details")) return answer } private fun createShowPathsActionLabel( project: Project, badVersionedRoots: Collection<BinaryVersionedFile<BinaryVersion>>, answer: EditorNotificationPanel, @NlsContexts.LinkLabel labelText: String ) { answer.createComponentActionLabel(labelText) { label -> val task = { assert(!badVersionedRoots.isEmpty()) { "This action should only be called when bad roots are present" } val listPopupModel = LibraryRootsPopupModel( KotlinPluginUpdaterBundle.message("unsupported.format.plugin.version.0", KotlinIdePlugin.version), project, badVersionedRoots ) val popup = JBPopupFactory.getInstance().createListPopup(listPopupModel) popup.showUnderneathOf(label) null } DumbService.getInstance(project).tryRunReadActionInSmartMode( task, KotlinPluginUpdaterBundle.message("can.t.show.all.paths.during.index.update") ) } } private fun createUpdatePluginLink(answer: ErrorNotificationPanel) { answer.createProgressAction( KotlinPluginUpdaterBundle.message("progress.action.text.check"), KotlinPluginUpdaterBundle.message("progress.action.text.update.plugin") ) { link, updateLink -> KotlinPluginUpdater.getInstance().runCachedUpdate { pluginUpdateStatus -> when (pluginUpdateStatus) { is PluginUpdateStatus.Update -> { link.isVisible = false updateLink.isVisible = true updateLink.addHyperlinkListener(object : HyperlinkAdapter() { override fun hyperlinkActivated(e: HyperlinkEvent) { KotlinPluginUpdater.getInstance().installPluginUpdate(pluginUpdateStatus) } }) } is PluginUpdateStatus.LatestVersionInstalled -> { link.text = KotlinPluginUpdaterBundle.message("no.updates.found") } else -> {} } false // do not auto-retry update check } } } override fun collectNotificationData(project: Project, file: VirtualFile): Function<in FileEditor, out JComponent?>? { if (!file.isKotlinFileType()) { return null } try { if ( DumbService.isDumb(project) || isUnitTestMode() || CompilerManager.getInstance(project).isExcludedFromCompilation(file) || KotlinNotConfiguredSuppressedModulesState.isSuppressed(project) ) { return null } val module = ModuleUtilCore.findModuleForFile(file, project) ?: return null val badRoots: Collection<BinaryVersionedFile<BinaryVersion>> = getLibraryRootsWithIncompatibleAbi(module) .takeUnless(Collection<BinaryVersionedFile<BinaryVersion>>::isEmpty) ?: return null return Function { doCreate(it, project, badRoots) } } catch (e: ProcessCanceledException) { // Ignore } catch (e: IndexNotReadyException) { DumbService.getInstance(project).runWhenSmart { updateNotifications(project) } } return null } private fun findBadRootsInRuntimeLibraries( badRuntimeLibraries: List<Library>, badVersionedRoots: Collection<BinaryVersionedFile<BinaryVersion>> ): ArrayList<BinaryVersionedFile<BinaryVersion>> { val badRootsInLibraries = ArrayList<BinaryVersionedFile<BinaryVersion>>() fun addToBadRoots(file: VirtualFile?) { if (file != null) { val runtimeJarBadRoot = badVersionedRoots.firstOrNull { it.file == file } if (runtimeJarBadRoot != null) { badRootsInLibraries.add(runtimeJarBadRoot) } } } badRuntimeLibraries.forEach { library -> for (descriptor in LibraryJarDescriptor.values()) { addToBadRoots(descriptor.findExistingJar(library)?.let<VirtualFile, @NotNull VirtualFile> { VfsUtil.getLocalFile(it) }) } } return badRootsInLibraries } private class LibraryRootsPopupModel( @NlsContexts.PopupTitle title: String, private val project: Project, roots: Collection<BinaryVersionedFile<BinaryVersion>> ) : BaseListPopupStep<BinaryVersionedFile<BinaryVersion>>(title, *roots.toTypedArray()) { override fun getTextFor(root: BinaryVersionedFile<BinaryVersion>): String { val relativePath = VfsUtilCore.getRelativePath(root.file, project.baseDir, '/') return KotlinPluginUpdaterBundle.message("0.1.expected.2", relativePath ?: root.file.path, root.version, root.supportedVersion) } override fun getIconFor(aValue: BinaryVersionedFile<BinaryVersion>): Icon = if (aValue.file.isDirectory) { AllIcons.Nodes.Folder } else { AllIcons.FileTypes.Archive } override fun onChosen(selectedValue: BinaryVersionedFile<BinaryVersion>, finalChoice: Boolean): PopupStep<*>? { navigateToLibraryRoot(project, selectedValue.file) return PopupStep.FINAL_CHOICE } override fun isSpeedSearchEnabled(): Boolean = true } private class ErrorNotificationPanel(fileEditor: FileEditor) : EditorNotificationPanel(fileEditor, Status.Error) { init { myLabel.icon = AllIcons.General.Error } fun createProgressAction(@Nls text: String, @Nls successLinkText: String, updater: (JLabel, HyperlinkLabel) -> Unit) { val label = JLabel(text) myLinksPanel.add(label) val successLink = createActionLabel(successLinkText) { } successLink.isVisible = false // Several notification panels can be created almost instantly but we want to postpone deferred checks until // panels are actually visible on screen. myLinksPanel.addComponentListener(object : ComponentAdapter() { var isUpdaterCalled = false override fun componentResized(p0: ComponentEvent?) { if (!isUpdaterCalled) { isUpdaterCalled = true updater(label, successLink) } } }) } } private fun updateNotifications(project: Project) { invokeLater { if (!project.isDisposed) { EditorNotifications.getInstance(project).updateAllNotifications() } } } companion object { private fun navigateToLibraryRoot(project: Project, root: VirtualFile) { OpenFileDescriptor(project, root).navigate(true) } } } private operator fun BinaryVersion.compareTo(other: BinaryVersion): Int { val first = this.toArray() val second = other.toArray() for (i in 0 until maxOf(first.size, second.size)) { val thisPart = first.getOrNull(i) ?: -1 val otherPart = second.getOrNull(i) ?: -1 if (thisPart != otherPart) { return thisPart - otherPart } } return 0 }
apache-2.0
ae542c474f3ab49c6b4bcfa7176923e1
43.748555
200
0.643738
5.23605
false
false
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/ide/customize/transferSettings/providers/vscode/parsers/GeneralSettingsParser.kt
1
2804
package com.intellij.ide.customize.transferSettings.providers.vscode.parsers import com.fasterxml.jackson.core.JsonFactory import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.node.JsonNodeType import com.fasterxml.jackson.databind.node.ObjectNode import com.intellij.ide.customize.transferSettings.db.KnownLafs import com.intellij.ide.customize.transferSettings.models.ILookAndFeel import com.intellij.ide.customize.transferSettings.models.Settings import com.intellij.ide.customize.transferSettings.models.SystemDarkThemeDetectorLookAndFeel import com.intellij.ide.customize.transferSettings.providers.vscode.mappings.ThemesMappings import com.intellij.openapi.diagnostic.logger import java.io.File class GeneralSettingsParser(private val settings: Settings) { private val logger = logger<GeneralSettingsParser>() companion object { private const val COLOR_THEME = "workbench.colorTheme" private const val AUTODETECT_THEME = "window.autoDetectColorScheme" private const val PREFERRED_DARK_THEME = "workbench.preferredDarkColorTheme" private const val PREFERRED_LIGHT_THEME = "workbench.preferredLightColorTheme" } fun process(file: File) = try { logger.info("Processing a general settings file: $file") val root = ObjectMapper(JsonFactory().enable(JsonParser.Feature.ALLOW_COMMENTS)).readTree(file) as? ObjectNode ?: error("Unexpected JSON data; expected: ${JsonNodeType.OBJECT}") processThemeAndScheme(root) processAutodetectTheme(root) } catch (t: Throwable) { logger.warn(t) } private fun processThemeAndScheme(root: ObjectNode) { try { val theme = root[COLOR_THEME]?.textValue() ?: return val laf = ThemesMappings.themeMap(theme) settings.laf = laf } catch (t: Throwable) { logger.warn(t) } } private fun processAutodetectTheme(root: ObjectNode) { var lightLaf: ILookAndFeel? = null var darkLaf: ILookAndFeel? = null try { val preferredDarkTheme = root[PREFERRED_DARK_THEME]?.textValue() ?: return val laf = ThemesMappings.themeMap(preferredDarkTheme) darkLaf = laf } catch (t: Throwable) { logger.warn(t) } try { val preferredLightTheme = root[PREFERRED_LIGHT_THEME]?.textValue() ?: return val laf = ThemesMappings.themeMap(preferredLightTheme) lightLaf = laf } catch (t: Throwable) { logger.warn(t) } try { val autodetectTheme = root[AUTODETECT_THEME]?.booleanValue() ?: return if (autodetectTheme) { settings.laf = SystemDarkThemeDetectorLookAndFeel(darkLaf ?: KnownLafs.Darcula, lightLaf ?: KnownLafs.Light) } } catch (t: Throwable) { logger.warn(t) } } }
apache-2.0
a485552d363066505be46c10530ca39b
34.0625
116
0.731455
4.178838
false
false
false
false
JetBrains/intellij-community
platform/lang-api/src/com/intellij/codeInsight/hints/InlayHintsProvider.kt
1
8165
// 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 import com.intellij.lang.Language import com.intellij.openapi.application.ApplicationBundle import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.options.UnnamedConfigurable import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsContexts import com.intellij.psi.PsiFile import com.intellij.psi.PsiFileFactory import com.intellij.util.xmlb.annotations.Property import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.Nls import javax.swing.JComponent import kotlin.reflect.KMutableProperty0 enum class InlayGroup(val key: String, @Nls val description: String? = null) { CODE_VISION_GROUP_NEW("settings.hints.new.group.code.vision", ApplicationBundle.message("settings.hints.new.group.code.vision.description")), CODE_VISION_GROUP("settings.hints.group.code.vision", ApplicationBundle.message("settings.hints.new.group.code.vision.description")), PARAMETERS_GROUP("settings.hints.group.parameters", ApplicationBundle.message("settings.hints.group.parameters.description")), TYPES_GROUP("settings.hints.group.types", ApplicationBundle.message("settings.hints.group.types.description")), VALUES_GROUP("settings.hints.group.values", ApplicationBundle.message("settings.hints.group.values.description")), ANNOTATIONS_GROUP("settings.hints.group.annotations", ApplicationBundle.message("settings.hints.group.annotations.description")), METHOD_CHAINS_GROUP("settings.hints.group.method.chains"), LAMBDAS_GROUP("settings.hints.group.lambdas", ApplicationBundle.message("settings.hints.group.lambdas.description")), CODE_AUTHOR_GROUP("settings.hints.group.code.author", ApplicationBundle.message("settings.hints.group.code.author.description")), URL_PATH_GROUP("settings.hints.group.url.path", ApplicationBundle.message("settings.hints.group.url.path.description")), OTHER_GROUP("settings.hints.group.other"); override fun toString(): @Nls String { return ApplicationBundle.message(key) }} /** * ATTENTION! Consider using [com.intellij.codeInsight.hints.declarative.InlayHintsProvider] whenever possible! * It is order of magnitude faster, much simpler and less error-prone. This class is very likely to be deprecated in the future. * * Provider of inlay hints for single language. If you need to create hints for multiple languages, please use [InlayHintsProviderFactory]. * Both block and inline hints collection are supported. * Block hints draws between lines of code text. Inline ones are placed on the code text line (like parameter hints) * * @param T settings type of this provider, if no settings required, please, use [NoSettings] * @see com.intellij.openapi.editor.InlayModel.addInlineElement * @see com.intellij.openapi.editor.InlayModel.addBlockElement * * To test it you may use InlayHintsProviderTestCase. * Mark as [com.intellij.openapi.project.DumbAware] to enable it in dumb mode. */ @JvmDefaultWithCompatibility interface InlayHintsProvider<T : Any> { /** * If this method is called, provider is enabled for this file * Warning! Your collector should not use any settings besides [settings] */ fun getCollectorFor(file: PsiFile, editor: Editor, settings: T, sink: InlayHintsSink): InlayHintsCollector? /** * Returns quick collector of placeholders. * Placeholders are shown on editor opening and stay until [getCollectorFor] collector hints are calculated. */ @ApiStatus.Experimental fun getPlaceholdersCollectorFor(file: PsiFile, editor: Editor, settings: T, sink: InlayHintsSink): InlayHintsCollector? = null /** * Settings must be plain java object, fields of these settings will be copied via serialization. * Must implement `equals` method, otherwise settings won't be able to track modification. * Returned object will be used to create configurable and collector. * It persists automatically. */ fun createSettings(): T @get:Nls(capitalization = Nls.Capitalization.Sentence) /** * Name of this kind of hints. It will be used in settings and in context menu. * Please, do not use word "hints" to avoid duplication */ val name: String val group: InlayGroup get() = InlayGroup.OTHER_GROUP /** * Used for persisting settings. */ val key: SettingsKey<T> val description: String? @Nls get() { return getProperty("inlay." + key.id + ".description") } /** * Text, that will be used in the settings as a preview. */ val previewText: String? /** * Creates configurable, that immediately applies changes from UI to [settings]. */ fun createConfigurable(settings: T): ImmediateConfigurable /** * Checks whether the language is accepted by the provider. */ fun isLanguageSupported(language: Language): Boolean = true fun createFile(project: Project, fileType: FileType, document: Document): PsiFile { val factory = PsiFileFactory.getInstance(project) return factory.createFileFromText("dummy", fileType, document.text) } @Nls fun getProperty(key: String): String? = null fun preparePreview(editor: Editor, file: PsiFile, settings: T) { } @Nls fun getCaseDescription(case: ImmediateConfigurable.Case): String? { return getProperty("inlay." + this.key.id + "." + case.id) } val isVisibleInSettings: Boolean get() = true } /** * The same as [UnnamedConfigurable], but not waiting for apply() to save settings. */ interface ImmediateConfigurable { /** * Creates component, which listen to its components and immediately updates state of settings object * This is required to make preview in settings works instantly * Note, that if you need to express only cases of this provider, you should use [cases] instead */ fun createComponent(listener: ChangeListener): JComponent /** * Loads state from its configurable. */ fun reset() {} /** * Text, that will be used in settings for checkbox to enable/disable hints. */ val mainCheckboxText: String get() = "Show hints" val cases : List<Case> get() = emptyList() class Case( @Nls val name: String, val id: String, private val loadFromSettings: () -> Boolean, private val onUserChanged: (newValue: Boolean) -> Unit, @NlsContexts.DetailedDescription val extendedDescription: String? = null ) { var value: Boolean get() = loadFromSettings() set(value) = onUserChanged(value) constructor(@Nls name: String, id: String, property: KMutableProperty0<Boolean>, @NlsContexts.DetailedDescription extendedDescription: String? = null) : this( name, id, { property.get() }, {property.set(it)}, extendedDescription ) } } interface ChangeListener { /** * This method should be called on any change of corresponding settings. */ fun settingsChanged() } /** * This class should be used if provider should not have settings. If you use e.g. [Unit] you will have annoying warning in logs. */ @Property(assertIfNoBindings = false) class NoSettings { override fun equals(other: Any?): Boolean = other is NoSettings override fun hashCode(): Int { return javaClass.hashCode() } } /** * Similar to [com.intellij.openapi.util.Key], but it also requires language to be unique. * Allows type-safe access to settings of provider. */ data class SettingsKey<T>(val id: String) { companion object { fun getFullId(languageId: String, keyId: String): String { return "$languageId.$keyId" } } fun getFullId(language: Language): String = getFullId(language.id, id) } interface AbstractSettingsKey<T: Any> { fun getFullId(language: Language): String } data class InlayKey<T: Any, C: Any>(val id: String) : AbstractSettingsKey<T>, ContentKey<C> { override fun getFullId(language: Language): String = language.id + "." + id } /** * Allows type-safe access to content of the root presentation. */ interface ContentKey<C: Any>
apache-2.0
2536087838260ecdc6430eddd3d47cfd
35.293333
162
0.738641
4.283841
false
false
false
false
JetBrains/intellij-community
plugins/git4idea/src/git4idea/checkin/GitCheckinHandlerFactory.kt
1
14784
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package git4idea.checkin import com.intellij.CommonBundle import com.intellij.ide.BrowserUtil import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.coroutineToIndicator import com.intellij.openapi.progress.progressSink import com.intellij.openapi.progress.runModalTask import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DoNotAskOption import com.intellij.openapi.ui.MessageDialogBuilder import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.Ref import com.intellij.openapi.util.text.HtmlBuilder import com.intellij.openapi.util.text.HtmlChunk import com.intellij.openapi.vcs.CheckinProjectPanel import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.changes.ChangesUtil import com.intellij.openapi.vcs.changes.CommitContext import com.intellij.openapi.vcs.changes.CommitExecutor import com.intellij.openapi.vcs.checkin.* import com.intellij.openapi.vfs.VirtualFile import com.intellij.vcs.log.VcsUser import git4idea.GitUserRegistry import git4idea.GitUtil import git4idea.GitVcs import git4idea.commands.Git import git4idea.config.GitConfigUtil import git4idea.config.GitVcsSettings import git4idea.crlf.GitCrlfDialog import git4idea.crlf.GitCrlfProblemsDetector import git4idea.crlf.GitCrlfUtil import git4idea.i18n.GitBundle import git4idea.rebase.GitRebaseUtils import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.jetbrains.annotations.Nls abstract class GitCheckinHandlerFactory : VcsCheckinHandlerFactory(GitVcs.getKey()) class GitUserNameCheckinHandlerFactory : GitCheckinHandlerFactory() { override fun createVcsHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler { return GitUserNameCheckinHandler(panel.project) } } class GitCRLFCheckinHandlerFactory : GitCheckinHandlerFactory() { override fun createVcsHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler { return GitCRLFCheckinHandler(panel.project) } } class GitDetachedRootCheckinHandlerFactory : GitCheckinHandlerFactory() { override fun createVcsHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler { return GitDetachedRootCheckinHandler(panel.project) } } private class GitCRLFCheckinHandler(project: Project) : GitCheckinHandler(project) { override fun getExecutionOrder(): CommitCheck.ExecutionOrder = CommitCheck.ExecutionOrder.EARLY override fun isEnabled(): Boolean { return GitVcsSettings.getInstance(project).warnAboutCrlf() } override suspend fun runCheck(commitInfo: CommitInfo): CommitProblem? { val git = Git.getInstance() val files = commitInfo.committedVirtualFiles // Deleted files aren't included. But for them, we don't care about CRLFs. val shouldWarn = withContext(Dispatchers.Default) { coroutineContext.progressSink?.update(GitBundle.message("progress.checking.line.separator.issues")) coroutineToIndicator { GitCrlfProblemsDetector.detect(project, git, files).shouldWarn() } } if (!shouldWarn) return null val dialog = GitCrlfDialog(project) dialog.show() val decision = dialog.exitCode val dontWarnAgain = dialog.dontWarnAgain() if (decision == GitCrlfDialog.CANCEL) { return GitCRLFCommitProblem() } if (decision == GitCrlfDialog.SET) { val anyRoot = commitInfo.committedChanges.asSequence() .mapNotNull { ProjectLevelVcsManager.getInstance(project).getVcsRootObjectFor(ChangesUtil.getFilePath(it)) } .filter { it.vcs is GitVcs } .map { it.path } .firstOrNull() if (anyRoot != null) { setCoreAutoCrlfAttribute(project, anyRoot) } } else if (dontWarnAgain) { val settings = GitVcsSettings.getInstance(project) settings.setWarnAboutCrlf(false) } return null } private fun setCoreAutoCrlfAttribute(project: Project, anyRoot: VirtualFile) { runModalTask(GitBundle.message("progress.setting.config.value"), project, true) { try { GitConfigUtil.setValue(project, anyRoot, GitConfigUtil.CORE_AUTOCRLF, GitCrlfUtil.RECOMMENDED_VALUE, "--global") } catch (e: VcsException) { // it is not critical: the user just will get the dialog again next time logger<GitCRLFCheckinHandler>().warn("Couldn't globally set core.autocrlf in $anyRoot", e) } } } private class GitCRLFCommitProblem : CommitProblem { override val text: String get() = GitBundle.message("text.crlf.fix.notification.description.warning") override fun showModalSolution(project: Project, commitInfo: CommitInfo): ReturnResult { return ReturnResult.CANCEL // dialog was already shown } } } private class GitUserNameCheckinHandler(project: Project) : GitCheckinHandler(project) { override fun getExecutionOrder(): CommitCheck.ExecutionOrder = CommitCheck.ExecutionOrder.LATE override fun isEnabled(): Boolean = true override suspend fun runCheck(commitInfo: CommitInfo): CommitProblem? { if (commitInfo.commitContext.commitAuthor != null) return null val vcs = GitVcs.getInstance(project) val affectedRoots = getSelectedRoots(commitInfo) val defined = getDefinedUserNames(project, affectedRoots, false) val allRoots = ProjectLevelVcsManager.getInstance(project).getRootsUnderVcs(vcs).toMutableList() val notDefined = affectedRoots.toMutableList() notDefined.removeAll(defined.keys) if (notDefined.isEmpty()) return null // try to find a root with defined user name among other roots - to propose this user name in the dialog if (defined.isEmpty() && allRoots.size > affectedRoots.size) { allRoots.removeAll(affectedRoots) defined.putAll(getDefinedUserNames(project, allRoots, true)) } val dialog = GitUserNameNotDefinedDialog(project, notDefined, affectedRoots, defined) if (!dialog.showAndGet()) return GitUserNameCommitProblem(closeWindow = true) if (setUserNameUnderProgress(project, notDefined, dialog)) { return null } return GitUserNameCommitProblem(closeWindow = false) } private suspend fun getDefinedUserNames(project: Project, roots: Collection<VirtualFile>, stopWhenFoundFirst: Boolean): MutableMap<VirtualFile, VcsUser> { return withContext(Dispatchers.Default) { coroutineToIndicator { val defined = HashMap<VirtualFile, VcsUser>() for (root in roots) { val user = GitUserRegistry.getInstance(project).readUser(root) ?: continue defined[root] = user if (stopWhenFoundFirst) { break } } defined } } } private fun setUserNameUnderProgress(project: Project, notDefined: Collection<VirtualFile>, dialog: GitUserNameNotDefinedDialog): Boolean { val error = Ref.create<@Nls String?>() runModalTask(GitBundle.message("progress.setting.user.name.email"), project, true) { try { if (dialog.isSetGlobalConfig) { GitConfigUtil.setValue(project, notDefined.iterator().next(), GitConfigUtil.USER_NAME, dialog.userName, "--global") GitConfigUtil.setValue(project, notDefined.iterator().next(), GitConfigUtil.USER_EMAIL, dialog.userEmail, "--global") } else { for (root in notDefined) { GitConfigUtil.setValue(project, root, GitConfigUtil.USER_NAME, dialog.userName) GitConfigUtil.setValue(project, root, GitConfigUtil.USER_EMAIL, dialog.userEmail) } } } catch (e: VcsException) { logger<GitUserNameCheckinHandler>().error("Couldn't set user.name and user.email", e) error.set(GitBundle.message("error.cant.set.user.name.email")) } } if (error.isNull) { return true } else { Messages.showErrorDialog(project, error.get(), CommonBundle.getErrorTitle()) return false } } private class GitUserNameCommitProblem(val closeWindow: Boolean) : CommitProblem { override val text: String get() = GitBundle.message("commit.check.warning.user.name.email.not.set") override fun showModalSolution(project: Project, commitInfo: CommitInfo): ReturnResult { // dialog was already shown if (closeWindow) { return ReturnResult.CLOSE_WINDOW } else { return ReturnResult.CANCEL } } } } private class GitDetachedRootCheckinHandler(project: Project) : GitCheckinHandler(project) { override fun getExecutionOrder(): CommitCheck.ExecutionOrder = CommitCheck.ExecutionOrder.EARLY override fun isEnabled(): Boolean { return GitVcsSettings.getInstance(project).warnAboutDetachedHead() } override suspend fun runCheck(commitInfo: CommitInfo): CommitProblem? { val detachedRoot = getDetachedRoot(commitInfo) if (detachedRoot == null) return null if (detachedRoot.isDuringRebase) { return GitRebaseCommitProblem(detachedRoot.root) } else { return GitDetachedRootCommitProblem(detachedRoot.root) } } companion object { private const val DETACHED_HEAD_HELP_LINK = "https://git-scm.com/docs/git-checkout#_detached_head" private const val REBASE_HELP_LINK = "https://git-scm.com/docs/git-rebase" private fun detachedHeadDoNotAsk(project: Project): DoNotAskOption { return object : DoNotAskOption.Adapter() { override fun rememberChoice(isSelected: Boolean, exitCode: Int) { GitVcsSettings.getInstance(project).setWarnAboutDetachedHead(!isSelected) } override fun getDoNotShowMessage(): String { return GitBundle.message("checkbox.dont.warn.again") } } } } private class GitRebaseCommitProblem(val root: VirtualFile) : CommitProblemWithDetails { override val text: String get() = GitBundle.message("commit.check.warning.title.commit.during.rebase", root.presentableUrl) override fun showModalSolution(project: Project, commitInfo: CommitInfo): ReturnResult { val title = GitBundle.message("warning.title.commit.with.unfinished.rebase") val message = HtmlBuilder() .appendRaw(GitBundle.message("warning.message.commit.with.unfinished.rebase", HtmlChunk.text(root.presentableUrl).bold().toString())) .br() .appendLink(REBASE_HELP_LINK, GitBundle.message("link.label.commit.with.unfinished.rebase.read.more")) val commit = MessageDialogBuilder.okCancel(title, message.wrapWithHtmlBody().toString()) .yesText(commitInfo.commitActionText) .icon(Messages.getWarningIcon()) .doNotAsk(detachedHeadDoNotAsk(project)) .ask(project) if (commit) { return ReturnResult.COMMIT } else { return ReturnResult.CLOSE_WINDOW } } override val showDetailsLink: String? get() = GitBundle.message("commit.check.warning.title.commit.during.rebase.details") override val showDetailsAction: String get() = GitBundle.message("commit.check.warning.title.commit.during.rebase.details") override fun showDetails(project: Project) { BrowserUtil.browse(REBASE_HELP_LINK) } } private class GitDetachedRootCommitProblem(val root: VirtualFile) : CommitProblemWithDetails { override val text: String get() = GitBundle.message("commit.check.warning.title.commit.with.detached.head", root.presentableUrl) override fun showModalSolution(project: Project, commitInfo: CommitInfo): ReturnResult { val title = GitBundle.message("warning.title.commit.with.detached.head") val message = HtmlBuilder() .appendRaw(GitBundle.message("warning.message.commit.with.detached.head", HtmlChunk.text(root.presentableUrl).bold().toString())) .br() .appendLink(DETACHED_HEAD_HELP_LINK, GitBundle.message("link.label.commit.with.detached.head.read.more")) val commit = MessageDialogBuilder.okCancel(title, message.wrapWithHtmlBody().toString()) .yesText(commitInfo.commitActionText) .icon(Messages.getWarningIcon()) .doNotAsk(detachedHeadDoNotAsk(project)) .ask(project) if (commit) { return ReturnResult.COMMIT } else { return ReturnResult.CLOSE_WINDOW } } override val showDetailsLink: String? get() = GitBundle.message("commit.check.warning.title.commit.with.detached.head.details") override val showDetailsAction: String get() = GitBundle.message("commit.check.warning.title.commit.with.detached.head.details") override fun showDetails(project: Project) { BrowserUtil.browse(DETACHED_HEAD_HELP_LINK) } } /** * Scans the Git roots, selected for commit, for the root which is on a detached HEAD. * Returns null if all repositories are on the branch. * There might be several detached repositories - in that case, only one is returned. * This is because the situation is very rare, while it requires a lot of additional effort of making a well-formed message. */ private fun getDetachedRoot(commitInfo: CommitInfo): DetachedRoot? { val repositoryManager = GitUtil.getRepositoryManager(project) for (root in getSelectedRoots(commitInfo)) { val repository = repositoryManager.getRepositoryForRootQuick(root) ?: continue if (!repository.isOnBranch && !GitRebaseUtils.isInteractiveRebaseInProgress(repository)) { return DetachedRoot(root, repository.isRebaseInProgress) } } return null } private class DetachedRoot(val root: VirtualFile, val isDuringRebase: Boolean) } private abstract class GitCheckinHandler(val project: Project) : CheckinHandler(), CommitCheck { override fun acceptExecutor(executor: CommitExecutor?): Boolean { return (executor == null || executor is GitCommitAndPushExecutor) && super.acceptExecutor(executor) } protected fun getSelectedRoots(commitInfo: CommitInfo): Collection<VirtualFile> { val vcsManager = ProjectLevelVcsManager.getInstance(project) val git = GitVcs.getInstance(project) val result = mutableSetOf<VirtualFile>() for (path in ChangesUtil.getPaths(commitInfo.committedChanges)) { val vcsRoot = vcsManager.getVcsRootObjectFor(path) if (vcsRoot != null) { val root = vcsRoot.path if (git == vcsRoot.vcs) { result.add(root) } } } return result } }
apache-2.0
3e3ffa1d9007239d2daebbef4c7e505d
38.111111
127
0.719291
4.570015
false
false
false
false
spacecowboy/Feeder
app/src/main/java/com/nononsenseapps/feeder/ui/compose/feedarticle/FeedArticleScreens.kt
1
66686
package com.nononsenseapps.feeder.ui.compose.feedarticle import android.content.Intent import androidx.activity.compose.BackHandler import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.annotation.DrawableRes import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.animation.core.MutableTransitionState import androidx.compose.animation.core.tween import androidx.compose.animation.slideInHorizontally import androidx.compose.animation.slideOutHorizontally import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.WindowInsetsSides import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.navigationBars import androidx.compose.foundation.layout.only import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.statusBars import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.lazy.staggeredgrid.LazyStaggeredGridState import androidx.compose.foundation.lazy.staggeredgrid.rememberLazyStaggeredGridState import androidx.compose.material.IconToggleButton import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Article import androidx.compose.material.icons.filled.Bookmark import androidx.compose.material.icons.filled.BookmarkRemove import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.DoneAll import androidx.compose.material.icons.filled.Edit import androidx.compose.material.icons.filled.Email import androidx.compose.material.icons.filled.ImportExport import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material.icons.filled.OpenInBrowser import androidx.compose.material.icons.filled.PushPin import androidx.compose.material.icons.filled.Refresh import androidx.compose.material.icons.filled.Settings import androidx.compose.material.icons.filled.Share import androidx.compose.material.icons.filled.Visibility import androidx.compose.material.icons.filled.VisibilityOff import androidx.compose.material3.DismissibleDrawerSheet import androidx.compose.material3.DismissibleNavigationDrawer import androidx.compose.material3.Divider import androidx.compose.material3.DrawerState import androidx.compose.material3.DrawerValue import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.rememberDrawerState import androidx.compose.material3.rememberTopAppBarState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.key import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.stateDescription import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.navigation.NavController import androidx.paging.compose.LazyPagingItems import androidx.paging.compose.collectAsLazyPagingItems import com.nononsenseapps.feeder.ApplicationCoroutineScope import com.nononsenseapps.feeder.R import com.nononsenseapps.feeder.archmodel.TextToDisplay import com.nononsenseapps.feeder.blob.blobFile import com.nononsenseapps.feeder.blob.blobFullFile import com.nononsenseapps.feeder.blob.blobFullInputStream import com.nononsenseapps.feeder.blob.blobInputStream import com.nononsenseapps.feeder.db.room.ID_ALL_FEEDS import com.nononsenseapps.feeder.db.room.ID_UNSET import com.nononsenseapps.feeder.model.LocaleOverride import com.nononsenseapps.feeder.model.opml.exportOpml import com.nononsenseapps.feeder.model.opml.importOpml import com.nononsenseapps.feeder.ui.compose.feed.FeedGridContent import com.nononsenseapps.feeder.ui.compose.feed.FeedListContent import com.nononsenseapps.feeder.ui.compose.feed.FeedListItem import com.nononsenseapps.feeder.ui.compose.feed.FeedScreen import com.nononsenseapps.feeder.ui.compose.icons.CustomFilled import com.nononsenseapps.feeder.ui.compose.icons.TextToSpeech import com.nononsenseapps.feeder.ui.compose.navdrawer.DrawerFeed import com.nononsenseapps.feeder.ui.compose.navdrawer.DrawerItemWithUnreadCount import com.nononsenseapps.feeder.ui.compose.navdrawer.DrawerTag import com.nononsenseapps.feeder.ui.compose.navdrawer.DrawerTop import com.nononsenseapps.feeder.ui.compose.navdrawer.ListOfFeedsAndTags import com.nononsenseapps.feeder.ui.compose.navigation.EditFeedDestination import com.nononsenseapps.feeder.ui.compose.navigation.SearchFeedDestination import com.nononsenseapps.feeder.ui.compose.navigation.SettingsDestination import com.nononsenseapps.feeder.ui.compose.readaloud.HideableTTSPlayer import com.nononsenseapps.feeder.ui.compose.reader.ReaderView import com.nononsenseapps.feeder.ui.compose.reader.dateTimeFormat import com.nononsenseapps.feeder.ui.compose.reader.onLinkClick import com.nononsenseapps.feeder.ui.compose.text.htmlFormattedText import com.nononsenseapps.feeder.ui.compose.text.withBidiDeterminedLayoutDirection import com.nononsenseapps.feeder.ui.compose.theme.isLight import com.nononsenseapps.feeder.ui.compose.utils.ImmutableHolder import com.nononsenseapps.feeder.ui.compose.utils.ScreenType import com.nononsenseapps.feeder.ui.compose.utils.WindowSize import com.nononsenseapps.feeder.ui.compose.utils.getScreenType import com.nononsenseapps.feeder.util.openGitlabIssues import com.nononsenseapps.feeder.util.openLinkInBrowser import com.nononsenseapps.feeder.util.openLinkInCustomTab import com.nononsenseapps.feeder.util.unicodeWrap import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import org.kodein.di.compose.LocalDI import org.kodein.di.instance import org.threeten.bp.LocalDateTime import org.threeten.bp.ZonedDateTime @OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class) @Composable fun FeedArticleScreen( windowSize: WindowSize, navController: NavController, viewModel: FeedArticleViewModel, ) { val viewState: FeedArticleScreenViewState by viewModel.viewState.collectAsState() val pagedFeedItems = viewModel.currentFeedListItems.collectAsLazyPagingItems() val di = LocalDI.current val opmlExporter = rememberLauncherForActivityResult( ActivityResultContracts.CreateDocument("application/xml") ) { uri -> if (uri != null) { val applicationCoroutineScope: ApplicationCoroutineScope by di.instance() applicationCoroutineScope.launch { exportOpml(di, uri) } } } val opmlImporter = rememberLauncherForActivityResult( ActivityResultContracts.OpenDocument() ) { uri -> if (uri != null) { val applicationCoroutineScope: ApplicationCoroutineScope by di.instance() applicationCoroutineScope.launch { importOpml(di, uri) } } } val feedArticleScreenType = getFeedArticleScreenType( windowSize = windowSize, viewState = viewState, ) val context = LocalContext.current // Each feed gets its own scroll state. Persists across device rotations, but is cleared when // switching feeds val feedListState = key(viewState.currentFeedOrTag) { rememberLazyListState() } val feedGridState = key(viewState.currentFeedOrTag) { rememberLazyStaggeredGridState() } // Each article gets its own scroll state. Persists across device rotations, but is cleared // when switching articles. val articleListState = key(viewState.articleId) { rememberLazyListState() } val toolbarColor = MaterialTheme.colorScheme.surface.toArgb() FeedArticleScreen( feedArticleScreenType = feedArticleScreenType, viewState = viewState, onRefreshVisible = { viewModel.requestImmediateSyncOfCurrentFeedOrTag() }, onRefreshAll = { viewModel.requestImmediateSyncOfAll() }, onToggleOnlyUnread = { value -> viewModel.setShowOnlyUnread(value) }, onToggleOnlyBookmarked = { value -> viewModel.setShowOnlyBookmarked(value) }, onDrawerItemSelected = { feedId, tag -> viewModel.setCurrentFeedAndTag(feedId, tag) }, onMarkAllAsRead = { viewModel.markAllAsRead() }, onToggleTagExpansion = { tag -> viewModel.toggleTagExpansion(tag) }, onShowToolbarMenu = { visible -> viewModel.setToolbarMenuVisible(visible) }, ttsOnPlay = viewModel::ttsPlay, ttsOnPause = viewModel::ttsPause, ttsOnStop = viewModel::ttsStop, ttsOnSkipNext = viewModel::ttsSkipNext, ttsOnSelectLanguage = viewModel::ttsOnSelectLanguage, onAddFeed = { SearchFeedDestination.navigate(navController) }, onEditFeed = { feedId -> EditFeedDestination.navigate(navController, feedId) }, onShowEditDialog = { viewModel.setShowEditDialog(true) }, onDismissEditDialog = { viewModel.setShowEditDialog(false) }, onDeleteFeeds = { feedIds -> viewModel.deleteFeeds(feedIds.toList()) }, onShowDeleteDialog = { viewModel.setShowDeleteDialog(true) }, onDismissDeleteDialog = { viewModel.setShowDeleteDialog(false) }, onSettings = { SettingsDestination.navigate(navController) }, onSendFeedback = { context.startActivity(openGitlabIssues()) }, onImport = { opmlImporter.launch(arrayOf("text/plain", "text/xml", "text/opml", "*/*")) }, onExport = { opmlExporter.launch("feeder-export-${LocalDateTime.now()}.opml") }, markAsUnread = { itemId, unread -> if (unread) { viewModel.markAsUnread(itemId) } else { viewModel.markAsRead(itemId) } }, markBeforeAsRead = { index -> viewModel.markBeforeAsRead(index) }, markAfterAsRead = { index -> viewModel.markAfterAsRead(index) }, onOpenFeedItem = { itemId -> viewModel.openArticle( itemId = itemId, openInBrowser = { articleLink -> openLinkInBrowser(context, articleLink) }, openInCustomTab = { articleLink -> openLinkInCustomTab(context, articleLink, toolbarColor) } ) }, onInteractWithArticle = { viewModel.setArticleOpen(true) }, onToggleFullText = { if (viewState.textToDisplay == TextToDisplay.FULLTEXT) { viewModel.displayArticleText() } else { viewModel.displayFullText() } }, displayFullText = viewModel::displayFullText, onMarkAsUnread = { viewModel.markAsUnread(viewState.articleId) }, onShareArticle = { if (viewState.articleId > ID_UNSET) { val intent = Intent.createChooser( Intent(Intent.ACTION_SEND).apply { if (viewState.articleLink != null) { putExtra(Intent.EXTRA_TEXT, viewState.articleLink) } putExtra(Intent.EXTRA_TITLE, viewState.articleTitle) type = "text/plain" }, null ) context.startActivity(intent) } }, onOpenInCustomTab = { viewState.articleLink?.let { link -> openLinkInCustomTab(context, link, toolbarColor) } }, onFeedTitleClick = { viewModel.setCurrentFeedAndTag( viewState.articleFeedId, "" ) viewModel.setArticleOpen(false) }, onNavigateUpFromArticle = { viewModel.setArticleOpen(false) }, onToggleCurrentArticlePinned = { viewModel.setPinned(viewState.articleId, !viewState.isPinned) }, onSetPinned = { itemId, value -> viewModel.setPinned(itemId, value) }, onToggleCurrentArticleBookmarked = { viewModel.setBookmarked(viewState.articleId, !viewState.isBookmarked) }, onSetBookmarked = { itemId, value -> viewModel.setBookmarked(itemId, value) }, feedListState = feedListState, feedGridState = feedGridState, articleListState = articleListState, pagedFeedItems = pagedFeedItems, ) } @OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class) @Composable private fun FeedArticleScreen( feedArticleScreenType: FeedArticleScreenType, viewState: FeedArticleScreenViewState, onRefreshVisible: () -> Unit, onRefreshAll: () -> Unit, onToggleOnlyUnread: (Boolean) -> Unit, onToggleOnlyBookmarked: (Boolean) -> Unit, onDrawerItemSelected: (Long, String) -> Unit, onMarkAllAsRead: () -> Unit, onToggleTagExpansion: (String) -> Unit, onShowToolbarMenu: (Boolean) -> Unit, ttsOnPlay: () -> Unit, ttsOnPause: () -> Unit, ttsOnStop: () -> Unit, ttsOnSkipNext: () -> Unit, ttsOnSelectLanguage: (LocaleOverride) -> Unit, onAddFeed: () -> Unit, onEditFeed: (Long) -> Unit, onShowEditDialog: () -> Unit, onDismissEditDialog: () -> Unit, onDeleteFeeds: (Iterable<Long>) -> Unit, onShowDeleteDialog: () -> Unit, onDismissDeleteDialog: () -> Unit, onSettings: () -> Unit, onSendFeedback: () -> Unit, onImport: () -> Unit, onExport: () -> Unit, markAsUnread: (Long, Boolean) -> Unit, markBeforeAsRead: (Int) -> Unit, markAfterAsRead: (Int) -> Unit, onOpenFeedItem: (Long) -> Unit, onInteractWithArticle: () -> Unit, onToggleFullText: () -> Unit, displayFullText: () -> Unit, onMarkAsUnread: () -> Unit, onShareArticle: () -> Unit, onOpenInCustomTab: () -> Unit, onFeedTitleClick: () -> Unit, onNavigateUpFromArticle: () -> Unit, onToggleCurrentArticlePinned: () -> Unit, onSetPinned: (Long, Boolean) -> Unit, onToggleCurrentArticleBookmarked: () -> Unit, onSetBookmarked: (Long, Boolean) -> Unit, feedListState: LazyListState, feedGridState: LazyStaggeredGridState, articleListState: LazyListState, pagedFeedItems: LazyPagingItems<FeedListItem>, drawerState: DrawerState = rememberDrawerState(initialValue = DrawerValue.Closed), ) { AnimatedVisibility( visible = feedArticleScreenType == FeedArticleScreenType.Feed || feedArticleScreenType == FeedArticleScreenType.FeedGrid, enter = slideInHorizontally(tween(256), initialOffsetX = { -it }), exit = slideOutHorizontally(tween(256), targetOffsetX = { -it }), ) { ScreenWithNavDrawer( drawerState = drawerState, feedsAndTags = ImmutableHolder(viewState.drawerItemsWithUnreadCounts), expandedTags = ImmutableHolder(viewState.expandedTags), onToggleTagExpansion = onToggleTagExpansion, onDrawerItemSelected = onDrawerItemSelected, content = { FeedListScreen( viewState = viewState, onRefreshVisible = onRefreshVisible, onRefreshAll = onRefreshAll, onToggleOnlyUnread = onToggleOnlyUnread, onToggleOnlyBookmarked = onToggleOnlyBookmarked, onMarkAllAsRead = onMarkAllAsRead, onShowToolbarMenu = onShowToolbarMenu, ttsOnPlay = ttsOnPlay, ttsOnPause = ttsOnPause, ttsOnStop = ttsOnStop, ttsOnSkipNext = ttsOnSkipNext, ttsOnSelectLanguage = ttsOnSelectLanguage, onAddFeed = onAddFeed, onEditFeed = onEditFeed, onShowEditDialog = onShowEditDialog, onDismissEditDialog = onDismissEditDialog, onDeleteFeeds = onDeleteFeeds, onShowDeleteDialog = onShowDeleteDialog, onDismissDeleteDialog = onDismissDeleteDialog, onSettings = onSettings, onSendFeedback = onSendFeedback, onImport = onImport, onExport = onExport, drawerState = drawerState, markAsUnread = markAsUnread, markBeforeAsRead = markBeforeAsRead, markAfterAsRead = markAfterAsRead, onOpenFeedItem = onOpenFeedItem, onSetPinned = onSetPinned, onSetBookmarked = onSetBookmarked, feedListState = feedListState, feedGridState = feedGridState, pagedFeedItems = pagedFeedItems, feedArticleScreenType = feedArticleScreenType, ) } ) } AnimatedVisibility( visible = feedArticleScreenType == FeedArticleScreenType.ArticleDetails, enter = slideInHorizontally(tween(256), initialOffsetX = { it }), exit = slideOutHorizontally(tween(256), targetOffsetX = { it }), ) { ArticleScreen( viewState = viewState, onToggleFullText = onToggleFullText, onMarkAsUnread = onMarkAsUnread, onShare = onShareArticle, onOpenInCustomTab = onOpenInCustomTab, onFeedTitleClick = onFeedTitleClick, onShowToolbarMenu = onShowToolbarMenu, onInteractWithArticle = onInteractWithArticle, displayFullText = displayFullText, ttsOnPlay = ttsOnPlay, ttsOnPause = ttsOnPause, ttsOnStop = ttsOnStop, ttsOnSkipNext = ttsOnSkipNext, ttsOnSelectLanguage = ttsOnSelectLanguage, onTogglePinned = onToggleCurrentArticlePinned, onToggleBookmarked = onToggleCurrentArticleBookmarked, articleListState = articleListState, onNavigateUp = onNavigateUpFromArticle, ) } } @OptIn(ExperimentalMaterial3Api::class, ExperimentalAnimationApi::class) @Composable fun ScreenWithNavDrawer( drawerState: DrawerState = rememberDrawerState(initialValue = DrawerValue.Closed), feedsAndTags: ImmutableHolder<List<DrawerItemWithUnreadCount>>, expandedTags: ImmutableHolder<Set<String>>, onToggleTagExpansion: (String) -> Unit, onDrawerItemSelected: (Long, String) -> Unit, content: @Composable () -> Unit, ) { val coroutineScope = rememberCoroutineScope() DismissibleNavigationDrawer( drawerState = drawerState, drawerContent = { DismissibleDrawerSheet { ListOfFeedsAndTags( feedsAndTags = feedsAndTags, expandedTags = expandedTags, onToggleTagExpansion = onToggleTagExpansion, onItemClick = { item -> coroutineScope.launch { val id = when (item) { is DrawerFeed -> item.id is DrawerTag -> ID_UNSET is DrawerTop -> ID_ALL_FEEDS } val tag = when (item) { is DrawerFeed -> item.tag is DrawerTag -> item.tag is DrawerTop -> "" } onDrawerItemSelected(id, tag) drawerState.close() } } ) } }, content = content, ) } @OptIn(ExperimentalMaterial3Api::class) @Composable fun FeedWithArticleScreen( viewState: FeedArticleScreenViewState, onRefreshVisible: () -> Unit, onRefreshAll: () -> Unit, onToggleOnlyUnread: (Boolean) -> Unit, onToggleOnlyBookmarked: (Boolean) -> Unit, onMarkAllAsRead: () -> Unit, onShowToolbarMenu: (Boolean) -> Unit, ttsOnPlay: () -> Unit, ttsOnPause: () -> Unit, ttsOnStop: () -> Unit, ttsOnSkipNext: () -> Unit, ttsOnSelectLanguage: (LocaleOverride) -> Unit, onOpenInCustomTab: () -> Unit, onAddFeed: () -> Unit, onEditFeed: (Long) -> Unit, onShowEditDialog: () -> Unit, onDismissEditDialog: () -> Unit, onDeleteFeeds: (Iterable<Long>) -> Unit, onShowDeleteDialog: () -> Unit, onDismissDeleteDialog: () -> Unit, onSettings: () -> Unit, onSendFeedback: () -> Unit, onImport: () -> Unit, onExport: () -> Unit, drawerState: DrawerState = rememberDrawerState(initialValue = DrawerValue.Closed), onShareArticle: () -> Unit, markAsUnread: (Long, Boolean) -> Unit, markBeforeAsRead: (Int) -> Unit, markAfterAsRead: (Int) -> Unit, onOpenFeedItem: (Long) -> Unit, onInteractWithList: () -> Unit, onInteractWithArticle: () -> Unit, onFeedTitleClick: () -> Unit, onToggleFullText: () -> Unit, displayFullText: () -> Unit, onToggleCurrentArticlePinned: () -> Unit, onSetPinned: (Long, Boolean) -> Unit, onToggleCurrentArticleBookmarked: () -> Unit, onSetBookmarked: (Long, Boolean) -> Unit, feedListState: LazyListState, articleListState: LazyListState, pagedFeedItems: LazyPagingItems<FeedListItem>, ) { val showingUnreadStateLabel = if (viewState.onlyUnread) { stringResource(R.string.showing_only_unread_articles) } else { stringResource(R.string.showing_all_articles) } val showingBookmarksStateLabel = if (viewState.onlyBookmarked) { stringResource(R.string.showing_only_bookmarked_articles) } else { stringResource(R.string.showing_all_articles) } val coroutineScope = rememberCoroutineScope() FeedScreen( viewState = viewState, onRefreshVisible = onRefreshVisible, onOpenNavDrawer = { coroutineScope.launch { if (drawerState.isOpen) { drawerState.close() } else { drawerState.open() } } }, onMarkAllAsRead = onMarkAllAsRead, ttsOnPlay = ttsOnPlay, ttsOnPause = ttsOnPause, ttsOnStop = ttsOnStop, ttsOnSkipNext = ttsOnSkipNext, ttsOnSelectLanguage = ttsOnSelectLanguage, onDismissDeleteDialog = onDismissDeleteDialog, onDismissEditDialog = onDismissEditDialog, onDelete = onDeleteFeeds, onEditFeed = onEditFeed, toolbarActions = { IconToggleButton( checked = viewState.onlyUnread, onCheckedChange = onToggleOnlyUnread, modifier = Modifier.semantics { stateDescription = showingUnreadStateLabel } ) { if (viewState.onlyUnread) { Icon( Icons.Default.VisibilityOff, contentDescription = null, ) } else { Icon( Icons.Default.Visibility, contentDescription = null, ) } } IconToggleButton( checked = viewState.onlyBookmarked, onCheckedChange = onToggleOnlyBookmarked, modifier = Modifier.semantics { stateDescription = showingBookmarksStateLabel } ) { if (viewState.onlyBookmarked) { Icon( Icons.Default.BookmarkRemove, contentDescription = null, ) } else { Icon( Icons.Default.Bookmark, contentDescription = null, ) } } Box { IconButton(onClick = { onShowToolbarMenu(true) }) { Icon( Icons.Default.MoreVert, contentDescription = stringResource(R.string.open_menu), ) } DropdownMenu( expanded = viewState.showToolbarMenu, onDismissRequest = { onShowToolbarMenu(false) } ) { DropdownMenuItem( onClick = { onMarkAllAsRead() onShowToolbarMenu(false) }, leadingIcon = { Icon( Icons.Default.DoneAll, contentDescription = null, ) }, text = { Text(stringResource(id = R.string.mark_all_as_read)) } ) Divider() DropdownMenuItem( onClick = { onRefreshAll() onShowToolbarMenu(false) }, leadingIcon = { Icon( Icons.Default.Refresh, contentDescription = stringResource(R.string.synchronize_feeds), ) }, text = { Text(stringResource(id = R.string.synchronize_feeds)) } ) Divider() DropdownMenuItem( onClick = { onShowToolbarMenu(false) onAddFeed() }, leadingIcon = { Icon( Icons.Default.Add, contentDescription = null, ) }, text = { Text(stringResource(id = R.string.add_feed)) } ) DropdownMenuItem( onClick = { if (viewState.visibleFeeds.size == 1) { onEditFeed(viewState.visibleFeeds.first().id) } else { onShowEditDialog() } onShowToolbarMenu(false) }, leadingIcon = { Icon( Icons.Default.Edit, contentDescription = null, ) }, text = { Text(stringResource(id = R.string.edit_feed)) } ) DropdownMenuItem( onClick = { onShowDeleteDialog() onShowToolbarMenu(false) }, leadingIcon = { Icon( Icons.Default.Delete, contentDescription = null, ) }, text = { Text(stringResource(id = R.string.delete_feed)) } ) Divider() DropdownMenuItem( onClick = { onToggleFullText() onShowToolbarMenu(false) }, leadingIcon = { Icon( Icons.Default.Article, contentDescription = stringResource(R.string.fetch_full_article), ) }, text = { Text(stringResource(id = R.string.fetch_full_article)) } ) DropdownMenuItem( onClick = { onOpenInCustomTab() onShowToolbarMenu(false) }, leadingIcon = { Icon( Icons.Default.OpenInBrowser, contentDescription = stringResource(R.string.open_in_web_view), ) }, text = { Text(stringResource(id = R.string.open_in_web_view)) } ) DropdownMenuItem( onClick = { onShowToolbarMenu(false) onShareArticle() }, leadingIcon = { Icon( Icons.Default.Share, contentDescription = null, ) }, text = { Text(stringResource(id = R.string.share)) } ) DropdownMenuItem( onClick = { onShowToolbarMenu(false) markAsUnread(viewState.articleId, true) }, leadingIcon = { Icon( Icons.Default.VisibilityOff, contentDescription = null, ) }, text = { Text(stringResource(id = R.string.mark_as_unread)) } ) DropdownMenuItem( onClick = { onShowToolbarMenu(false) onToggleCurrentArticlePinned() }, leadingIcon = { Icon( Icons.Default.PushPin, contentDescription = null, ) }, text = { Text( stringResource( if (viewState.isPinned) { R.string.unpin_article } else { R.string.pin_article } ) ) } ) DropdownMenuItem( onClick = { onShowToolbarMenu(false) onToggleCurrentArticleBookmarked() }, leadingIcon = { Icon( Icons.Default.Bookmark, contentDescription = null, ) }, text = { Text( stringResource( if (viewState.isBookmarked) { R.string.remove_bookmark } else { R.string.bookmark_article } ) ) } ) DropdownMenuItem( onClick = { onShowToolbarMenu(false) ttsOnPlay() }, leadingIcon = { Icon( Icons.CustomFilled.TextToSpeech, contentDescription = null, ) }, text = { Text(stringResource(id = R.string.read_article)) } ) Divider() DropdownMenuItem( onClick = { onShowToolbarMenu(false) onImport() }, leadingIcon = { Icon( Icons.Default.ImportExport, contentDescription = null, ) }, text = { Text(stringResource(id = R.string.import_feeds_from_opml)) } ) DropdownMenuItem( onClick = { onShowToolbarMenu(false) onExport() }, leadingIcon = { Icon( Icons.Default.ImportExport, contentDescription = null, ) }, text = { Text(stringResource(id = R.string.export_feeds_to_opml)) } ) Divider() DropdownMenuItem( onClick = { onShowToolbarMenu(false) onSettings() }, leadingIcon = { Icon( Icons.Default.Settings, contentDescription = null, ) }, text = { Text(stringResource(id = R.string.action_settings)) } ) Divider() DropdownMenuItem( onClick = { onShowToolbarMenu(false) onSendFeedback() }, leadingIcon = { Icon( Icons.Default.Email, contentDescription = null, ) }, text = { Text(stringResource(id = R.string.send_bug_report)) } ) } } }, content = { modifier -> Row(modifier) { FeedListContent( viewState = viewState, onOpenNavDrawer = { coroutineScope.launch { if (drawerState.isOpen) { drawerState.close() } else { drawerState.open() } } }, onAddFeed = onAddFeed, markAsUnread = markAsUnread, markBeforeAsRead = markBeforeAsRead, markAfterAsRead = markAfterAsRead, onItemClick = onOpenFeedItem, listState = feedListState, onSetPinned = onSetPinned, onSetBookmarked = onSetBookmarked, pagedFeedItems = pagedFeedItems, modifier = Modifier .width(334.dp) .notifyInput(onInteractWithList), ) if (viewState.articleId > ID_UNSET) { // Avoid state sharing between articles key(viewState.articleId) { ArticleContent( viewState = viewState, screenType = ScreenType.DUAL, onFeedTitleClick = onFeedTitleClick, articleListState = articleListState, displayFullText = displayFullText, modifier = Modifier .fillMaxSize() .notifyInput(onInteractWithArticle) // .imePadding() // add padding for the on-screen keyboard ) } } } }, ) } @OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class) @Composable fun FeedListScreen( viewState: FeedScreenViewState, onRefreshVisible: () -> Unit, onRefreshAll: () -> Unit, onToggleOnlyUnread: (Boolean) -> Unit, onToggleOnlyBookmarked: (Boolean) -> Unit, onMarkAllAsRead: () -> Unit, onShowToolbarMenu: (Boolean) -> Unit, ttsOnPlay: () -> Unit, ttsOnPause: () -> Unit, ttsOnStop: () -> Unit, ttsOnSkipNext: () -> Unit, ttsOnSelectLanguage: (LocaleOverride) -> Unit, onAddFeed: () -> Unit, onEditFeed: (Long) -> Unit, onShowEditDialog: () -> Unit, onDismissEditDialog: () -> Unit, onDeleteFeeds: (Iterable<Long>) -> Unit, onShowDeleteDialog: () -> Unit, onDismissDeleteDialog: () -> Unit, onSettings: () -> Unit, onSendFeedback: () -> Unit, onImport: () -> Unit, onExport: () -> Unit, drawerState: DrawerState = rememberDrawerState(initialValue = DrawerValue.Closed), markAsUnread: (Long, Boolean) -> Unit, markBeforeAsRead: (Int) -> Unit, markAfterAsRead: (Int) -> Unit, onOpenFeedItem: (Long) -> Unit, onSetPinned: (Long, Boolean) -> Unit, onSetBookmarked: (Long, Boolean) -> Unit, feedListState: LazyListState, feedGridState: LazyStaggeredGridState, pagedFeedItems: LazyPagingItems<FeedListItem>, feedArticleScreenType: FeedArticleScreenType, ) { val showingUnreadStateLabel = if (viewState.onlyUnread) { stringResource(R.string.showing_only_unread_articles) } else { stringResource(R.string.showing_all_articles) } val showingBookmarksStateLabel = if (viewState.onlyBookmarked) { stringResource(R.string.showing_only_bookmarked_articles) } else { stringResource(R.string.showing_all_articles) } val coroutineScope = rememberCoroutineScope() FeedScreen( viewState = viewState, onRefreshVisible = onRefreshVisible, onOpenNavDrawer = { coroutineScope.launch { if (drawerState.isOpen) { drawerState.close() } else { drawerState.open() } } }, onMarkAllAsRead = onMarkAllAsRead, ttsOnPlay = ttsOnPlay, ttsOnPause = ttsOnPause, ttsOnStop = ttsOnStop, ttsOnSkipNext = ttsOnSkipNext, ttsOnSelectLanguage = ttsOnSelectLanguage, onDismissDeleteDialog = onDismissDeleteDialog, onDismissEditDialog = onDismissEditDialog, onDelete = onDeleteFeeds, onEditFeed = onEditFeed, toolbarActions = { IconToggleButton( checked = viewState.onlyUnread, onCheckedChange = onToggleOnlyUnread, modifier = Modifier.semantics { stateDescription = showingUnreadStateLabel } ) { if (viewState.onlyUnread) { Icon( Icons.Default.VisibilityOff, contentDescription = null, ) } else { Icon( Icons.Default.Visibility, contentDescription = null, ) } } IconToggleButton( checked = viewState.onlyBookmarked, onCheckedChange = onToggleOnlyBookmarked, modifier = Modifier.semantics { stateDescription = showingBookmarksStateLabel } ) { if (viewState.onlyBookmarked) { Icon( Icons.Default.BookmarkRemove, contentDescription = null, ) } else { Icon( Icons.Default.Bookmark, contentDescription = null, ) } } Box { IconButton(onClick = { onShowToolbarMenu(true) }) { Icon( Icons.Default.MoreVert, contentDescription = stringResource(R.string.open_menu), ) } DropdownMenu( expanded = viewState.showToolbarMenu, onDismissRequest = { onShowToolbarMenu(false) } ) { DropdownMenuItem( onClick = { onMarkAllAsRead() onShowToolbarMenu(false) }, leadingIcon = { Icon( Icons.Default.DoneAll, contentDescription = null, ) }, text = { Text(stringResource(id = R.string.mark_all_as_read)) } ) Divider() DropdownMenuItem( onClick = { onRefreshAll() onShowToolbarMenu(false) }, leadingIcon = { Icon( Icons.Default.Refresh, contentDescription = stringResource(R.string.synchronize_feeds), ) }, text = { Text(stringResource(id = R.string.synchronize_feeds)) } ) Divider() DropdownMenuItem( onClick = { onShowToolbarMenu(false) onAddFeed() }, leadingIcon = { Icon( Icons.Default.Add, contentDescription = null, ) }, text = { Text(stringResource(id = R.string.add_feed)) } ) DropdownMenuItem( onClick = { if (viewState.visibleFeeds.size == 1) { onEditFeed(viewState.visibleFeeds.first().id) } else { onShowEditDialog() } onShowToolbarMenu(false) }, leadingIcon = { Icon( Icons.Default.Edit, contentDescription = null, ) }, text = { Text(stringResource(id = R.string.edit_feed)) } ) DropdownMenuItem( onClick = { onShowDeleteDialog() onShowToolbarMenu(false) }, leadingIcon = { Icon( Icons.Default.Delete, contentDescription = null, ) }, text = { Text(stringResource(id = R.string.delete_feed)) } ) Divider() DropdownMenuItem( onClick = { onShowToolbarMenu(false) onImport() }, leadingIcon = { Icon( Icons.Default.ImportExport, contentDescription = null, ) }, text = { Text(stringResource(id = R.string.import_feeds_from_opml)) } ) DropdownMenuItem( onClick = { onShowToolbarMenu(false) onExport() }, leadingIcon = { Icon( Icons.Default.ImportExport, contentDescription = null, ) }, text = { Text(stringResource(id = R.string.export_feeds_to_opml)) } ) Divider() DropdownMenuItem( onClick = { onShowToolbarMenu(false) onSettings() }, leadingIcon = { Icon( Icons.Default.Settings, contentDescription = null, ) }, text = { Text(stringResource(id = R.string.action_settings)) } ) Divider() DropdownMenuItem( onClick = { onShowToolbarMenu(false) onSendFeedback() }, leadingIcon = { Icon( Icons.Default.Email, contentDescription = null, ) }, text = { Text(stringResource(id = R.string.send_bug_report)) } ) } } }, ) { modifier -> if (feedArticleScreenType == FeedArticleScreenType.FeedGrid) { FeedGridContent( viewState = viewState, gridState = feedGridState, onOpenNavDrawer = { coroutineScope.launch { if (drawerState.isOpen) { drawerState.close() } else { drawerState.open() } } }, onAddFeed = onAddFeed, markBeforeAsRead = markBeforeAsRead, markAfterAsRead = markAfterAsRead, onItemClick = onOpenFeedItem, onSetPinned = onSetPinned, onSetBookmarked = onSetBookmarked, pagedFeedItems = pagedFeedItems, modifier = modifier, ) } else { FeedListContent( viewState = viewState, onOpenNavDrawer = { coroutineScope.launch { if (drawerState.isOpen) { drawerState.close() } else { drawerState.open() } } }, onAddFeed = onAddFeed, markAsUnread = markAsUnread, markBeforeAsRead = markBeforeAsRead, markAfterAsRead = markAfterAsRead, onItemClick = onOpenFeedItem, listState = feedListState, onSetPinned = onSetPinned, onSetBookmarked = onSetBookmarked, pagedFeedItems = pagedFeedItems, modifier = modifier, ) } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun ArticleScreen( viewState: ArticleScreenViewState, onToggleFullText: () -> Unit, onMarkAsUnread: () -> Unit, onShare: () -> Unit, onOpenInCustomTab: () -> Unit, onFeedTitleClick: () -> Unit, onShowToolbarMenu: (Boolean) -> Unit, onInteractWithArticle: () -> Unit, displayFullText: () -> Unit, ttsOnPlay: () -> Unit, ttsOnPause: () -> Unit, ttsOnStop: () -> Unit, ttsOnSkipNext: () -> Unit, ttsOnSelectLanguage: (LocaleOverride) -> Unit, onTogglePinned: () -> Unit, onToggleBookmarked: () -> Unit, articleListState: LazyListState, onNavigateUp: () -> Unit, ) { BackHandler(onBack = onNavigateUp) val scrollBehavior = TopAppBarDefaults.enterAlwaysScrollBehavior( rememberTopAppBarState() ) val bottomBarVisibleState = remember { MutableTransitionState(viewState.isBottomBarVisible) } LaunchedEffect(viewState.isBottomBarVisible) { bottomBarVisibleState.targetState = viewState.isBottomBarVisible } Scaffold( modifier = Modifier .nestedScroll(scrollBehavior.nestedScrollConnection) .windowInsetsPadding(WindowInsets.navigationBars.only(WindowInsetsSides.Horizontal)), contentWindowInsets = WindowInsets.statusBars, topBar = { TopAppBar( scrollBehavior = scrollBehavior, title = { withBidiDeterminedLayoutDirection(paragraph = viewState.feedDisplayTitle) { Text( text = viewState.feedDisplayTitle, maxLines = 1, overflow = TextOverflow.Ellipsis ) } }, navigationIcon = { IconButton(onClick = onNavigateUp) { Icon( Icons.Default.ArrowBack, contentDescription = stringResource(R.string.go_back) ) } }, actions = { IconButton( onClick = onToggleFullText ) { Icon( Icons.Default.Article, contentDescription = stringResource(R.string.fetch_full_article) ) } IconButton(onClick = onOpenInCustomTab) { Icon( Icons.Default.OpenInBrowser, contentDescription = stringResource(id = R.string.open_in_web_view) ) } Box { IconButton(onClick = { onShowToolbarMenu(true) }) { Icon( Icons.Default.MoreVert, contentDescription = stringResource(id = R.string.open_menu), ) } DropdownMenu( expanded = viewState.showToolbarMenu, onDismissRequest = { onShowToolbarMenu(false) } ) { DropdownMenuItem( onClick = { onShowToolbarMenu(false) onShare() }, leadingIcon = { Icon( Icons.Default.Share, contentDescription = null, ) }, text = { Text(stringResource(id = R.string.share)) } ) DropdownMenuItem( onClick = { onShowToolbarMenu(false) onMarkAsUnread() }, leadingIcon = { Icon( Icons.Default.VisibilityOff, contentDescription = null, ) }, text = { Text(stringResource(id = R.string.mark_as_unread)) } ) DropdownMenuItem( onClick = { onShowToolbarMenu(false) onTogglePinned() }, leadingIcon = { Icon( Icons.Default.PushPin, contentDescription = null, ) }, text = { Text( stringResource( if (viewState.isPinned) { R.string.unpin_article } else { R.string.pin_article } ) ) } ) DropdownMenuItem( onClick = { onShowToolbarMenu(false) onToggleBookmarked() }, leadingIcon = { Icon( Icons.Default.Bookmark, contentDescription = null, ) }, text = { Text( stringResource( if (viewState.isBookmarked) { R.string.remove_bookmark } else { R.string.bookmark_article } ) ) } ) DropdownMenuItem( onClick = { onShowToolbarMenu(false) ttsOnPlay() }, leadingIcon = { Icon( Icons.CustomFilled.TextToSpeech, contentDescription = null, ) }, text = { Text(stringResource(id = R.string.read_article)) } ) } } } ) }, bottomBar = { HideableTTSPlayer( visibleState = bottomBarVisibleState, currentlyPlaying = viewState.isTTSPlaying, onPlay = ttsOnPlay, onPause = ttsOnPause, onStop = ttsOnStop, onSkipNext = ttsOnSkipNext, languages = ImmutableHolder(viewState.ttsLanguages), onSelectLanguage = ttsOnSelectLanguage, ) }, ) { padding -> ArticleContent( viewState = viewState, screenType = ScreenType.SINGLE, articleListState = articleListState, onFeedTitleClick = onFeedTitleClick, displayFullText = displayFullText, modifier = Modifier .padding(padding) .notifyInput(onInteractWithArticle) ) } } @Composable fun ArticleContent( viewState: ArticleScreenViewState, screenType: ScreenType, onFeedTitleClick: () -> Unit, articleListState: LazyListState, displayFullText: () -> Unit, modifier: Modifier, ) { val isLightTheme = MaterialTheme.colorScheme.isLight @DrawableRes val placeHolder: Int by remember(isLightTheme) { derivedStateOf { if (isLightTheme) { R.drawable.placeholder_image_article_day } else { R.drawable.placeholder_image_article_night } } } val toolbarColor = MaterialTheme.colorScheme.surface.toArgb() val context = LocalContext.current if (viewState.articleId > ID_UNSET && viewState.textToDisplay == TextToDisplay.FULLTEXT && !blobFullFile(viewState.articleId, context.filesDir).isFile ) { LaunchedEffect(viewState.articleId, viewState.textToDisplay) { // Trigger parse and fetch displayFullText() } } ReaderView( modifier = modifier, screenType = screenType, articleListState = articleListState, articleTitle = viewState.articleTitle, feedTitle = viewState.feedDisplayTitle, enclosure = viewState.enclosure, onEnclosureClick = { if (viewState.enclosure.present) { openLinkInBrowser(context, viewState.enclosure.link) } }, onFeedTitleClick = onFeedTitleClick, authorDate = when { viewState.author == null && viewState.pubDate != null -> stringResource( R.string.on_date, (viewState.pubDate ?: ZonedDateTime.now()).format(dateTimeFormat) ) viewState.author != null && viewState.pubDate != null -> stringResource( R.string.by_author_on_date, // Must wrap author in unicode marks to ensure it formats // correctly in RTL context.unicodeWrap(viewState.author ?: ""), (viewState.pubDate ?: ZonedDateTime.now()).format(dateTimeFormat) ) else -> null }, ) { // Can take a composition or two before viewstate is set to its actual values // TODO show something in case no article to show if (viewState.articleId > ID_UNSET) { when (viewState.textToDisplay) { TextToDisplay.DEFAULT -> { if (blobFile(viewState.articleId, context.filesDir).isFile) { blobInputStream(viewState.articleId, context.filesDir).use { htmlFormattedText( inputStream = it, baseUrl = viewState.articleFeedUrl ?: "", imagePlaceholder = placeHolder, onLinkClick = { link -> onLinkClick( link = link, linkOpener = viewState.linkOpener, context = context, toolbarColor = toolbarColor ) } ) } } else { item { Text(text = stringResource(id = R.string.failed_to_open_article)) } } } TextToDisplay.FAILED_TO_LOAD_FULLTEXT -> { item { Text(text = stringResource(id = R.string.failed_to_fetch_full_article)) } } TextToDisplay.LOADING_FULLTEXT -> { LoadingItem() } TextToDisplay.FULLTEXT -> { if (blobFullFile(viewState.articleId, context.filesDir).isFile) { blobFullInputStream(viewState.articleId, context.filesDir).use { htmlFormattedText( inputStream = it, baseUrl = viewState.articleFeedUrl ?: "", imagePlaceholder = placeHolder, onLinkClick = { link -> onLinkClick( link = link, linkOpener = viewState.linkOpener, context = context, toolbarColor = toolbarColor ) } ) } } else { // Already trigger load in effect above LoadingItem() } } } } } } @Suppress("FunctionName") private fun LazyListScope.LoadingItem() { item { Text(text = stringResource(id = R.string.fetching_full_article)) } } enum class FeedArticleScreenType { FeedGrid, Feed, ArticleDetails, } private fun getFeedArticleScreenType( windowSize: WindowSize, viewState: FeedArticleScreenViewState, ): FeedArticleScreenType = when (getScreenType(windowSize)) { ScreenType.SINGLE -> { when { viewState.isArticleOpen -> FeedArticleScreenType.ArticleDetails else -> FeedArticleScreenType.Feed } } ScreenType.DUAL -> { when { viewState.isArticleOpen -> FeedArticleScreenType.ArticleDetails else -> FeedArticleScreenType.FeedGrid } } } /** * A [Modifier] that tracks all input, and calls [block] every time input is received. */ private fun Modifier.notifyInput(block: () -> Unit): Modifier = composed { val blockState = rememberUpdatedState(block) pointerInput(Unit) { while (currentCoroutineContext().isActive) { awaitPointerEventScope { awaitPointerEvent(PointerEventPass.Initial) blockState.value() } } } }
gpl-3.0
d13e46fe174fe3751bf0193394d9f05b
38.931737
129
0.478781
6.309585
false
false
false
false
ncipollo/android-viper
sample/src/main/kotlin/viper/sample/ui/fragments/UserFragment.kt
1
2637
package viper.sample.ui.fragments import android.content.Context import android.hardware.input.InputManager import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.EditorInfo import android.view.inputmethod.InputMethodManager import com.jakewharton.rxbinding.view.clicks import com.jakewharton.rxbinding.widget.editorActionEvents import com.jakewharton.rxbinding.widget.textChanges import kotlinx.android.synthetic.main.fragment_user.* import nucleus.factory.RequiresPresenter import rx.Observable import rx.lang.kotlin.addTo import rx.subscriptions.CompositeSubscription import viper.sample.R import viper.sample.ui.presenters.UserPresenter import viper.view.fragments.ViperFragment /** * A fragment which allows the user to input a user. * Created by Nick Cipollo on 12/16/16. */ @RequiresPresenter(UserPresenter::class) class UserFragment : UserView, ViperFragment<UserPresenter>() { override var user: String get() = userField.text.toString() set(value) { userField.setText(value) } override val onUserChanged: Observable<CharSequence> get() = userField.textChanges() override var doneEnabled: Boolean get() = doneButton.isEnabled set(value) { doneButton.isEnabled = value } var subscriptions: CompositeSubscription? = null override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater?.inflate(R.layout.fragment_user, container, false) } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val subscriptions = CompositeSubscription() this.subscriptions = subscriptions userField.editorActionEvents() .filter { it.actionId() == EditorInfo.IME_ACTION_DONE } .subscribe { selectUser() } .addTo(subscriptions) doneButton.clicks() .subscribe { selectUser() } .addTo(subscriptions) } fun selectUser() { dismissKeyboard() presenter.selectUser(userField.text.toString()) } fun dismissKeyboard() { val inputManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager val windowToken = view?.windowToken if (windowToken != null) { inputManager.hideSoftInputFromWindow(windowToken, 0) } } }
mit
365dc093644575d8b096234b4028cc92
34.16
81
0.691316
4.910615
false
false
false
false
allotria/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/action/GHPRReviewSubmitAction.kt
2
11634
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.action import com.intellij.icons.AllIcons import com.intellij.ide.ui.laf.darcula.ui.DarculaButtonUI import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.Presentation import com.intellij.openapi.actionSystem.ex.CustomComponentAction import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.actions.IncrementalFindAction import com.intellij.openapi.fileTypes.FileTypes import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.ui.ComponentContainer import com.intellij.openapi.ui.MessageDialogBuilder import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.text.StringUtil import com.intellij.ui.EditorTextField import com.intellij.ui.IdeBorderFactory import com.intellij.ui.SideBorder import com.intellij.ui.components.panels.HorizontalBox import com.intellij.ui.scale.JBUIScale import com.intellij.util.ui.JBDimension import com.intellij.util.ui.JBUI import com.intellij.util.ui.JButtonAction import com.intellij.util.ui.UIUtil import com.intellij.util.ui.codereview.InlineIconButton import icons.VcsCodeReviewIcons import net.miginfocom.layout.CC import net.miginfocom.layout.LC import net.miginfocom.swing.MigLayout import org.jetbrains.plugins.github.api.data.GHPullRequestReviewEvent import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestPendingReview import org.jetbrains.plugins.github.i18n.GithubBundle import org.jetbrains.plugins.github.pullrequest.data.provider.GHPRReviewDataProvider import org.jetbrains.plugins.github.ui.component.GHHtmlErrorPanel import org.jetbrains.plugins.github.ui.component.GHSimpleErrorPanelModel import org.jetbrains.plugins.github.util.errorOnEdt import org.jetbrains.plugins.github.util.successOnEdt import java.awt.FlowLayout import java.awt.Font import java.awt.event.ActionListener import javax.swing.* class GHPRReviewSubmitAction : JButtonAction(StringUtil.ELLIPSIS, GithubBundle.message("pull.request.review.submit.action.description")) { override fun update(e: AnActionEvent) { val dataProvider = e.getData(GHPRActionKeys.PULL_REQUEST_DATA_PROVIDER) if (dataProvider == null) { e.presentation.isEnabledAndVisible = false return } val reviewData = dataProvider.reviewData val details = dataProvider.detailsData.loadedDetails e.presentation.isVisible = true val pendingReviewFuture = reviewData.loadPendingReview() e.presentation.isEnabled = pendingReviewFuture.isDone && details != null e.presentation.putClientProperty(PROP_PREFIX, getPrefix(e.place)) if (e.presentation.isEnabledAndVisible) { val review = try { pendingReviewFuture.getNow(null) } catch (e: Exception) { null } val pendingReview = review != null val comments = review?.comments?.totalCount e.presentation.text = getText(comments) e.presentation.putClientProperty(DarculaButtonUI.DEFAULT_STYLE_KEY, pendingReview) } updateButtonFromPresentation(e) } private fun getPrefix(place: String) = if (place == ActionPlaces.DIFF_TOOLBAR) GithubBundle.message("pull.request.review.submit") else GithubBundle.message("pull.request.review.submit.review") @NlsSafe private fun getText(pendingComments: Int?): String { val builder = StringBuilder() if (pendingComments != null) builder.append(" ($pendingComments)") builder.append(StringUtil.ELLIPSIS) return builder.toString() } override fun actionPerformed(e: AnActionEvent) { val dataProvider = e.getRequiredData(GHPRActionKeys.PULL_REQUEST_DATA_PROVIDER) val details = dataProvider.detailsData.loadedDetails ?: return val reviewDataProvider = dataProvider.reviewData val pendingReviewFuture = reviewDataProvider.loadPendingReview() if (!pendingReviewFuture.isDone) return val pendingReview = try { pendingReviewFuture.getNow(null) } catch (e: Exception) { null } val parentComponent = e.presentation.getClientProperty(CustomComponentAction.COMPONENT_KEY) ?: return var cancelRunnable: (() -> Unit)? = null val cancelActionListener = ActionListener { cancelRunnable?.invoke() } val container = createPopupComponent(reviewDataProvider, reviewDataProvider.submitReviewCommentDocument, cancelActionListener, pendingReview, details.viewerDidAuthor) val popup = JBPopupFactory.getInstance() .createComponentPopupBuilder(container.component, container.preferredFocusableComponent) .setFocusable(true) .setRequestFocus(true) .setResizable(true) .createPopup() cancelRunnable = { popup.cancel() } popup.showUnderneathOf(parentComponent) } private fun createPopupComponent(reviewDataProvider: GHPRReviewDataProvider, document: Document, cancelActionListener: ActionListener, pendingReview: GHPullRequestPendingReview?, viewerIsAuthor: Boolean): ComponentContainer { return object : ComponentContainer { private val editor = createEditor(document) private val errorModel = GHSimpleErrorPanelModel(GithubBundle.message("pull.request.review.submit.error")) private val approveButton = if (!viewerIsAuthor) JButton(GithubBundle.message("pull.request.review.submit.approve.button")).apply { addActionListener(createSubmitButtonActionListener(GHPullRequestReviewEvent.APPROVE)) } else null private val rejectButton = if (!viewerIsAuthor) JButton(GithubBundle.message("pull.request.review.submit.request.changes")).apply { addActionListener(createSubmitButtonActionListener(GHPullRequestReviewEvent.REQUEST_CHANGES)) } else null private val commentButton = JButton(GithubBundle.message("pull.request.review.submit.comment.button")).apply { toolTipText = GithubBundle.message("pull.request.review.submit.comment.description") addActionListener(createSubmitButtonActionListener(GHPullRequestReviewEvent.COMMENT)) } private fun createSubmitButtonActionListener(event: GHPullRequestReviewEvent): ActionListener = ActionListener { e -> editor.isEnabled = false approveButton?.isEnabled = false rejectButton?.isEnabled = false commentButton.isEnabled = false discardButton?.isEnabled = false val reviewId = pendingReview?.id if (reviewId == null) { reviewDataProvider.createReview(EmptyProgressIndicator(), event, editor.text) } else { reviewDataProvider.submitReview(EmptyProgressIndicator(), reviewId, event, editor.text) }.successOnEdt { cancelActionListener.actionPerformed(e) runWriteAction { document.setText("") } }.errorOnEdt { errorModel.error = it editor.isEnabled = true approveButton?.isEnabled = true rejectButton?.isEnabled = true commentButton.isEnabled = true discardButton?.isEnabled = true } } private val discardButton: InlineIconButton? init { discardButton = pendingReview?.let { review -> val button = InlineIconButton(icon = VcsCodeReviewIcons.Delete, hoveredIcon = VcsCodeReviewIcons.DeleteHovered, tooltip = GithubBundle.message("pull.request.discard.pending.comments")) button.actionListener = ActionListener { if (MessageDialogBuilder.yesNo(GithubBundle.message("pull.request.discard.pending.comments.dialog.title"), GithubBundle.message("pull.request.discard.pending.comments.dialog.msg")).ask(button)) { reviewDataProvider.deleteReview(EmptyProgressIndicator(), review.id) } } button } } override fun getComponent(): JComponent { val titleLabel = JLabel(GithubBundle.message("pull.request.review.submit.review")).apply { font = font.deriveFont(font.style or Font.BOLD) } val titlePanel = HorizontalBox().apply { border = JBUI.Borders.empty(4, 4, 4, 4) add(titleLabel) if (pendingReview != null) { val commentsCount = pendingReview.comments.totalCount!! add(Box.createRigidArea(JBDimension(5, 0))) add(JLabel(GithubBundle.message("pull.request.review.pending.comments.count", commentsCount))).apply { foreground = UIUtil.getContextHelpForeground() } } add(Box.createHorizontalGlue()) discardButton?.let { add(it) } add(InlineIconButton(AllIcons.Actions.Close, AllIcons.Actions.CloseHovered).apply { actionListener = cancelActionListener }) } val errorPanel = GHHtmlErrorPanel.create(errorModel, SwingConstants.LEFT).apply { border = JBUI.Borders.empty(4) } val buttonsPanel = JPanel(FlowLayout(FlowLayout.LEFT, 0, 0)).apply { border = JBUI.Borders.empty(4) if (!viewerIsAuthor) add(approveButton) if (!viewerIsAuthor) add(rejectButton) add(commentButton) } return JPanel(MigLayout(LC().gridGap("0", "0") .insets("0", "0", "0", "0") .fill().flowY().noGrid())).apply { isOpaque = false preferredSize = JBDimension(450, 165) add(titlePanel, CC().growX()) add(editor, CC().growX().growY() .gap("0", "0", "0", "0")) add(errorPanel, CC().minHeight("${JBUIScale.scale(32)}").growY().growPrioY(0).hideMode(3) .gap("0", "0", "0", "0")) add(buttonsPanel, CC().alignX("right")) } } private fun createEditor(document: Document) = EditorTextField(document, null, FileTypes.PLAIN_TEXT).apply { setOneLineMode(false) putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) setPlaceholder(GithubBundle.message("pull.request.review.comment.empty.text")) addSettingsProvider { it.settings.isUseSoftWraps = true it.setVerticalScrollbarVisible(true) it.scrollPane.border = IdeBorderFactory.createBorder(SideBorder.TOP or SideBorder.BOTTOM) it.scrollPane.viewportBorder = JBUI.Borders.emptyLeft(4) it.putUserData(IncrementalFindAction.SEARCH_DISABLED, true) } } override fun getPreferredFocusableComponent() = editor override fun dispose() {} } } override fun updateButtonFromPresentation(button: JButton, presentation: Presentation) { super.updateButtonFromPresentation(button, presentation) val prefix = presentation.getClientProperty(PROP_PREFIX) as? String ?: GithubBundle.message("pull.request.review.submit.review") button.text = prefix + presentation.text UIUtil.putClientProperty(button, DarculaButtonUI.DEFAULT_STYLE_KEY, presentation.getClientProperty(DarculaButtonUI.DEFAULT_STYLE_KEY)) } companion object { private const val PROP_PREFIX = "PREFIX" } }
apache-2.0
39315b5c101315fa1f5bd038d0add097
41.933579
140
0.703198
4.938031
false
false
false
false
Homes-MinecraftServerMod/Homes
src/main/kotlin/com/masahirosaito/spigot/homes/strings/EconomyStrings.kt
1
1233
package com.masahirosaito.spigot.homes.strings import com.masahirosaito.spigot.homes.datas.strings.EconomyStringData import com.masahirosaito.spigot.homes.load import com.masahirosaito.spigot.homes.loadData import com.masahirosaito.spigot.homes.strings.Strings.BALANCE import com.masahirosaito.spigot.homes.strings.Strings.COMMAND_FEE import com.masahirosaito.spigot.homes.strings.Strings.ERROR_MESSAGE import com.masahirosaito.spigot.homes.strings.Strings.PAY_AMOUNT import java.io.File object EconomyStrings { lateinit private var data: EconomyStringData fun load(folderPath: String) { data = loadData(File(folderPath, "economy.json").load(), EconomyStringData::class.java) } fun PAY(payAmount: String, balance: String) = data.PAY .replace(PAY_AMOUNT, payAmount) .replace(BALANCE, balance) fun ECONOMY_ERROR(errorMessage: String) = data.ECONOMY_ERROR .replace(ERROR_MESSAGE, errorMessage) fun NO_ACCOUNT_ERROR() = data.NO_ACCOUNT_ERROR fun NOT_ENOUGH_MONEY_ERROR(commandFee: Double) = data.NOT_ENOUGH_MONEY_ERROR .replace(COMMAND_FEE, commandFee.toString()) }
apache-2.0
e9e371b3e78aa46b02cee929155a2b4b
35.264706
95
0.705596
4.082781
false
false
false
false
aporter/coursera-android
ExamplesKotlin/UIWebView/app/src/main/java/course/examples/ui/webview/WebViewActivity.kt
1
1524
package course.examples.ui.webview import android.app.Activity import android.os.Bundle import android.util.Log import android.view.KeyEvent import android.webkit.WebView import android.webkit.WebViewClient class WebViewActivity : Activity() { companion object { private const val TAG = "HelloWebViewClient" } private lateinit var mWebView: WebView public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main) mWebView = findViewById(R.id.webview) // Set a kind of listener on the WebView so the WebView can intercept // URL loading requests if it wants to mWebView.webViewClient = HelloWebViewClient() // Add Zoom controls to WebView mWebView.settings.builtInZoomControls = true mWebView.loadUrl("https://www.cs.umd.edu/~aporter/Tmp/bee.html") } override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) { mWebView.goBack() return true } return super.onKeyDown(keyCode, event) } private inner class HelloWebViewClient : WebViewClient() { // Give application a chance to catch additional URL loading requests override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean { Log.i(TAG, "About to load:$url") view.loadUrl(url) return true } } }
mit
d40d1b5997e646b5d33336504f54b8c9
28.326923
84
0.669948
4.822785
false
false
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/jvm/test/scheduling/WorkQueueStressTest.kt
1
3914
/* * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.scheduling import kotlinx.coroutines.* import org.junit.* import org.junit.Test import java.util.concurrent.* import kotlin.concurrent.* import kotlin.test.* class WorkQueueStressTest : TestBase() { private val threads = mutableListOf<Thread>() private val offerIterations = 100_000 * stressTestMultiplierSqrt // memory pressure, not CPU time private val stealersCount = 6 private val stolenTasks = Array(stealersCount) { GlobalQueue() } private val globalQueue = GlobalQueue() // only producer will use it private val producerQueue = WorkQueue() @Volatile private var producerFinished = false @Before fun setUp() { schedulerTimeSource = TestTimeSource(Long.MAX_VALUE) // always steal } @After fun tearDown() { schedulerTimeSource = NanoTimeSource } @Test fun testStealing() { val startLatch = CountDownLatch(1) threads += thread(name = "producer") { startLatch.await() for (i in 1..offerIterations) { while (producerQueue.bufferSize > BUFFER_CAPACITY / 2) { Thread.yield() } producerQueue.add(task(i.toLong()))?.let { globalQueue.addLast(it) } } producerFinished = true } for (i in 0 until stealersCount) { threads += thread(name = "stealer $i") { val myQueue = WorkQueue() startLatch.await() while (!producerFinished || producerQueue.size != 0) { stolenTasks[i].addAll(myQueue.drain().map { task(it) }) myQueue.tryStealFrom(victim = producerQueue) } // Drain last element which is not counted in buffer stolenTasks[i].addAll(myQueue.drain().map { task(it) }) myQueue.tryStealFrom(producerQueue) stolenTasks[i].addAll(myQueue.drain().map { task(it) }) } } startLatch.countDown() threads.forEach { it.join() } validate() } @Test fun testSingleProducerSingleStealer() { val startLatch = CountDownLatch(1) threads += thread(name = "producer") { startLatch.await() for (i in 1..offerIterations) { while (producerQueue.bufferSize == BUFFER_CAPACITY - 1) { Thread.yield() } // No offloading to global queue here producerQueue.add(task(i.toLong())) } } val stolen = GlobalQueue() threads += thread(name = "stealer") { val myQueue = WorkQueue() startLatch.await() while (stolen.size != offerIterations) { if (myQueue.tryStealFrom(producerQueue) != NOTHING_TO_STEAL) { stolen.addAll(myQueue.drain().map { task(it) }) } } stolen.addAll(myQueue.drain().map { task(it) }) } startLatch.countDown() threads.forEach { it.join() } assertEquals((1L..offerIterations).toSet(), stolen.map { it.submissionTime }.toSet()) } private fun validate() { val result = mutableSetOf<Long>() for (stolenTask in stolenTasks) { assertEquals(stolenTask.size, stolenTask.map { it }.toSet().size) result += stolenTask.map { it.submissionTime } } result += globalQueue.map { it.submissionTime } val expected = (1L..offerIterations).toSet() assertEquals(expected, result, "Following elements are missing: ${(expected - result)}") } private fun GlobalQueue.addAll(tasks: Collection<Task>) { tasks.forEach { addLast(it) } } }
apache-2.0
268859ea9f55e60463dc0b8892597304
31.347107
102
0.573327
4.432616
false
true
false
false
takke/cpustats
app/src/main/java/jp/takke/cpustats/PreviewActivity.kt
1
14522
package jp.takke.cpustats import android.annotation.SuppressLint import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.os.Build import android.os.Bundle import android.os.IBinder import android.os.RemoteException import android.text.SpannableStringBuilder import android.text.Spanned import android.text.style.RelativeSizeSpan import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.launch class PreviewActivity : AppCompatActivity() { // 表示確認 private var mIsForeground = false // サービス実行フラグ(メニュー切り替え用。コールバックがあれば実行中と判定する) private var mServiceMaybeRunning = false // サービスのIF private var mServiceIf: IUsageUpdateService? = null private val mConfigActivityLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { // 設定完了 // 設定変更の内容をサービスに反映させる if (mServiceIf != null) { try { // 設定のリロード MyLog.d("request reloadSettings") mServiceIf!!.reloadSettings() } catch (e: RemoteException) { MyLog.e(e) } } else { MyLog.w("cannot reloadSettings (no service i.f.)") // 接続後に再ロードする } } // コールバックIFの実装 private val mCallback = object : IUsageUpdateCallback.Stub() { /** * サービスからの通知受信メソッド */ @Throws(RemoteException::class) override fun updateUsage(cpuUsages: IntArray, freqs: IntArray, minFreqs: IntArray, maxFreqs: IntArray) { lifecycleScope.launch { // サービス実行中フラグを立てておく mServiceMaybeRunning = true if (mIsForeground) { // CPUクロック周波数表示 showCpuFrequency(freqs, minFreqs, maxFreqs) // CPU使用率表示更新 showCpuUsages(cpuUsages, freqs, minFreqs, maxFreqs) // setTitle(getString(R.string.app_name) + " Freq: " + MyUtil.formatFreq(currentFreq) + ""); } } } } // サービスのコネクション private val mServiceConnection = object : ServiceConnection { override fun onServiceConnected(name: ComponentName, service: IBinder) { MyLog.i("PreviewActivity.onServiceConnected") // サービスのインターフェースを取得する mServiceIf = IUsageUpdateService.Stub.asInterface(service) try { // コールバック登録 mServiceIf?.registerCallback(mCallback) // onActivityResult 後に設定がロードされていないかもしれないのでここで強制再ロードする mServiceIf?.reloadSettings() } catch (e: RemoteException) { MyLog.e(e) } } override fun onServiceDisconnected(name: ComponentName) { MyLog.i("PreviewActivity.onServiceDisconnected") mServiceIf = null } } public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_preview) MyLog.d("PreviewActivity.onCreate") // とりあえず全消去 hideAllCoreFreqInfo() // CPU クロック更新 val coreCount = CpuInfoCollector.calcCpuCoreCount() val fi = AllCoreFrequencyInfo(coreCount) showCpuFrequency(fi.freqs, fi.minFreqs, fi.maxFreqs) // CPU使用率表示更新 val dummyCpuUsages = IntArray(coreCount) for (i in dummyCpuUsages.indices) { dummyCpuUsages[i] = 0 } CpuInfoCollector.takeAllCoreFreqs(fi) // CPU周波数が100%になってしまうので最初はゼロにしておく System.arraycopy(fi.minFreqs, 0, fi.freqs, 0, fi.freqs.size) showCpuUsages(dummyCpuUsages, fi.freqs, fi.minFreqs, fi.maxFreqs) // Toolbar初期化 setSupportActionBar(findViewById(R.id.my_toolbar)) // Toolbarのアイコン変更 setActionBarLogo(R.drawable.single000) // サービス開始 doBindService() } private fun doBindService() { // サービスへのバインド開始 val serviceIntent = Intent(this, UsageUpdateService::class.java) // start MyLog.d("PreviewActivity: startService of UsageUpdateService") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { serviceIntent.putExtra("FOREGROUND_REQUEST", true) startForegroundService(serviceIntent) } else { startService(serviceIntent) } // bind bindService(serviceIntent, mServiceConnection, Context.BIND_AUTO_CREATE) } private fun setActionBarLogo(iconId: Int) { // val actionBar = supportActionBar // actionBar?.setLogo(iconId) val toolbar = findViewById<Toolbar?>(R.id.my_toolbar) toolbar?.setNavigationIcon(iconId) // toolbar.setLogo(iconId) } private fun hideAllCoreFreqInfo() { // Core val cores = intArrayOf(R.id.core1, R.id.core2, R.id.core3, R.id.core4, R.id.core5, R.id.core6, R.id.core7, R.id.core8) for (i in 0..7) { findViewById<View>(cores[i]).visibility = View.GONE } // Freq findViewById<View>(R.id.freqImage).visibility = View.GONE findViewById<View>(R.id.freqText1).visibility = View.GONE } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.activity_preview, menu) return true } override fun onPrepareOptionsMenu(menu: Menu): Boolean { // サービス状態によってmenu変更 run { val item = menu.findItem(R.id.menu_start_service) if (item != null) { item.isVisible = !mServiceMaybeRunning } } run { val item = menu.findItem(R.id.menu_stop_service) if (item != null) { item.isVisible = mServiceMaybeRunning } } return super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menu_start_service -> // サービス開始 if (mServiceIf != null) { MyLog.i("PreviewActivity: start") try { // 常駐開始 mServiceIf!!.startResident() } catch (e: RemoteException) { MyLog.e(e) } } R.id.menu_stop_service -> // サービス停止 if (mServiceIf != null) { MyLog.i("PreviewActivity: stop") try { // 常駐停止 mServiceIf!!.stopResident() // サービス実行中フラグを下ろしておく mServiceMaybeRunning = false // 表示初期化 hideAllCoreFreqInfo() // タイトル初期化 title = "CPU Stats" // Toolbarのアイコン初期化 setActionBarLogo(R.drawable.single000) } catch (e: RemoteException) { MyLog.e(e) } } R.id.menu_settings -> { val intent = Intent(this, ConfigActivity::class.java) mConfigActivityLauncher.launch(intent) } R.id.menu_about -> startActivity(Intent(this, AboutActivity::class.java)) R.id.menu_exut -> // 終了 finish() } return super.onOptionsItemSelected(item) } override fun onDestroy() { MyLog.d("PreviewActivity.onDestroy") cleanupServiceConnection() super.onDestroy() } private fun cleanupServiceConnection() { // コールバック解除 if (mServiceIf != null) { try { mServiceIf!!.unregisterCallback(mCallback) } catch (e: RemoteException) { MyLog.e(e) } } // サービスのbind解除 unbindService(mServiceConnection) } override fun onPause() { MyLog.d("onPause") mIsForeground = false super.onPause() } override fun onResume() { MyLog.d("onResume") mIsForeground = true super.onResume() } /** * CPU クロック周波数を画面に表示する */ @SuppressLint("SetTextI18n") private fun showCpuFrequency(freqs: IntArray, minFreqs: IntArray, maxFreqs: IntArray) { // 全コアのうち最適なクロック周波数を探す val activeCoreIndex = MyUtil.getActiveCoreIndex(freqs) val currentFreq = freqs[activeCoreIndex] val minFreq = minFreqs[activeCoreIndex] val maxFreq = maxFreqs[activeCoreIndex] val textView1 = findViewById<View>(R.id.freqText1) as TextView val ssb = SpannableStringBuilder() ssb.append(MyUtil.formatFreq(currentFreq)) // アクティブなコア番号と(周波数による)負荷 run { val start = ssb.length val clockPercent = MyUtil.getClockPercent(currentFreq, minFreq, maxFreq) ssb.append(" [Core " + (activeCoreIndex + 1) + ": " + clockPercent + "%]") ssb.setSpan(RelativeSizeSpan(0.8f), start, ssb.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) // MyLog.i(" clock[" + currentFreq + "] => " + clockPercent + "%"); } // 周波数の min/max run { ssb.append("\n") val minFreqText = MyUtil.formatFreq(minFreq) val maxFreqText = MyUtil.formatFreq(maxFreq) val start = ssb.length ssb.append(" ($minFreqText - $maxFreqText)") ssb.setSpan(RelativeSizeSpan(0.8f), start, ssb.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } textView1.text = ssb textView1.visibility = View.VISIBLE val id = ResourceUtil.getIconIdForCpuFreq(currentFreq) val imageView = findViewById<View>(R.id.freqImage) as ImageView imageView.setImageResource(id) imageView.visibility = View.VISIBLE } /** * CPU 使用率を画面に表示する */ @SuppressLint("SetTextI18n") private fun showCpuUsages(cpuUsages: IntArray?, freqs: IntArray, minFreqs: IntArray, maxFreqs: IntArray) { // MyLog.d("PreviewActivity.updateCpuUsages"); // Toolbarのアイコン変更 if (cpuUsages != null && cpuUsages.isNotEmpty()) { val id = ResourceUtil.getIconIdForCpuUsageSingleColor(cpuUsages[0]) setActionBarLogo(id) } // プレビュー画面に表示 val cores = intArrayOf(R.id.core1, R.id.core2, R.id.core3, R.id.core4, R.id.core5, R.id.core6, R.id.core7, R.id.core8) val coreCount = CpuInfoCollector.calcCpuCoreCount() for (i in 0..7) { if (coreCount <= i) { // Coreが少ないので消去 findViewById<View>(cores[i]).visibility = View.GONE continue } val coreView = findViewById<View>(cores[i]) coreView.visibility = View.VISIBLE var cpuUsage = 0 if (cpuUsages != null && cpuUsages.size > i + 1) { cpuUsage = cpuUsages[i + 1] } //-------------------------------------------------- // アイコン設定 //-------------------------------------------------- val id = ResourceUtil.getIconIdForCpuUsageSingleColor(cpuUsage) val imageView = coreView.findViewById<View>(R.id.coreImage) as ImageView imageView.setImageResource(id) imageView.visibility = View.VISIBLE //-------------------------------------------------- // テキスト設定 //-------------------------------------------------- val textView = coreView.findViewById<View>(R.id.coreText) as TextView val ssb = SpannableStringBuilder() ssb.append("Core" + (i + 1) + ": " + cpuUsage + "%") // MyLog.i("disp core[" + i + "] = " + cpuUsage + "% (max=" + maxFreqs[i] + ")"); // 周波数 val freqText = MyUtil.formatFreq(freqs[i]) ssb.append("\n") ssb.append(" $freqText") // 周波数による負荷 val clockPercent = MyUtil.getClockPercent(freqs[i], minFreqs[i], maxFreqs[i]) run { val start = ssb.length ssb.append(" [$clockPercent%]") ssb.setSpan(RelativeSizeSpan(0.8f), start, ssb.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } // 周波数の min/max run { ssb.append("\n") val start = ssb.length val minFreqText = MyUtil.formatFreq(minFreqs[i]) val maxFreqText = MyUtil.formatFreq(maxFreqs[i]) ssb.append(" ($minFreqText - $maxFreqText)") ssb.setSpan(RelativeSizeSpan(0.8f), start, ssb.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } textView.text = ssb textView.visibility = View.VISIBLE // アクティブコアの背景色を変える val color = ResourceUtil.getBackgroundColor(clockPercent) coreView.setBackgroundColor(color) } } }
apache-2.0
0d113ec89b3c661bc4ab2d2435f43ec9
29.368539
126
0.558088
4.265783
false
false
false
false
leafclick/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/BooleanCommitOption.kt
1
2140
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.ui import com.intellij.ide.ui.UISettings import com.intellij.openapi.options.UnnamedConfigurable import com.intellij.openapi.vcs.CheckinProjectPanel import com.intellij.openapi.vcs.checkin.CheckinHandlerUtil.disableWhenDumb import com.intellij.openapi.vcs.configurable.CommitOptionsConfigurable import com.intellij.openapi.vcs.ui.RefreshableOnComponent import com.intellij.ui.components.JBCheckBox import com.intellij.vcs.commit.isNonModalCommit import org.jetbrains.annotations.Nls import java.util.function.Consumer import javax.swing.JComponent import kotlin.reflect.KMutableProperty0 open class BooleanCommitOption( private val checkinPanel: CheckinProjectPanel, @Nls text: String, disableWhenDumb: Boolean, private val getter: () -> Boolean, private val setter: Consumer<Boolean> ) : RefreshableOnComponent, UnnamedConfigurable { constructor(panel: CheckinProjectPanel, @Nls text: String, disableWhenDumb: Boolean, property: KMutableProperty0<Boolean>) : this(panel, text, disableWhenDumb, { property.get() }, Consumer { property.set(it) }) protected val checkBox = JBCheckBox(text).apply { isFocusable = isInSettings || isInNonModalOptionsPopup || UISettings.shadowInstance.disableMnemonicsInControls if (disableWhenDumb && !isInSettings) disableWhenDumb(checkinPanel.project, this, "Impossible until indices are up-to-date") } private val isInSettings get() = checkinPanel is CommitOptionsConfigurable.CheckinPanel private val isInNonModalOptionsPopup get() = checkinPanel.isNonModalCommit override fun refresh() { } override fun saveState() { setter.accept(checkBox.isSelected) } override fun restoreState() { checkBox.isSelected = getter() } override fun getComponent(): JComponent = checkBox override fun createComponent() = component override fun isModified() = checkBox.isSelected != getter() override fun apply() = saveState() override fun reset() = restoreState() }
apache-2.0
dd30b88c09b30644e8f27a60f202fe21
36.561404
140
0.788318
4.582441
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/codeInsight/smartEnter/SmartEnterTest.kt
4
33570
// 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.codeInsight.smartEnter import com.intellij.ide.highlighter.JavaFileType import com.intellij.openapi.actionSystem.IdeActions import com.intellij.testFramework.LightProjectDescriptor import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.junit.internal.runners.JUnit38ClassRunner import org.junit.runner.RunWith @RunWith(JUnit38ClassRunner::class) class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { fun testIfCondition() = doFunTest( """ if <caret> """, """ if (<caret>) { } """ ) fun testIfCondition2() = doFunTest( """ if<caret> """, """ if (<caret>) { } """ ) fun testIfWithFollowingCode() = doFunTest( """ if<caret> return true """, """ if (<caret>) { } return true """ ) fun testIfCondition3() = doFunTest( """ if (<caret> """, """ if (<caret>) { } """ ) fun testIfCondition4() = doFunTest( """ if (true<caret>) { } """, """ if (true) { <caret> } """ ) fun testIfCondition5() = doFunTest( """ if (true) {<caret> """, """ if (true) { <caret> } """ ) fun testIfCondition6() = doFunTest( """ if (true<caret>) { println() } """, """ if (true) { <caret> println() } """ ) fun testIfCondition7() = doFunTest( """ if<caret> if (true && false ) return """, """ if (<caret>) { } if (true && false ) return """ ) fun testIfThenOneLine1() = doFunTest( """ if (true) println()<caret> """, """ if (true) println() <caret> """ ) fun testIfThenOneLine2() = doFunTest( """ if (true) <caret>println() """, """ if (true) println() <caret> """ ) fun testIfThenOneLine3() = doFunTest( """ if (true && false ) <caret>println() """, """ if (true && false ) println() <caret> """ ) fun testIfThenMultiLine1() = doFunTest( """ if (true) println()<caret> """, """ if (true) println() <caret> """ ) fun testIfThenMultiLine2() = doFunTest( """ if (true) println()<caret> """, """ if (true) println() <caret> """ ) // TODO: indent for println fun testIfThenMultiLine3() = doFunTest( """ if (true<caret>) println() """, """ if (true) { <caret> } println() """ ) fun testIfWithReformat() = doFunTest( """ if (true<caret>) { } """, """ if (true) { <caret> } """ ) fun testElse() = doFunTest( """ if (true) { } else<caret> """, """ if (true) { } else { <caret> } """ ) fun testElseOneLine1() = doFunTest( """ if (true) { } else println()<caret> """, """ if (true) { } else println() <caret> """ ) fun testElseOneLine2() = doFunTest( """ if (true) { } else <caret>println() """, """ if (true) { } else println() <caret> """ ) fun testElseTwoLines1() = doFunTest( """ if (true) { } else <caret>println() """, """ if (true) { } else println() <caret> """ ) fun testElseTwoLines2() = doFunTest( """ if (true) { } else println()<caret> """, """ if (true) { } else println() <caret> """ ) // TODO: remove space in expected data fun testElseWithSpace() = doFunTest( """ if (true) { } else <caret> """, """ if (true) { } else { <caret> }${' '} """ ) fun testWhile() = doFunTest( """ while <caret> """, """ while (<caret>) { } """ ) fun testWhile2() = doFunTest( """ while<caret> """, """ while (<caret>) { } """ ) fun testWhile3() = doFunTest( """ while (<caret> """, """ while (<caret>) { } """ ) fun testWhile4() = doFunTest( """ while (true<caret>) { } """, """ while (true) { <caret> } """ ) fun testWhile5() = doFunTest( """ while (true) {<caret> """, """ while (true) { <caret> } """ ) fun testWhile6() = doFunTest( """ while (true<caret>) { println() } """, """ while (true) { <caret> println() } """ ) fun testWhile7() = doFunTest( """ while ()<caret> """, """ while (<caret>) { } """ ) fun testWhileSingle() = doFunTest( """ <caret>while (true) println() """, """ while (true) println() <caret> """ ) fun testWhileMultiLine1() = doFunTest( """ while (true) println()<caret> """, """ while (true) println() <caret> """ ) fun testWhileMultiLine2() = doFunTest( """ while (<caret>true) println() """, """ while (true) { <caret> } println() """ ) fun testForStatement() = doFunTest( """ for <caret> """, """ for (<caret>) { } """ ) fun testForStatement2() = doFunTest( """ for<caret> """, """ for (<caret>) { } """ ) fun testForStatement4() = doFunTest( """ for (i in 1..10<caret>) { } """, """ for (i in 1..10) { <caret> } """ ) fun testForStatement5() = doFunTest( """ for (i in 1..10) {<caret> """, """ for (i in 1..10) { <caret> } """ ) fun testForStatement6() = doFunTest( """ for (i in 1..10<caret>) { println() } """, """ for (i in 1..10) { <caret> println() } """ ) fun testForStatementSingle() = doFunTest( """ for (i in 1..10<caret>) println() """, """ for (i in 1..10) println() <caret> """ ) fun testForStatementSingleEmpty() = doFunTest( """ for (<caret>) println() """, """ for (<caret>) println() """ ) fun testForStatementOnLoopParameter() = doFunTest( """ for (som<caret>e) println() """, """ for (some) { <caret> } println() """ ) fun testForMultiLine1() = doFunTest( """ for (i in 1..10<caret>) println() """, """ for (i in 1..10) { <caret> } println() """ ) fun testForMultiLine2() = doFunTest( """ for (i in 1..10) println()<caret> """, """ for (i in 1..10) println() <caret> """ ) fun testWhen() = doFunTest( """ when <caret> """, """ when { <caret> } """ ) fun testWhen1() = doFunTest( """ when<caret> """, """ when { <caret> } """ ) fun testWhen2() = doFunTest( """ when (true<caret>) { } """, """ when (true) { <caret> } """ ) fun testWhen3() = doFunTest( """ when (true) {<caret> """, """ when (true) { <caret> } """ ) fun testWhen4() = doFunTest( """ when (true<caret>) { false -> println("false") } """, """ when (true) { <caret> false -> println("false") } """ ) fun testWhen5() = doFunTest( """ when (<caret>) """, """ when (<caret>) { } """ ) fun testWhen6() = doFunTest( """ when (true<caret>) """, """ when (true) { <caret> } """ ) // Check that no addition {} inserted fun testWhenBadParsed() = doFunTest( """ when ({<caret> } """, """ when ({ <caret> } """ ) fun testDoWhile() = doFunTest( """ do <caret> """, """ do { } while (<caret>)${' '} """ ) fun testDoWhile2() = doFunTest( """ do<caret> """, """ do { } while (<caret>) """ ) fun testDoWhile3() = doFunTest( """ do<caret> { println(hi) } """, """ do { println(hi) } while (<caret>) """ ) fun testDoWhile5() = doFunTest( """ do<caret> { } while () """, """ do { } while (<caret>) """ ) fun testDoWhile6() = doFunTest( """ do<caret> { } while (true) """, """ do { <caret> } while (true) """ ) fun testDoWhile7() = doFunTest( """ do { } <caret>while (true) """, """ do { <caret> } while (true) """ ) fun testDoWhile8() = doFunTest( """ do { } while (<caret>true) """, """ do { <caret> } while (true) """ ) fun testDoWhile9() = doFunTest( """ do while<caret> """, """ do { } while (<caret>) """ ) fun testDoWhile10() = doFunTest( """ do while (true<caret>) """, """ do { <caret> } while (true) """ ) fun testDoWhile11() = doFunTest( """ do { println("some") } while<caret> """, """ do { println("some") } while (<caret>) """ ) fun testDoWhile12() = doFunTest( """ do { println("some") } while (true<caret> """, """ do { <caret> println("some") } while (true """ ) fun testDoWhile13() = doFunTest( """ do<caret> println("some") """, """ do { println("some") } while (<caret>) """ ) fun testDoWhile14() = doFunTest( """ do <caret> println("some") """, """ do { println("some") } while (<caret>) """ ) fun testDoWhileOneLine1() = doFunTest( """ do println("some") while (true<caret>) println("hi") """, """ do println("some") while (true) <caret> println("hi") """ ) fun testDoWhileOneLine2() = doFunTest( """ do <caret>println("some") while (true) println("hi") """, """ do println("some") while (true) <caret> println("hi") """ ) fun testDoWhileMultiLine1() = doFunTest( """ do println()<caret> while (true) """, """ do println() <caret> while (true) """ ) fun testDoWhileMultiLine2() = doFunTest( """ do<caret> println() while (true) """, """ do { <caret> println() } while (true) """ ) fun testDoWhileMultiLine3() = doFunTest( """ do println() while <caret>(true) """, """ do { <caret> println() } while (true) """ ) fun testFunBody() = doFileTest( """ fun test<caret>() """, """ fun test() { <caret> } """ ) fun testFunBody1() = doFileTest( """ fun test<caret> """, """ fun test() { <caret> } """ ) fun testFunBody2() = doFileTest( """ fun (p: Int, s: String<caret> """, """ fun(p: Int, s: String) { <caret> } """ ) fun testFunBody3() = doFileTest( """ interface Some { fun (<caret>p: Int) } """, """ interface Some { fun(p: Int) <caret> } """ ) fun testFunBody4() = doFileTest( """ class Some { abstract fun (<caret>p: Int) } """, """ class Some { abstract fun(p: Int) <caret> } """ ) fun testFunBody5() = doFileTest( """ class Some { fun test(<caret>p: Int) = 1 } """, """ class Some { fun test(p: Int) = 1 <caret> } """ ) fun testFunBody6() = doFileTest( """ fun test(<caret>p: Int) { } """, """ fun test(p: Int) { <caret> } """ ) fun testFunBody7() = doFileTest( """ trait T fun <U> other() where U: T<caret> """, """ trait T fun <U> other() where U : T { <caret> } """ ) fun testFunBody8() = doFileTest( """ fun Int.other<caret> """, """ fun Int.other() { <caret> } """ ) fun testFunBody9() = doFileTest( """ fun test(){<caret>} """, """ fun test() {} <caret> """ ) fun testInLambda1() = doFunTest( """ some { p -><caret> } """, """ some { p -> <caret> } """ ) fun testInLambda2() = doFunTest( """ some { p<caret> -> } """, """ some { p -> <caret> } """ ) fun testInLambda3() = doFunTest( """ some { (<caret>p: Int) : Int -> } """, """ some { (p: Int) : Int -> <caret> } """ ) fun testInLambda4() = doFunTest( """ some { (p: <caret>Int) : Int -> } """, """ some { (p: Int) : Int -> <caret> } """ ) fun testSetter1() = doFileTest( """ var a : Int = 0 set<caret> """, """ var a : Int = 0 set <caret> """ ) fun testSetter2() = doFileTest( """ var a : Int = 0 set(<caret> """, """ var a : Int = 0 set(value) { <caret> } """ ) fun testSetter3() = doFileTest( """ var a : Int = 0 set(<caret>) """, """ var a : Int = 0 set(value) { <caret> } """ ) fun testSetter4() = doFileTest( """ var a : Int = 0 set(v<caret>) """, """ var a : Int = 0 set(v) { <caret> } """ ) fun testSetter5() = doFileTest( """ var a : Int = 0 set(<caret>) { } """, """ var a : Int = 0 set(value) { <caret> } """ ) fun testSetter6() = doFileTest( """ var a : Int = 0 set(v<caret>) { } """, """ var a : Int = 0 set(v) { <caret> } """ ) fun testSetter7() = doFileTest( """ var a : Int = 0 set(value){<caret>} """, """ var a : Int = 0 set(value) {} <caret> """ ) fun testSetterPrivate1() = doFileTest( """ var a : Int = 0 private set<caret> """, """ var a : Int = 0 private set <caret> """ ) fun testSetterPrivate2() = doFileTest( """ var a : Int = 0 private set(<caret> """, """ var a : Int = 0 private set(value) { <caret> } """ ) fun testSetterPrivate3() = doFileTest( """ var a : Int = 0 private set(<caret>) """, """ var a : Int = 0 private set(value) { <caret> } """ ) fun testSetterPrivate4() = doFileTest( """ var a : Int = 0 private set(v<caret>) """, """ var a : Int = 0 private set(v) { <caret> } """ ) fun testSetterPrivate5() = doFileTest( """ var a : Int = 0 private set(<caret>) { } """, """ var a : Int = 0 private set(value) { <caret> } """ ) fun testSetterPrivate6() = doFileTest( """ var a : Int = 0 private set(v<caret>) { } """, """ var a : Int = 0 private set(v) { <caret> } """ ) fun testGetter1() = doFileTest( """ var a: Int = 0 get<caret> """ , """ var a: Int = 0 get <caret> """ ) fun testGetter2() = doFileTest( """ var a: Int = 0 get(<caret> """ , """ var a: Int = 0 get() { <caret> } """ ) fun testGetter3() = doFileTest( """ var a: Int = 0 get(<caret>) """ , """ var a: Int = 0 get() { <caret> } """ ) fun testGetter4() = doFileTest( """ var a: Int = 0 get(<caret>) = 1 """ , """ var a: Int = 0 get() = 1 <caret> """ ) fun testGetter5() = doFileTest( """ var a: Int = 0 get(<caret>) { return 1 } """ , """ var a: Int = 0 get() { <caret> return 1 } """ ) fun testTryBody() = doFunTest( """ try<caret> """, """ try { <caret> } """ ) fun testCatchBody() = doFunTest( """ try { } catch(e: Exception) <caret> """, """ try { } catch (e: Exception) { <caret> }${" "} """ ) fun testCatchParameter1() = doFunTest( """ try { } catch<caret> """, """ try { } catch (<caret>) { } """ ) fun testCatchParameter2() = doFunTest( """ try { } catch(<caret> """, """ try { } catch (<caret>) { } """ ) fun testCatchParameter3() = doFunTest( """ try { } catch(<caret> {} """, """ try { } catch (<caret>) { } """ ) fun testCatchParameter4() = doFunTest( """ try { } catch(e: Exception<caret> """, """ try { } catch (e: Exception) { <caret> } """ ) fun testFinallyBody() = doFunTest( """ try { } catch(e: Exception) { } finally<caret> """, """ try { } catch (e: Exception) { } finally { <caret> } """ ) fun testLambdaParam() = doFileTest( """ fun foo(a: Any, block: () -> Unit) { } fun test() { foo(Any()<caret>) } """, """ fun foo(a: Any, block: () -> Unit) { } fun test() { foo(Any()) { <caret>} } """ ) fun testExtensionLambdaParam() = doFileTest( """ fun foo(a: Any, block: Any.() -> Unit) { } fun test() { foo(Any()<caret>) } """, """ fun foo(a: Any, block: Any.() -> Unit) { } fun test() { foo(Any()) { <caret>} } """ ) fun testClassInit() = doFileTest( """ class Foo { init<caret> } """, """ class Foo { init { <caret> } } """ ) fun testClassBody1() = doFileTest( """ class Foo<caret> """, """ class Foo { <caret> } """ ) fun testClassBody2() = doFileTest( """ class <caret>Foo """, """ class Foo { <caret> } """ ) fun testObjectExpressionBody1() = doFileTest( """ interface I val a = object : I<caret> """, """ interface I val a = object : I { <caret> } """ ) fun testObjectExpressionBody2() = doFileTest( """ interface I val a = object : I<caret> val b = "" """, """ interface I val a = object : I { <caret> } val b = "" """ ) fun testClassBodyHasInitializedSuperType() = doFileTest( """ open class A class B : A()<caret> """, """ open class A class B : A() { <caret> } """ ) fun testClassBodyHasNotInitializedSuperType() = doFileTest( """ open class A class B : A<caret> """, """ open class A class B : A() { <caret> } """ ) fun testClassBodyHasNotInitializedSuperType2() = doFileTest( """ sealed class A(val s: String) class B : A<caret> """, """ sealed class A(val s: String) class B : A() { <caret> } """ ) fun testClassBodyHasNotInitializedSuperType3() = doFileTest( """ interface I interface J abstract class A class B : I, A, J<caret> """, """ interface I interface J abstract class A class B : I, A(), J { <caret> } """ ) fun testClassBodyHasNotInitializedJavaInterfaceSuperType() = doFileTest( before = """ class A : I<caret> """, after = """ class A : I { <caret> } """, javaFile = """ interface I {} """ ) fun testClassBodyHasNotInitializedJavaClassSuperType() = doFileTest( before = """ class A : C<caret> """, after = """ class A : C() { <caret> } """, javaFile = """ class C {} """ ) fun testClassBodyHasNotInitializedAbstractJavaClassSuperType() = doFileTest( before = """ class A : C<caret> """, after = """ class A : C() { <caret> } """, javaFile = """ abstract class C {} """ ) fun testClassBodyHasNotInitializedJavaInterfaceAndClassSuperType() = doFileTest( before = """ class A : C, I<caret> """, after = """ class A : C(), I { <caret> } """, javaFile = """ interface I {} class C {} """ ) fun testEmptyLine() = doFileTest( """fun foo() {} <caret>""", """fun foo() {} <caret>""" ) fun testValueArgumentList1() = doFileTest( """ fun foo(i: Int) = 1 fun test1() { foo(1<caret> } """, """ fun foo(i: Int) = 1 fun test1() { foo(1)<caret> } """ ) fun testValueArgumentList2() = doFileTest( """ fun foo(i: Int) = 1 fun test2() { foo(foo(1<caret> } """, """ fun foo(i: Int) = 1 fun test2() { foo(foo(1))<caret> } """ ) fun testValueArgumentList3() = doFileTest( """ fun foo(i: Int) = 1 fun test3() { foo(<caret> } """, """ fun foo(i: Int) = 1 fun test3() { foo(<caret>) } """ ) fun testValueArgumentList4() = doFileTest( """ fun foo(i: Int) = 1 fun test4() { foo(1,<caret> } """, """ fun foo(i: Int) = 1 fun test4() { foo(1<caret>) } """ ) fun testValueArgumentList5() = doFileTest( """ class Foo(i: Int) fun test5() { Foo(1<caret> } """, """ class Foo(i: Int) fun test5() { Foo(1)<caret> } """ ) fun testValueArgumentList6() = doFileTest( """ fun foo(s: String) = 1 fun test() { foo(""<caret> val aValue = "" } """, """ fun foo(s: String) = 1 fun test() { foo("")<caret> val aValue = "" } """ ) fun testValueArgumentList7() = doFileTest( """ fun test() { String.to("123"<caret> val aValue = "" } """, """ fun test() { String.to("123") <caret> val aValue = "" } """ ) fun doFunTest(before: String, after: String) { fun String.withFunContext(): String { val bodyText = "//----\n${this.trimIndent()}\n//----" val withIndent = bodyText.prependIndent(" ") return "fun method() {\n$withIndent\n}" } doTest(before.withFunContext(), after.withFunContext()) } fun doFileTest(before: String, after: String, javaFile: String = "") { if (javaFile.isNotEmpty()) myFixture.configureByText(JavaFileType.INSTANCE, javaFile.trimIndent().removeFirstEmptyLines()) doTest(before.trimIndent().removeFirstEmptyLines(), after.trimIndent().removeFirstEmptyLines()) } fun doTest(before: String, after: String) { myFixture.configureByText(KotlinFileType.INSTANCE, before) myFixture.performEditorAction(IdeActions.ACTION_EDITOR_COMPLETE_STATEMENT) myFixture.checkResult(after) } override fun getProjectDescriptor(): LightProjectDescriptor = LightJavaCodeInsightFixtureTestCase.JAVA_LATEST private fun String.removeFirstEmptyLines() = this.split("\n").dropWhile { it.isEmpty() }.joinToString(separator = "\n") }
apache-2.0
617596f28fae5179b3ad08fa68b71f78
19.029833
158
0.30709
4.981451
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/DestructuringWrongNameInspection.kt
5
2306
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInsight.daemon.impl.quickfix.RenameElementFix import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.psi.destructuringDeclarationVisitor class DestructuringWrongNameInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return destructuringDeclarationVisitor(fun(destructuringDeclaration) { val initializer = destructuringDeclaration.initializer ?: return val type = initializer.analyze().getType(initializer) ?: return val classDescriptor = type.constructor.declarationDescriptor as? ClassDescriptor ?: return val primaryParameterNames = classDescriptor.constructors .firstOrNull { it.isPrimary } ?.valueParameters ?.map { it.name.asString() } ?: return destructuringDeclaration.entries.forEachIndexed { entryIndex, entry -> val variableName = entry.name if (variableName != primaryParameterNames.getOrNull(entryIndex)) { for ((parameterIndex, parameterName) in primaryParameterNames.withIndex()) { if (parameterIndex == entryIndex) continue if (variableName == parameterName) { val fix = primaryParameterNames.getOrNull(entryIndex)?.let { RenameElementFix(entry, it) } holder.registerProblem( entry, KotlinBundle.message("variable.name.0.matches.the.name.of.a.different.component", variableName), *listOfNotNull(fix).toTypedArray() ) break } } } } }) } }
apache-2.0
f048d55b84f8da9946e0114234c2ab62
50.244444
158
0.6366
5.98961
false
false
false
false
jotomo/AndroidAPS
danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Dual_Bolus.kt
1
1586
package info.nightscout.androidaps.danars.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.danars.encryption.BleEncryption import javax.inject.Inject class DanaRS_Packet_Bolus_Get_Dual_Bolus( injector: HasAndroidInjector ) : DanaRS_Packet(injector) { @Inject lateinit var danaPump: DanaPump init { opCode = BleEncryption.DANAR_PACKET__OPCODE_BOLUS__GET_DUAL_BOLUS aapsLogger.debug(LTag.PUMPCOMM, "New message") } override fun handleMessage(data: ByteArray) { val error = byteArrayToInt(getBytes(data, DATA_START, 1)) danaPump.bolusStep = byteArrayToInt(getBytes(data, DATA_START + 1, 2)) / 100.0 danaPump.extendedBolusAbsoluteRate = byteArrayToInt(getBytes(data, DATA_START + 3, 2)) / 100.0 danaPump.maxBolus = byteArrayToInt(getBytes(data, DATA_START + 5, 2)) / 100.0 val bolusIncrement = byteArrayToInt(getBytes(data, DATA_START + 7, 1)) / 100.0 failed = error != 0 aapsLogger.debug(LTag.PUMPCOMM, "Result: $error") aapsLogger.debug(LTag.PUMPCOMM, "Bolus step: ${danaPump.bolusStep} U") aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus running: ${danaPump.extendedBolusAbsoluteRate} U/h") aapsLogger.debug(LTag.PUMPCOMM, "Max bolus: " + danaPump.maxBolus + " U") aapsLogger.debug(LTag.PUMPCOMM, "bolusIncrement: $bolusIncrement U") } override fun getFriendlyName(): String { return "BOLUS__GET_DUAL_BOLUS" } }
agpl-3.0
6eb4920646451e06dbc108259b73767b
41.891892
108
0.710593
4.01519
false
false
false
false
jotomo/AndroidAPS
app/src/main/java/info/nightscout/androidaps/utils/ActivityMonitor.kt
1
3301
package info.nightscout.androidaps.utils import android.app.Activity import android.app.Application import android.os.Bundle import android.text.Spanned import info.nightscout.androidaps.R import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import javax.inject.Inject import javax.inject.Singleton @Singleton class ActivityMonitor @Inject constructor( private var aapsLogger: AAPSLogger, private val resourceHelper: ResourceHelper, private var sp: SP ) : Application.ActivityLifecycleCallbacks { override fun onActivityPaused(activity: Activity?) { val name = activity?.javaClass?.simpleName ?: return val resumed = sp.getLong("Monitor_" + name + "_" + "resumed", 0) if (resumed == 0L) { aapsLogger.debug(LTag.UI, "onActivityPaused: $name resumed == 0") return } val elapsed = DateUtil.now() - resumed val total = sp.getLong("Monitor_" + name + "_total", 0) if (total == 0L) { sp.putLong("Monitor_" + name + "_start", DateUtil.now()) } sp.putLong("Monitor_" + name + "_total", total + elapsed) aapsLogger.debug(LTag.UI, "onActivityPaused: $name elapsed=$elapsed total=${total + elapsed}") } override fun onActivityResumed(activity: Activity?) { val name = activity?.javaClass?.simpleName ?: return aapsLogger.debug(LTag.UI, "onActivityResumed: $name") sp.putLong("Monitor_" + name + "_" + "resumed", DateUtil.now()) } override fun onActivityStarted(activity: Activity?) { } override fun onActivityDestroyed(activity: Activity?) { } override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) { } override fun onActivityStopped(activity: Activity?) { } override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) { } private fun toText(): String { val keys: Map<String, *> = sp.getAll() var result = "" for ((key, value) in keys) if (key.startsWith("Monitor") && key.endsWith("total")) { val v = if (value is Long) value else SafeParse.stringToLong(value as String) val activity = key.split("_")[1].replace("Activity", "") val duration = DateUtil.niceTimeScalar(v as Long, resourceHelper) val start = sp.getLong(key.replace("total", "start"), 0) val days = T.msecs(DateUtil.now() - start).days() result += "<b><span style=\"color:yellow\">$activity:</span></b> <b>$duration</b> in <b>$days</b> days<br>" } return result } fun stats(): Spanned { return HtmlHelper.fromHtml("<br><b>" + resourceHelper.gs(R.string.activitymonitor) + ":</b><br>" + toText()) } fun reset() { val keys: Map<String, *> = sp.getAll() for ((key, _) in keys) if (key.startsWith("Monitor") && key.endsWith("total")) { sp.remove(key) sp.remove(key.replace("total", "start")) sp.remove(key.replace("total", "resumed")) } } }
agpl-3.0
662aeae7db8e3f143b87842f70adc686
36.954023
123
0.624053
4.366402
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/models/responses/TaskDirectionDataTemp.kt
1
442
package com.habitrpg.android.habitica.models.responses class TaskDirectionDataTemp { var drop: TaskDirectionDataDrop? = null var quest: TaskDirectionDataQuest? = null var crit: Float? = null } class TaskDirectionDataQuest { var progressDelta: Double = 0.0 } class TaskDirectionDataDrop { var value: Int = 0 var key: String? = null var type: String? = null var dialog: String? = null }
gpl-3.0
398706dec761e74458263af99fae90fa
19.142857
54
0.671946
4.130841
false
false
false
false
siosio/intellij-community
platform/execution-impl/src/com/intellij/execution/impl/ExecutionManagerImpl.kt
1
40086
// 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.execution.impl import com.intellij.CommonBundle import com.intellij.build.BuildContentManager import com.intellij.execution.* import com.intellij.execution.configuration.CompatibilityAwareRunProfile import com.intellij.execution.configurations.RunConfiguration import com.intellij.execution.configurations.RunConfiguration.RestartSingletonResult import com.intellij.execution.configurations.RunProfile import com.intellij.execution.configurations.RunProfileState import com.intellij.execution.executors.DefaultRunExecutor import com.intellij.execution.filters.TextConsoleBuilderFactory import com.intellij.execution.impl.ExecutionManagerImpl.Companion.DELEGATED_RUN_PROFILE_KEY import com.intellij.execution.impl.statistics.RunConfigurationUsageTriggerCollector import com.intellij.execution.impl.statistics.RunConfigurationUsageTriggerCollector.RunConfigurationFinishType import com.intellij.execution.impl.statistics.RunConfigurationUsageTriggerCollector.UI_SHOWN_STAGE import com.intellij.execution.process.* import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.runners.ExecutionEnvironmentBuilder import com.intellij.execution.runners.ExecutionUtil import com.intellij.execution.runners.ProgramRunner import com.intellij.execution.target.TargetEnvironmentAwareRunProfile import com.intellij.execution.target.TargetProgressIndicator import com.intellij.execution.target.getEffectiveTargetName import com.intellij.execution.ui.ConsoleView import com.intellij.execution.ui.RunContentDescriptor import com.intellij.execution.ui.RunContentManager import com.intellij.ide.SaveAndSyncHandler import com.intellij.internal.statistic.StructuredIdeActivity import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.impl.SimpleDataContext import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.ReadAction import com.intellij.openapi.components.service import com.intellij.openapi.components.serviceIfCreated import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.project.* import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.Condition import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Key import com.intellij.openapi.util.UserDataHolder import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.wm.ToolWindow import com.intellij.ui.AppUIUtil import com.intellij.ui.UIBundle import com.intellij.ui.content.ContentManager import com.intellij.ui.content.impl.ContentImpl import com.intellij.util.Alarm import com.intellij.util.SmartList import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.containers.ContainerUtil import org.jetbrains.annotations.* import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.resolvedPromise import java.awt.BorderLayout import java.io.OutputStream import java.util.* import java.util.concurrent.Callable import java.util.concurrent.atomic.AtomicBoolean import javax.swing.JPanel import javax.swing.SwingUtilities class ExecutionManagerImpl(private val project: Project) : ExecutionManager(), Disposable { companion object { val LOG = logger<ExecutionManagerImpl>() private val EMPTY_PROCESS_HANDLERS = emptyArray<ProcessHandler>() internal val DELEGATED_RUN_PROFILE_KEY = Key.create<RunProfile>("DELEGATED_RUN_PROFILE_KEY") @JvmField val EXECUTION_SESSION_ID_KEY = Key.create<Any>("EXECUTION_SESSION_ID_KEY") @JvmField val EXECUTION_SKIP_RUN = Key.create<Boolean>("EXECUTION_SKIP_RUN") @JvmStatic fun getInstance(project: Project) = project.service<ExecutionManager>() as ExecutionManagerImpl @JvmStatic fun isProcessRunning(descriptor: RunContentDescriptor?): Boolean { val processHandler = descriptor?.processHandler return processHandler != null && !processHandler.isProcessTerminated } @JvmStatic fun stopProcess(descriptor: RunContentDescriptor?) { stopProcess(descriptor?.processHandler) } @JvmStatic fun stopProcess(processHandler: ProcessHandler?) { if (processHandler == null) { return } processHandler.putUserData(ProcessHandler.TERMINATION_REQUESTED, true) if (processHandler is KillableProcess && processHandler.isProcessTerminating) { // process termination was requested, but it's still alive // in this case 'force quit' will be performed processHandler.killProcess() return } if (!processHandler.isProcessTerminated) { if (processHandler.detachIsDefault()) { processHandler.detachProcess() } else { processHandler.destroyProcess() } } } @JvmStatic fun getAllDescriptors(project: Project): List<RunContentDescriptor> { return project.serviceIfCreated<RunContentManager>()?.allDescriptors ?: emptyList() } @ApiStatus.Internal @JvmStatic fun setDelegatedRunProfile(runProfile: RunProfile, runProfileToDelegate: RunProfile) { if (runProfile !== runProfileToDelegate && runProfile is UserDataHolder) { DELEGATED_RUN_PROFILE_KEY[runProfile] = runProfileToDelegate } } } init { val connection = ApplicationManager.getApplication().messageBus.connect(this) connection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener { override fun projectClosed(project: Project) { if (project === [email protected]) { inProgress.clear() } } }) } @set:TestOnly @Volatile var forceCompilationInTests = false private val awaitingTerminationAlarm = Alarm(Alarm.ThreadToUse.SWING_THREAD) private val awaitingRunProfiles = HashMap<RunProfile, ExecutionEnvironment>() private val runningConfigurations: MutableList<RunningConfigurationEntry> = ContainerUtil.createLockFreeCopyOnWriteList() private val inProgress = Collections.synchronizedSet(HashSet<InProgressEntry>()) private fun processNotStarted(environment: ExecutionEnvironment, activity: StructuredIdeActivity?, e : Throwable? = null) { RunConfigurationUsageTriggerCollector.logProcessFinished(activity, RunConfigurationFinishType.FAILED_TO_START) val executorId = environment.executor.id inProgress.remove(InProgressEntry(executorId, environment.runner.runnerId)) project.messageBus.syncPublisher(EXECUTION_TOPIC).processNotStarted(executorId, environment, e) } /** * Internal usage only. Maybe removed or changed in any moment. No backward compatibility. */ @ApiStatus.Internal override fun startRunProfile(environment: ExecutionEnvironment, starter: () -> Promise<RunContentDescriptor?>) { doStartRunProfile(environment) { // errors are handled by startRunProfile starter() .then { descriptor -> if (descriptor != null) { descriptor.executionId = environment.executionId val toolWindowId = RunContentManager.getInstance(environment.project).getContentDescriptorToolWindowId(environment) if (toolWindowId != null) { descriptor.contentToolWindowId = toolWindowId } environment.runnerAndConfigurationSettings?.let { descriptor.isActivateToolWindowWhenAdded = it.isActivateToolWindowBeforeRun } } environment.callback?.let { it.processStarted(descriptor) environment.callback = null } descriptor } } } override fun startRunProfile(starter: RunProfileStarter, environment: ExecutionEnvironment) { doStartRunProfile(environment) { starter.executeAsync(environment) } } private fun doStartRunProfile(environment: ExecutionEnvironment, task: () -> Promise<RunContentDescriptor>) { val activity = triggerUsage(environment) RunManager.getInstance(environment.project).refreshUsagesList(environment.runProfile) val project = environment.project val reuseContent = RunContentManager.getInstance(project).getReuseContent(environment) if (reuseContent != null) { reuseContent.executionId = environment.executionId environment.contentToReuse = reuseContent } val executor = environment.executor inProgress.add(InProgressEntry(executor.id, environment.runner.runnerId)) project.messageBus.syncPublisher(EXECUTION_TOPIC).processStartScheduled(executor.id, environment) val startRunnable = Runnable { if (project.isDisposed) { return@Runnable } project.messageBus.syncPublisher(EXECUTION_TOPIC).processStarting(executor.id, environment) fun handleError(e: Throwable) { processNotStarted(environment, activity, e) if (e !is ProcessCanceledException) { ProgramRunnerUtil.handleExecutionError(project, environment, e, environment.runProfile) LOG.debug(e) } } try { task() .onSuccess { descriptor -> AppUIUtil.invokeLaterIfProjectAlive(project) { if (descriptor == null) { processNotStarted(environment, activity) return@invokeLaterIfProjectAlive } val entry = RunningConfigurationEntry(descriptor, environment.runnerAndConfigurationSettings, executor) runningConfigurations.add(entry) Disposer.register(descriptor, Disposable { runningConfigurations.remove(entry) }) if (!descriptor.isHiddenContent && !environment.isHeadless) { RunContentManager.getInstance(project).showRunContent(executor, descriptor, environment.contentToReuse) } activity?.stageStarted(UI_SHOWN_STAGE) environment.contentToReuse = descriptor val processHandler = descriptor.processHandler if (processHandler != null) { if (!processHandler.isStartNotified) { project.messageBus.syncPublisher(EXECUTION_TOPIC).processStarting(executor.id, environment, processHandler) processHandler.startNotify() } inProgress.remove(InProgressEntry(executor.id, environment.runner.runnerId)) project.messageBus.syncPublisher(EXECUTION_TOPIC).processStarted(executor.id, environment, processHandler) val listener = ProcessExecutionListener(project, executor.id, environment, processHandler, descriptor, activity) processHandler.addProcessListener(listener) // Since we cannot guarantee that the listener is added before process handled is start notified, // we have to make sure the process termination events are delivered to the clients. // Here we check the current process state and manually deliver events, while // the ProcessExecutionListener guarantees each such event is only delivered once // either by this code, or by the ProcessHandler. val terminating = processHandler.isProcessTerminating val terminated = processHandler.isProcessTerminated if (terminating || terminated) { listener.processWillTerminate(ProcessEvent(processHandler), false /* doesn't matter */) if (terminated) { val exitCode = if (processHandler.isStartNotified) processHandler.exitCode ?: -1 else -1 listener.processTerminated(ProcessEvent(processHandler, exitCode)) } } } } } .onError(::handleError) } catch (e: Throwable) { handleError(e) } } if (!forceCompilationInTests && ApplicationManager.getApplication().isUnitTestMode) { startRunnable.run() } else { compileAndRun(Runnable { ApplicationManager.getApplication().invokeLater(startRunnable, project.disposed) }, environment, Runnable { if (!project.isDisposed) { processNotStarted(environment, activity) } }) } } override fun dispose() { for (entry in runningConfigurations) { Disposer.dispose(entry.descriptor) } runningConfigurations.clear() } @Suppress("OverridingDeprecatedMember") override fun getContentManager() = RunContentManager.getInstance(project) override fun getRunningProcesses(): Array<ProcessHandler> { var handlers: MutableList<ProcessHandler>? = null for (descriptor in getAllDescriptors(project)) { val processHandler = descriptor.processHandler ?: continue if (handlers == null) { handlers = SmartList() } handlers.add(processHandler) } return handlers?.toTypedArray() ?: EMPTY_PROCESS_HANDLERS } override fun compileAndRun(startRunnable: Runnable, environment: ExecutionEnvironment, onCancelRunnable: Runnable?) { var id = environment.executionId if (id == 0L) { id = environment.assignNewExecutionId() } val profile = environment.runProfile if (profile !is RunConfiguration) { startRunnable.run() return } val beforeRunTasks = doGetBeforeRunTasks(profile) if (beforeRunTasks.isEmpty()) { startRunnable.run() return } val context = environment.dataContext val projectContext = context ?: SimpleDataContext.getProjectContext(project) val runBeforeRunExecutorMap = Collections.synchronizedMap(linkedMapOf<BeforeRunTask<*>, Executor>()) ApplicationManager.getApplication().executeOnPooledThread { for (task in beforeRunTasks) { val provider = BeforeRunTaskProvider.getProvider(project, task.providerId) if (provider == null || task !is RunConfigurationBeforeRunProvider.RunConfigurableBeforeRunTask) { continue } val settings = task.settings if (settings != null) { // as side-effect here we setup runners list ( required for com.intellij.execution.impl.RunManagerImpl.canRunConfiguration() ) var executor = if (Registry.`is`("lock.run.executor.for.before.run.tasks", false)) { DefaultRunExecutor.getRunExecutorInstance() } else { environment.executor } val builder = ExecutionEnvironmentBuilder.createOrNull(executor, settings) if (builder == null || !RunManagerImpl.canRunConfiguration(settings, executor)) { executor = DefaultRunExecutor.getRunExecutorInstance() if (!RunManagerImpl.canRunConfiguration(settings, executor)) { // we should stop here as before run task cannot be executed at all (possibly it's invalid) onCancelRunnable?.run() ExecutionUtil.handleExecutionError(environment, ExecutionException( ExecutionBundle.message("dialog.message.cannot.start.before.run.task", settings))) return@executeOnPooledThread } } runBeforeRunExecutorMap[task] = executor } } for (task in beforeRunTasks) { if (project.isDisposed) { return@executeOnPooledThread } @Suppress("UNCHECKED_CAST") val provider = BeforeRunTaskProvider.getProvider(project, task.providerId) as BeforeRunTaskProvider<BeforeRunTask<*>>? if (provider == null) { LOG.warn("Cannot find BeforeRunTaskProvider for id='${task.providerId}'") continue } val builder = ExecutionEnvironmentBuilder(environment).contentToReuse(null) val executor = runBeforeRunExecutorMap[task] if (executor != null) { builder.executor(executor) } val taskEnvironment = builder.build() taskEnvironment.executionId = id EXECUTION_SESSION_ID_KEY.set(taskEnvironment, id) try { if (!provider.executeTask(projectContext, profile, taskEnvironment, task)) { if (onCancelRunnable != null) { SwingUtilities.invokeLater(onCancelRunnable) } return@executeOnPooledThread } } catch (e: ProcessCanceledException) { if (onCancelRunnable != null) { SwingUtilities.invokeLater(onCancelRunnable) } return@executeOnPooledThread } } doRun(environment, startRunnable) } } private fun doRun(environment: ExecutionEnvironment, startRunnable: Runnable) { val allowSkipRun = environment.getUserData(EXECUTION_SKIP_RUN) if (allowSkipRun != null && allowSkipRun) { processNotStarted(environment, null) return } // important! Do not use DumbService.smartInvokeLater here because it depends on modality state // and execution of startRunnable could be skipped if modality state check fails SwingUtilities.invokeLater { if (project.isDisposed) { return@invokeLater } val settings = environment.runnerAndConfigurationSettings if (settings != null && !settings.type.isDumbAware && DumbService.isDumb(project)) { DumbService.getInstance(project).runWhenSmart(startRunnable) } else { try { startRunnable.run() } catch (ignored: IndexNotReadyException) { ExecutionUtil.handleExecutionError(environment, ExecutionException( ExecutionBundle.message("dialog.message.cannot.start.while.indexing.in.progress"))) } } } } override fun restartRunProfile(project: Project, executor: Executor, target: ExecutionTarget, configuration: RunnerAndConfigurationSettings?, processHandler: ProcessHandler?) { val builder = createEnvironmentBuilder(project, executor, configuration) if (processHandler != null) { for (descriptor in getAllDescriptors(project)) { if (descriptor.processHandler === processHandler) { builder.contentToReuse(descriptor) break } } } restartRunProfile(builder.target(target).build()) } override fun restartRunProfile(environment: ExecutionEnvironment) { val configuration = environment.runnerAndConfigurationSettings val runningIncompatible: List<RunContentDescriptor> if (configuration == null) { runningIncompatible = emptyList() } else { runningIncompatible = getIncompatibleRunningDescriptors(configuration) } val contentToReuse = environment.contentToReuse val runningOfTheSameType = if (configuration != null && !configuration.configuration.isAllowRunningInParallel) { getRunningDescriptors(Condition { it.isOfSameType(configuration) }) } else if (isProcessRunning(contentToReuse)) { listOf(contentToReuse!!) } else { emptyList() } val runningToStop = ContainerUtil.concat(runningOfTheSameType, runningIncompatible) if (runningToStop.isNotEmpty()) { if (configuration != null) { if (runningOfTheSameType.isNotEmpty() && (runningOfTheSameType.size > 1 || contentToReuse == null || runningOfTheSameType.first() !== contentToReuse)) { val result = configuration.configuration.restartSingleton(environment) if (result == RestartSingletonResult.NO_FURTHER_ACTION) { return } if (result == RestartSingletonResult.ASK_AND_RESTART && !userApprovesStopForSameTypeConfigurations(environment.project, configuration.name, runningOfTheSameType.size)) { return } } if (runningIncompatible.isNotEmpty() && !userApprovesStopForIncompatibleConfigurations(project, configuration.name, runningIncompatible)) { return } } for (descriptor in runningToStop) { stopProcess(descriptor) } } if (awaitingRunProfiles[environment.runProfile] === environment) { // defense from rerunning exactly the same ExecutionEnvironment return } awaitingRunProfiles[environment.runProfile] = environment awaitTermination(object : Runnable { override fun run() { if (awaitingRunProfiles[environment.runProfile] !== environment) { // a new rerun has been requested before starting this one, ignore this rerun return } if ((configuration != null && !configuration.type.isDumbAware && DumbService.getInstance(project).isDumb) || inProgress.contains(InProgressEntry(environment.executor.id, environment.runner.runnerId))) { awaitTermination(this, 100) return } for (descriptor in runningOfTheSameType) { val processHandler = descriptor.processHandler if (processHandler != null && !processHandler.isProcessTerminated) { awaitTermination(this, 100) return } } awaitingRunProfiles.remove(environment.runProfile) // start() can be called during restartRunProfile() after pretty long 'awaitTermination()' so we have to check if the project is still here if (environment.project.isDisposed) { return } val settings = environment.runnerAndConfigurationSettings executeConfiguration(environment, settings != null && settings.isEditBeforeRun) } }, 50) } private class MyProcessHandler : ProcessHandler() { override fun destroyProcessImpl() {} override fun detachProcessImpl() {} override fun detachIsDefault(): Boolean { return false } override fun getProcessInput(): OutputStream? = null public override fun notifyProcessTerminated(exitCode: Int) { super.notifyProcessTerminated(exitCode) } } override fun executePreparationTasks(environment: ExecutionEnvironment, currentState: RunProfileState): Promise<Any?> { if (!(environment.runProfile is TargetEnvironmentAwareRunProfile)) { return resolvedPromise() } val targetEnvironmentAwareRunProfile = environment.runProfile as TargetEnvironmentAwareRunProfile if (!targetEnvironmentAwareRunProfile.needPrepareTarget()) { return resolvedPromise() } val processHandler = MyProcessHandler() val consoleView = TextConsoleBuilderFactory.getInstance().createBuilder(environment.project).console ProcessTerminatedListener.attach(processHandler) consoleView.attachToProcess(processHandler) val component = TargetPrepareComponent(consoleView) val buildContentManager = BuildContentManager.getInstance(environment.project) val contentName = targetEnvironmentAwareRunProfile.getEffectiveTargetName(environment.project)?.let { ExecutionBundle.message("tab.title.prepare.environment", it, environment.runProfile.name) } ?: ExecutionBundle.message("tab.title.prepare.target.environment", environment.runProfile.name) val toolWindow = buildContentManager.orCreateToolWindow val contentManager: ContentManager = toolWindow.contentManager val contentImpl = ContentImpl(component, contentName, true) contentImpl.putUserData(ToolWindow.SHOW_CONTENT_ICON, java.lang.Boolean.TRUE) contentImpl.icon = environment.runProfile.icon for (content in contentManager.contents) { if (contentName != content.displayName) continue if (content.isPinned) continue val contentComponent = content.component if (contentComponent !is TargetPrepareComponent) continue if (contentComponent.isPreparationFinished()) { contentManager.removeContent(content, true) } } contentManager.addContent(contentImpl) contentManager.setSelectedContent(contentImpl) toolWindow.activate(null) val promise = AsyncPromise<Any?>() ApplicationManager.getApplication().executeOnPooledThread { try { processHandler.startNotify() val targetProgressIndicator = object : TargetProgressIndicator { @Volatile var stopped = false override fun addText(text: @Nls String, key: Key<*>) { processHandler.notifyTextAvailable(text, key) } override fun isCanceled(): Boolean { return false } override fun stop() { stopped = true } override fun isStopped(): Boolean = stopped } promise.setResult(environment.prepareTargetEnvironment(currentState, targetProgressIndicator)) } catch (t: Throwable) { LOG.warn(t) promise.setError(ExecutionBundle.message("message.error.happened.0", t.localizedMessage)) processHandler.notifyTextAvailable(StringUtil.notNullize(t.localizedMessage), ProcessOutputType.STDERR) processHandler.notifyTextAvailable("\n", ProcessOutputType.STDERR) } finally { val exitCode = if (promise.isSucceeded) 0 else -1 processHandler.notifyProcessTerminated(exitCode) component.setPreparationFinished() } } return promise } @ApiStatus.Internal fun executeConfiguration(environment: ExecutionEnvironment, showSettings: Boolean, assignNewId: Boolean = true) { val runnerAndConfigurationSettings = environment.runnerAndConfigurationSettings val project = environment.project var runner = environment.runner if (runnerAndConfigurationSettings != null) { val targetManager = ExecutionTargetManager.getInstance(project) if (!targetManager.doCanRun(runnerAndConfigurationSettings.configuration, environment.executionTarget)) { ExecutionUtil.handleExecutionError(environment, ExecutionException(ProgramRunnerUtil.getCannotRunOnErrorMessage( environment.runProfile, environment.executionTarget))) processNotStarted(environment, null) return } if (!DumbService.isDumb(project)) { if (showSettings && runnerAndConfigurationSettings.isEditBeforeRun) { if (!RunDialog.editConfiguration(environment, ExecutionBundle.message("dialog.title.edit.configuration", 0))) { processNotStarted(environment, null) return } editConfigurationUntilSuccess(environment, assignNewId) } else { inProgress.add(InProgressEntry(environment.executor.id, environment.runner.runnerId)) ReadAction.nonBlocking(Callable { RunManagerImpl.canRunConfiguration(environment) }) .finishOnUiThread(ModalityState.NON_MODAL) { canRun -> inProgress.remove(InProgressEntry(environment.executor.id, environment.runner.runnerId)) if (canRun) { executeConfiguration(environment, environment.runner, assignNewId, this.project, environment.runnerAndConfigurationSettings) return@finishOnUiThread } if (!RunDialog.editConfiguration(environment, ExecutionBundle.message("dialog.title.edit.configuration", 0))) { processNotStarted(environment, null) return@finishOnUiThread } editConfigurationUntilSuccess(environment, assignNewId) } .expireWith(this) .submit(AppExecutorUtil.getAppExecutorService()) } return } } executeConfiguration(environment, runner, assignNewId, project, runnerAndConfigurationSettings) } private fun editConfigurationUntilSuccess(environment: ExecutionEnvironment, assignNewId: Boolean) { ReadAction.nonBlocking(Callable { RunManagerImpl.canRunConfiguration(environment) }) .finishOnUiThread(ModalityState.NON_MODAL) { canRun -> val runAnyway = if (!canRun) { val message = ExecutionBundle.message("dialog.message.configuration.still.incorrect.do.you.want.to.edit.it.again") val title = ExecutionBundle.message("dialog.title.change.configuration.settings") Messages.showYesNoDialog(project, message, title, CommonBundle.message("button.edit"), ExecutionBundle.message("run.continue.anyway"), Messages.getErrorIcon()) != Messages.YES } else true if (canRun || runAnyway) { val runner = ProgramRunner.getRunner(environment.executor.id, environment.runnerAndConfigurationSettings!!.configuration) if (runner == null) { ExecutionUtil.handleExecutionError(environment, ExecutionException(ExecutionBundle.message("dialog.message.cannot.find.runner.for", environment.runProfile.name))) } else { executeConfiguration(environment, runner, assignNewId, project, environment.runnerAndConfigurationSettings) } return@finishOnUiThread } if (!RunDialog.editConfiguration(environment, ExecutionBundle.message("dialog.title.edit.configuration", 0))) { processNotStarted(environment, null) return@finishOnUiThread } editConfigurationUntilSuccess(environment, assignNewId) } .expireWith(this) .submit(AppExecutorUtil.getAppExecutorService()) } private fun executeConfiguration(environment: ExecutionEnvironment, runner: @NotNull ProgramRunner<*>, assignNewId: Boolean, project: @NotNull Project, runnerAndConfigurationSettings: @Nullable RunnerAndConfigurationSettings?) { try { var effectiveEnvironment = environment if (runner != effectiveEnvironment.runner) { effectiveEnvironment = ExecutionEnvironmentBuilder(effectiveEnvironment).runner(runner).build() } if (assignNewId) { effectiveEnvironment.assignNewExecutionId() } runner.execute(effectiveEnvironment) } catch (e: ExecutionException) { ProgramRunnerUtil.handleExecutionError(project, environment, e, runnerAndConfigurationSettings?.configuration) } } override fun isStarting(executorId: String, runnerId: String): Boolean { return inProgress.contains(InProgressEntry(executorId, runnerId)) } private fun awaitTermination(request: Runnable, delayMillis: Long) { val app = ApplicationManager.getApplication() if (app.isUnitTestMode) { app.invokeLater(request, ModalityState.any()) } else { awaitingTerminationAlarm.addRequest(request, delayMillis) } } private fun getIncompatibleRunningDescriptors(configurationAndSettings: RunnerAndConfigurationSettings): List<RunContentDescriptor> { val configurationToCheckCompatibility = configurationAndSettings.configuration return getRunningDescriptors(Condition { runningConfigurationAndSettings -> val runningConfiguration = runningConfigurationAndSettings.configuration if (runningConfiguration is CompatibilityAwareRunProfile) { runningConfiguration.mustBeStoppedToRun(configurationToCheckCompatibility) } else { false } }) } fun getRunningDescriptors(condition: Condition<in RunnerAndConfigurationSettings>): List<RunContentDescriptor> { val result = SmartList<RunContentDescriptor>() for (entry in runningConfigurations) { if (entry.settings != null && condition.value(entry.settings)) { val processHandler = entry.descriptor.processHandler if (processHandler != null /*&& !processHandler.isProcessTerminating()*/ && !processHandler.isProcessTerminated) { result.add(entry.descriptor) } } } return result } fun getDescriptors(condition: Condition<in RunnerAndConfigurationSettings>): List<RunContentDescriptor> { val result = SmartList<RunContentDescriptor>() for (entry in runningConfigurations) { if (entry.settings != null && condition.value(entry.settings)) { result.add(entry.descriptor) } } return result } fun getExecutors(descriptor: RunContentDescriptor): Set<Executor> { val result = HashSet<Executor>() for (entry in runningConfigurations) { if (descriptor === entry.descriptor) { result.add(entry.executor) } } return result } fun getConfigurations(descriptor: RunContentDescriptor): Set<RunnerAndConfigurationSettings> { val result = HashSet<RunnerAndConfigurationSettings>() for (entry in runningConfigurations) { if (descriptor === entry.descriptor && entry.settings != null) { result.add(entry.settings) } } return result } } @ApiStatus.Internal fun RunnerAndConfigurationSettings.isOfSameType(runnerAndConfigurationSettings: RunnerAndConfigurationSettings): Boolean { if (this === runnerAndConfigurationSettings) return true val thisConfiguration = configuration val thatConfiguration = runnerAndConfigurationSettings.configuration if (thisConfiguration === thatConfiguration) return true if (thisConfiguration is UserDataHolder) { val originalRunProfile = DELEGATED_RUN_PROFILE_KEY[thisConfiguration] ?: return false if (originalRunProfile === thatConfiguration) return true if (thatConfiguration is UserDataHolder) return originalRunProfile === DELEGATED_RUN_PROFILE_KEY[thatConfiguration] } return false } private fun triggerUsage(environment: ExecutionEnvironment): StructuredIdeActivity? { val runConfiguration = environment.runnerAndConfigurationSettings?.configuration val configurationFactory = runConfiguration?.factory ?: return null return RunConfigurationUsageTriggerCollector.trigger(environment.project, configurationFactory, environment.executor, runConfiguration) } private fun createEnvironmentBuilder(project: Project, executor: Executor, configuration: RunnerAndConfigurationSettings?): ExecutionEnvironmentBuilder { val builder = ExecutionEnvironmentBuilder(project, executor) val runner = configuration?.let { ProgramRunner.getRunner(executor.id, it.configuration) } if (runner == null && configuration != null) { ExecutionManagerImpl.LOG.error("Cannot find runner for ${configuration.name}") } else if (runner != null) { builder.runnerAndSettings(runner, configuration) } return builder } private fun userApprovesStopForSameTypeConfigurations(project: Project, configName: String, instancesCount: Int): Boolean { val config = RunManagerImpl.getInstanceImpl(project).config if (!config.isRestartRequiresConfirmation) { return true } @Suppress("DuplicatedCode") val option = object : DialogWrapper.DoNotAskOption { override fun isToBeShown() = config.isRestartRequiresConfirmation override fun setToBeShown(value: Boolean, exitCode: Int) { config.isRestartRequiresConfirmation = value } override fun canBeHidden() = true override fun shouldSaveOptionsOnCancel() = false override fun getDoNotShowMessage(): String { return UIBundle.message("dialog.options.do.not.show") } } return Messages.showOkCancelDialog( project, ExecutionBundle.message("rerun.singleton.confirmation.message", configName, instancesCount), ExecutionBundle.message("process.is.running.dialog.title", configName), ExecutionBundle.message("rerun.confirmation.button.text"), CommonBundle.getCancelButtonText(), Messages.getQuestionIcon(), option) == Messages.OK } private fun userApprovesStopForIncompatibleConfigurations(project: Project, configName: String, runningIncompatibleDescriptors: List<RunContentDescriptor>): Boolean { @Suppress("DuplicatedCode") val config = RunManagerImpl.getInstanceImpl(project).config @Suppress("DuplicatedCode") if (!config.isStopIncompatibleRequiresConfirmation) { return true } @Suppress("DuplicatedCode") val option = object : DialogWrapper.DoNotAskOption { override fun isToBeShown() = config.isStopIncompatibleRequiresConfirmation override fun setToBeShown(value: Boolean, exitCode: Int) { config.isStopIncompatibleRequiresConfirmation = value } override fun canBeHidden() = true override fun shouldSaveOptionsOnCancel() = false override fun getDoNotShowMessage(): String { return UIBundle.message("dialog.options.do.not.show") } } val names = StringBuilder() for (descriptor in runningIncompatibleDescriptors) { val name = descriptor.displayName if (names.isNotEmpty()) { names.append(", ") } names.append(if (name.isNullOrEmpty()) ExecutionBundle.message("run.configuration.no.name") else String.format("'%s'", name)) } return Messages.showOkCancelDialog( project, ExecutionBundle.message("stop.incompatible.confirmation.message", configName, names.toString(), runningIncompatibleDescriptors.size), ExecutionBundle.message("incompatible.configuration.is.running.dialog.title", runningIncompatibleDescriptors.size), ExecutionBundle.message("stop.incompatible.confirmation.button.text"), CommonBundle.getCancelButtonText(), Messages.getQuestionIcon(), option) == Messages.OK } private class ProcessExecutionListener(private val project: Project, private val executorId: String, private val environment: ExecutionEnvironment, private val processHandler: ProcessHandler, private val descriptor: RunContentDescriptor, private val activity: StructuredIdeActivity?) : ProcessAdapter() { private val willTerminateNotified = AtomicBoolean() private val terminateNotified = AtomicBoolean() override fun processTerminated(event: ProcessEvent) { if (project.isDisposed || !terminateNotified.compareAndSet(false, true)) { return } ApplicationManager.getApplication().invokeLater(Runnable { val ui = descriptor.runnerLayoutUi if (ui != null && !ui.isDisposed) { ui.updateActionsNow() } }, ModalityState.any(), project.disposed) project.messageBus.syncPublisher(ExecutionManager.EXECUTION_TOPIC).processTerminated(executorId, environment, processHandler, event.exitCode) RunConfigurationUsageTriggerCollector.logProcessFinished(activity, RunConfigurationFinishType.UNKNOWN) processHandler.removeProcessListener(this) SaveAndSyncHandler.getInstance().scheduleRefresh() } override fun processWillTerminate(event: ProcessEvent, shouldNotBeUsed: Boolean) { if (project.isDisposed || !willTerminateNotified.compareAndSet(false, true)) { return } project.messageBus.syncPublisher(ExecutionManager.EXECUTION_TOPIC).processTerminating(executorId, environment, processHandler) } } private data class InProgressEntry(val executorId: String, val runnerId: String) private data class RunningConfigurationEntry(val descriptor: RunContentDescriptor, val settings: RunnerAndConfigurationSettings?, val executor: Executor) private class TargetPrepareComponent(val console: ConsoleView) : JPanel(BorderLayout()), Disposable { init { add(console.component, BorderLayout.CENTER) } @Volatile private var finished = false fun isPreparationFinished() = finished fun setPreparationFinished() { finished = true } override fun dispose() { Disposer.dispose(console) } }
apache-2.0
2d6d4e39be05df84fba9511dca811608
39.614995
185
0.705034
5.822222
false
true
false
false
TeamNewPipe/NewPipe
app/src/main/java/org/schabi/newpipe/local/feed/FeedDatabaseManager.kt
1
7044
package org.schabi.newpipe.local.feed import android.content.Context import android.util.Log import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.core.Completable import io.reactivex.rxjava3.core.Flowable import io.reactivex.rxjava3.core.Maybe import io.reactivex.rxjava3.schedulers.Schedulers import org.schabi.newpipe.MainActivity.DEBUG import org.schabi.newpipe.NewPipeDatabase import org.schabi.newpipe.database.feed.model.FeedEntity import org.schabi.newpipe.database.feed.model.FeedGroupEntity import org.schabi.newpipe.database.feed.model.FeedLastUpdatedEntity import org.schabi.newpipe.database.stream.StreamWithState import org.schabi.newpipe.database.stream.model.StreamEntity import org.schabi.newpipe.database.subscription.NotificationMode import org.schabi.newpipe.extractor.stream.StreamInfoItem import org.schabi.newpipe.extractor.stream.StreamType import org.schabi.newpipe.local.subscription.FeedGroupIcon import java.time.LocalDate import java.time.OffsetDateTime import java.time.ZoneOffset class FeedDatabaseManager(context: Context) { private val database = NewPipeDatabase.getInstance(context) private val feedTable = database.feedDAO() private val feedGroupTable = database.feedGroupDAO() private val streamTable = database.streamDAO() companion object { /** * Only items that are newer than this will be saved. */ val FEED_OLDEST_ALLOWED_DATE: OffsetDateTime = LocalDate.now().minusWeeks(13) .atStartOfDay().atOffset(ZoneOffset.UTC) } fun groups() = feedGroupTable.getAll() fun database() = database fun getStreams( groupId: Long, includePlayedStreams: Boolean, includeFutureStreams: Boolean ): Maybe<List<StreamWithState>> { return feedTable.getStreams( groupId, includePlayedStreams, if (includeFutureStreams) null else OffsetDateTime.now() ) } fun outdatedSubscriptions(outdatedThreshold: OffsetDateTime) = feedTable.getAllOutdated(outdatedThreshold) fun outdatedSubscriptionsWithNotificationMode( outdatedThreshold: OffsetDateTime, @NotificationMode notificationMode: Int ) = feedTable.getOutdatedWithNotificationMode(outdatedThreshold, notificationMode) fun notLoadedCount(groupId: Long = FeedGroupEntity.GROUP_ALL_ID): Flowable<Long> { return when (groupId) { FeedGroupEntity.GROUP_ALL_ID -> feedTable.notLoadedCount() else -> feedTable.notLoadedCountForGroup(groupId) } } fun outdatedSubscriptionsForGroup( groupId: Long = FeedGroupEntity.GROUP_ALL_ID, outdatedThreshold: OffsetDateTime ) = feedTable.getAllOutdatedForGroup(groupId, outdatedThreshold) fun markAsOutdated(subscriptionId: Long) = feedTable .setLastUpdatedForSubscription(FeedLastUpdatedEntity(subscriptionId, null)) fun doesStreamExist(stream: StreamInfoItem): Boolean { return streamTable.exists(stream.serviceId, stream.url) } fun upsertAll( subscriptionId: Long, items: List<StreamInfoItem>, oldestAllowedDate: OffsetDateTime = FEED_OLDEST_ALLOWED_DATE ) { val itemsToInsert = ArrayList<StreamInfoItem>() loop@ for (streamItem in items) { val uploadDate = streamItem.uploadDate itemsToInsert += when { uploadDate == null && streamItem.streamType == StreamType.LIVE_STREAM -> streamItem uploadDate != null && uploadDate.offsetDateTime() >= oldestAllowedDate -> streamItem else -> continue@loop } } feedTable.unlinkOldLivestreams(subscriptionId) if (itemsToInsert.isNotEmpty()) { val streamEntities = itemsToInsert.map { StreamEntity(it) } val streamIds = streamTable.upsertAll(streamEntities) val feedEntities = streamIds.map { FeedEntity(it, subscriptionId) } feedTable.insertAll(feedEntities) } feedTable.setLastUpdatedForSubscription( FeedLastUpdatedEntity(subscriptionId, OffsetDateTime.now(ZoneOffset.UTC)) ) } fun removeOrphansOrOlderStreams(oldestAllowedDate: OffsetDateTime = FEED_OLDEST_ALLOWED_DATE) { feedTable.unlinkStreamsOlderThan(oldestAllowedDate) streamTable.deleteOrphans() } fun clear() { feedTable.deleteAll() val deletedOrphans = streamTable.deleteOrphans() if (DEBUG) { Log.d( this::class.java.simpleName, "clear() → streamTable.deleteOrphans() → $deletedOrphans" ) } } // ///////////////////////////////////////////////////////////////////////// // Feed Groups // ///////////////////////////////////////////////////////////////////////// fun subscriptionIdsForGroup(groupId: Long): Flowable<List<Long>> { return feedGroupTable.getSubscriptionIdsFor(groupId) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } fun updateSubscriptionsForGroup(groupId: Long, subscriptionIds: List<Long>): Completable { return Completable .fromCallable { feedGroupTable.updateSubscriptionsForGroup(groupId, subscriptionIds) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } fun createGroup(name: String, icon: FeedGroupIcon): Maybe<Long> { return Maybe.fromCallable { feedGroupTable.insert(FeedGroupEntity(0, name, icon)) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } fun getGroup(groupId: Long): Maybe<FeedGroupEntity> { return feedGroupTable.getGroup(groupId) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } fun updateGroup(feedGroupEntity: FeedGroupEntity): Completable { return Completable.fromCallable { feedGroupTable.update(feedGroupEntity) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } fun deleteGroup(groupId: Long): Completable { return Completable.fromCallable { feedGroupTable.delete(groupId) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } fun updateGroupsOrder(groupIdList: List<Long>): Completable { var index = 0L val orderMap = groupIdList.associateBy({ it }, { index++ }) return Completable.fromCallable { feedGroupTable.updateOrder(orderMap) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } fun oldestSubscriptionUpdate(groupId: Long): Flowable<List<OffsetDateTime>> { return when (groupId) { FeedGroupEntity.GROUP_ALL_ID -> feedTable.oldestSubscriptionUpdateFromAll() else -> feedTable.oldestSubscriptionUpdate(groupId) } } }
gpl-3.0
523a06437edbe013888135e51f439b25
37.26087
110
0.679403
4.868603
false
false
false
false
jwren/intellij-community
platform/lang-impl/src/com/intellij/util/indexing/diagnostic/IndexDiagnosticDumper.kt
1
11250
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.util.indexing.diagnostic import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.fasterxml.jackson.module.kotlin.registerKotlinModule import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.ControlFlowException import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.getProjectCachePath import com.intellij.openapi.util.io.FileUtil import com.intellij.util.SystemProperties import com.intellij.util.concurrency.NonUrgentExecutor import com.intellij.util.indexing.diagnostic.dto.* import com.intellij.util.indexing.diagnostic.presentation.createAggregateHtml import com.intellij.util.indexing.diagnostic.presentation.generateHtml import com.intellij.util.io.* import org.jetbrains.annotations.TestOnly import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.time.LocalDateTime import java.time.format.DateTimeFormatter import java.util.concurrent.TimeUnit import kotlin.io.path.bufferedReader import kotlin.io.path.extension import kotlin.io.path.nameWithoutExtension import kotlin.streams.asSequence class IndexDiagnosticDumper : Disposable { companion object { @JvmStatic fun getInstance(): IndexDiagnosticDumper = service() val diagnosticTimestampFormat: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss.SSS") private const val fileNamePrefix = "diagnostic-" @JvmStatic val projectIndexingHistoryListenerEpName = ExtensionPointName.create<ProjectIndexingHistoryListener>("com.intellij.projectIndexingHistoryListener") @JvmStatic private val shouldDumpDiagnosticsForInterruptedUpdaters: Boolean get() = SystemProperties.getBooleanProperty("intellij.indexes.diagnostics.should.dump.for.interrupted.index.updaters", false) @JvmStatic private val indexingDiagnosticsLimitOfFiles: Int get() = SystemProperties.getIntProperty("intellij.indexes.diagnostics.limit.of.files", 300) @JvmStatic val shouldDumpPathsOfIndexedFiles: Boolean get() = SystemProperties.getBooleanProperty("intellij.indexes.diagnostics.should.dump.paths.of.indexed.files", false) @JvmStatic val shouldDumpProviderRootPaths: Boolean get() = SystemProperties.getBooleanProperty("intellij.indexes.diagnostics.should.dump.provider.root.paths", false) /** * Some processes may be done in multiple threads, like content loading, * see [com.intellij.util.indexing.contentQueue.IndexUpdateRunner.doIndexFiles] * Such processes have InAllThreads time and visible time, see [com.intellij.util.indexing.contentQueue.IndexUpdateRunner.indexFiles], * [ProjectIndexingHistoryImpl.visibleTimeToAllThreadsTimeRatio], [IndexingFileSetStatistics] * * This property allows to provide more details on those times and ratio in html */ @JvmStatic val shouldProvideVisibleAndAllThreadsTimeInfo: Boolean get() = SystemProperties.getBooleanProperty("intellij.indexes.diagnostics.should.provide.visible.and.all.threads.time.info", false) @JvmStatic @TestOnly var shouldDumpInUnitTestMode: Boolean = false private val LOG = Logger.getInstance(IndexDiagnosticDumper::class.java) val jacksonMapper: ObjectMapper by lazy { jacksonObjectMapper().registerKotlinModule() } fun readJsonIndexDiagnostic(file: Path): JsonIndexDiagnostic = jacksonMapper.readValue(file.toFile(), JsonIndexDiagnostic::class.java) fun clearDiagnostic() { if (indexingDiagnosticDir.exists()) { indexingDiagnosticDir.directoryStreamIfExists { dirStream -> dirStream.forEach { FileUtil.deleteWithRenaming(it) } } } } val indexingDiagnosticDir: Path by lazy { val logPath = PathManager.getLogPath() Paths.get(logPath).resolve("indexing-diagnostic") } fun getProjectDiagnosticDirectory(project: Project): Path { val directory = project.getProjectCachePath(indexingDiagnosticDir) directory.createDirectories() return directory } } private var isDisposed = false fun onIndexingStarted(projectIndexingHistory: ProjectIndexingHistoryImpl) { runAllListenersSafely { onStartedIndexing(projectIndexingHistory) } } fun onIndexingFinished(projectIndexingHistory: ProjectIndexingHistoryImpl) { try { if (ApplicationManager.getApplication().isUnitTestMode && !shouldDumpInUnitTestMode) { return } if (projectIndexingHistory.times.wasInterrupted && !shouldDumpDiagnosticsForInterruptedUpdaters) { return } projectIndexingHistory.indexingFinished() NonUrgentExecutor.getInstance().execute { dumpProjectIndexingHistoryToLogSubdirectory(projectIndexingHistory) } } finally { runAllListenersSafely { onFinishedIndexing(projectIndexingHistory) } } } private fun runAllListenersSafely(block: ProjectIndexingHistoryListener.() -> Unit) { val listeners = ProgressManager.getInstance().computeInNonCancelableSection<List<ProjectIndexingHistoryListener>, Exception> { projectIndexingHistoryListenerEpName.extensionList } for (listener in listeners) { try { listener.block() } catch (e: Exception) { if (e is ControlFlowException) { // Make all listeners run first. continue } LOG.error(e) } } } @Synchronized private fun dumpProjectIndexingHistoryToLogSubdirectory(projectIndexingHistory: ProjectIndexingHistoryImpl) { try { check(!isDisposed) val indexDiagnosticDirectory = getProjectDiagnosticDirectory(projectIndexingHistory.project) val (diagnosticJson: Path, diagnosticHtml: Path) = getFilesForNewJsonAndHtmlDiagnostics(indexDiagnosticDirectory) val jsonIndexDiagnostic = JsonIndexDiagnostic.generateForHistory(projectIndexingHistory) jacksonMapper.writerWithDefaultPrettyPrinter().writeValue(diagnosticJson.toFile(), jsonIndexDiagnostic) diagnosticHtml.write(jsonIndexDiagnostic.generateHtml()) val existingDiagnostics = parseExistingDiagnostics(indexDiagnosticDirectory) val survivedDiagnostics = deleteOutdatedDiagnostics(existingDiagnostics) val sharedIndexEvents = SharedIndexDiagnostic.readEvents(projectIndexingHistory.project) val changedFilesPushedEvents = ChangedFilesPushedDiagnostic.readEvents(projectIndexingHistory.project) indexDiagnosticDirectory.resolve("report.html").write( createAggregateHtml(projectIndexingHistory.project.name, survivedDiagnostics, sharedIndexEvents, changedFilesPushedEvents) ) } catch (e: Exception) { LOG.warn("Failed to dump index diagnostic", e) } } private fun getFilesForNewJsonAndHtmlDiagnostics(indexDiagnosticDirectory: Path): Pair<Path, Path> { var diagnosticJson: Path var diagnosticHtml: Path var nowTime = LocalDateTime.now() while (true) { val timestamp = nowTime.format(diagnosticTimestampFormat) diagnosticJson = indexDiagnosticDirectory.resolve("$fileNamePrefix$timestamp.json") diagnosticHtml = indexDiagnosticDirectory.resolve("$fileNamePrefix$timestamp.html") if (!diagnosticJson.exists() && !diagnosticHtml.exists()) { break } nowTime = nowTime.plusNanos(TimeUnit.MILLISECONDS.toNanos(1)) } return diagnosticJson to diagnosticHtml } private fun <T> fastReadJsonField(jsonFile: Path, propertyName: String, type: Class<T>): T? { try { jsonFile.bufferedReader().use { reader -> jacksonMapper.factory.createParser(reader).use { parser -> while (parser.nextToken() != null) { val property = parser.currentName if (property == propertyName) { parser.nextToken() return jacksonMapper.readValue(parser, type) } } } } } catch (e: Exception) { LOG.debug("Failed to parse project indexing time", e) } return null } private fun fastReadIndexingHistoryTimes(jsonFile: Path): JsonProjectIndexingHistoryTimes? = fastReadJsonField(jsonFile, "times", JsonProjectIndexingHistoryTimes::class.java) private fun fastReadFileCount(jsonFile: Path): JsonProjectIndexingFileCount? = fastReadJsonField(jsonFile, "fileCount", JsonProjectIndexingFileCount::class.java) private fun fastReadAppInfo(jsonFile: Path): JsonIndexDiagnosticAppInfo? = fastReadJsonField(jsonFile, "appInfo", JsonIndexDiagnosticAppInfo::class.java) private fun fastReadRuntimeInfo(jsonFile: Path): JsonRuntimeInfo? = fastReadJsonField(jsonFile, "runtimeInfo", JsonRuntimeInfo::class.java) private fun deleteOutdatedDiagnostics(existingDiagnostics: List<ExistingDiagnostic>): List<ExistingDiagnostic> { val sortedDiagnostics = existingDiagnostics.sortedByDescending { it.indexingTimes.updatingStart.instant } val survivedDiagnostics = sortedDiagnostics.take(indexingDiagnosticsLimitOfFiles) val outdatedDiagnostics = sortedDiagnostics.drop(indexingDiagnosticsLimitOfFiles) for (diagnostic in outdatedDiagnostics) { diagnostic.jsonFile.delete() diagnostic.htmlFile.delete() } return survivedDiagnostics } private fun parseExistingDiagnostics(indexDiagnosticDirectory: Path): List<ExistingDiagnostic> = Files.list(indexDiagnosticDirectory).use { files -> files.asSequence() .filter { file -> file.fileName.toString().startsWith(fileNamePrefix) && file.extension == "json" } .mapNotNull { jsonFile -> val times = fastReadIndexingHistoryTimes(jsonFile) ?: return@mapNotNull null val appInfo = fastReadAppInfo(jsonFile) ?: return@mapNotNull null val runtimeInfo = fastReadRuntimeInfo(jsonFile) ?: return@mapNotNull null val fileCount = fastReadFileCount(jsonFile) val htmlFile = jsonFile.resolveSibling(jsonFile.nameWithoutExtension + ".html") if (!htmlFile.exists()) { return@mapNotNull null } ExistingDiagnostic(jsonFile, htmlFile, times, appInfo, runtimeInfo, fileCount) } .toList() } data class ExistingDiagnostic( val jsonFile: Path, val htmlFile: Path, val indexingTimes: JsonProjectIndexingHistoryTimes, val appInfo: JsonIndexDiagnosticAppInfo, val runtimeInfo: JsonRuntimeInfo, // May be not available in existing local reports. After some time // (when all local reports are likely to expire) this field can be made non-null. val fileCount: JsonProjectIndexingFileCount? ) @Synchronized override fun dispose() { // The synchronized block allows to wait for unfinished background dumpers. isDisposed = true } }
apache-2.0
cd1a18962441ca3e468a5e20ffb43542
39.617329
151
0.752711
4.984493
false
false
false
false
hellenxu/TipsProject
DroidDailyProject/app/src/main/java/six/ca/droiddailyproject/sms/SmsBroadcastReceiver.kt
1
1368
package six.ca.droiddailyproject.sms import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import com.google.android.gms.auth.api.phone.SmsRetriever import com.google.android.gms.common.api.CommonStatusCodes import com.google.android.gms.common.api.Status /** * @author hellenxu * @date 2021-04-29 * Copyright 2021 Six. All rights reserved. */ class SmsBroadcastReceiver: BroadcastReceiver() { private val otpReg = Regex("[0-9]{6}") override fun onReceive(context: Context?, intent: Intent?) { println("xxl-onReceive: $intent") if (SmsRetriever.SMS_RETRIEVED_ACTION == intent?.action) { val extras = intent.extras val statusCode = extras?.get(SmsRetriever.EXTRA_STATUS) as? Status println("xxl-onReceive: $statusCode") when (statusCode?.statusCode) { CommonStatusCodes.SUCCESS -> { val msg = extras.getString(SmsRetriever.EXTRA_SMS_MESSAGE) ?: "" val code = otpReg.find(msg, 0)?.value println("xxl-onReceive: msg = $msg; code = $code") println("xxl-onReceive: code = $code") } CommonStatusCodes.TIMEOUT -> { println("xxl-onReceive-timeout") } } } } }
apache-2.0
5ba7ccc55639089c7a72e623b7c24537
33.225
84
0.611842
4.315457
false
false
false
false
siosio/intellij-community
plugins/ide-features-trainer/src/training/ui/LessonMessagePane.kt
1
22879
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package training.ui import com.intellij.icons.AllIcons import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.colors.FontPreferences import com.intellij.openapi.util.SystemInfo import com.intellij.ui.scale.JBUIScale import com.intellij.util.ui.GraphicsUtil import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import training.FeaturesTrainerIcons import training.learn.lesson.LessonManager import java.awt.* import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import java.awt.font.GlyphVector import java.awt.geom.Point2D import java.awt.geom.Rectangle2D import java.awt.geom.RoundRectangle2D import javax.swing.Icon import javax.swing.JTextPane import javax.swing.text.AttributeSet import javax.swing.text.BadLocationException import javax.swing.text.SimpleAttributeSet import javax.swing.text.StyleConstants import kotlin.math.roundToInt internal class LessonMessagePane(private val panelMode: Boolean = true) : JTextPane() { //Style Attributes for LessonMessagePane(JTextPane) private val INACTIVE = SimpleAttributeSet() private val REGULAR = SimpleAttributeSet() private val BOLD = SimpleAttributeSet() private val SHORTCUT = SimpleAttributeSet() private val ROBOTO = SimpleAttributeSet() private val CODE = SimpleAttributeSet() private val LINK = SimpleAttributeSet() private var codeFontSize = UISettings.instance.fontSize.toInt() private val TASK_PARAGRAPH_STYLE = SimpleAttributeSet() private val INTERNAL_PARAGRAPH_STYLE = SimpleAttributeSet() private val BALLOON_STYLE = SimpleAttributeSet() private val textColor: Color = if (panelMode) UISettings.instance.defaultTextColor else UISettings.instance.tooltipTextColor private val codeForegroundColor: Color = if (panelMode) UISettings.instance.codeForegroundColor else UISettings.instance.tooltipTextColor enum class MessageState { NORMAL, PASSED, INACTIVE, RESTORE, INFORMER } data class MessageProperties(val state: MessageState = MessageState.NORMAL, val visualIndex: Int? = null, val useInternalParagraphStyle: Boolean = false) private data class LessonMessage( val messageParts: List<MessagePart>, var state: MessageState, val visualIndex: Int?, val useInternalParagraphStyle: Boolean, var start: Int = 0, var end: Int = 0 ) private data class RangeData(var range: IntRange, val action: (Point, Int) -> Unit) private val activeMessages = mutableListOf<LessonMessage>() private val restoreMessages = mutableListOf<LessonMessage>() private val inactiveMessages = mutableListOf<LessonMessage>() private val fontFamily: String get() = UIUtil.getLabelFont().fontName private val ranges = mutableSetOf<RangeData>() private var insertOffset: Int = 0 private var paragraphStyle = SimpleAttributeSet() private fun allLessonMessages() = activeMessages + restoreMessages + inactiveMessages var currentAnimation = 0 var totalAnimation = 0 //, fontFace, check_width + check_right_indent init { UIUtil.doNotScrollToCaret(this) initStyleConstants() isEditable = false val listener = object : MouseAdapter() { override fun mouseClicked(me: MouseEvent) { val rangeData = getRangeDataForMouse(me) ?: return val middle = (rangeData.range.first + rangeData.range.last) / 2 val rectangle = modelToView2D(middle) rangeData.action(Point(rectangle.x.roundToInt(), (rectangle.y.roundToInt() + rectangle.height.roundToInt() / 2)), rectangle.height.roundToInt()) } override fun mouseMoved(me: MouseEvent) { val rangeData = getRangeDataForMouse(me) cursor = if (rangeData == null) { Cursor.getDefaultCursor() } else { Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) } } } addMouseListener(listener) addMouseMotionListener(listener) } private fun getRangeDataForMouse(me: MouseEvent): RangeData? { val offset = viewToModel2D(Point2D.Double(me.x.toDouble(), me.y.toDouble())) val result = ranges.find { offset in it.range } ?: return null if (offset < 0 || offset >= document.length) return null for (i in result.range) { val rectangle = modelToView2D(i) if (me.x >= rectangle.x && me.y >= rectangle.y && me.y <= rectangle.y + rectangle.height) { return result } } return null } override fun addNotify() { super.addNotify() initStyleConstants() redrawMessages() } override fun updateUI() { super.updateUI() ApplicationManager.getApplication().invokeLater(Runnable { initStyleConstants() redrawMessages() }) } private fun initStyleConstants() { val fontSize = UISettings.instance.fontSize.toInt() StyleConstants.setForeground(INACTIVE, UISettings.instance.inactiveColor) StyleConstants.setFontFamily(REGULAR, fontFamily) StyleConstants.setFontSize(REGULAR, fontSize) StyleConstants.setFontFamily(BOLD, fontFamily) StyleConstants.setFontSize(BOLD, fontSize) StyleConstants.setBold(BOLD, true) StyleConstants.setFontFamily(SHORTCUT, fontFamily) StyleConstants.setFontSize(SHORTCUT, fontSize) StyleConstants.setBold(SHORTCUT, true) EditorColorsManager.getInstance().globalScheme.editorFontName StyleConstants.setFontFamily(CODE, EditorColorsManager.getInstance().globalScheme.editorFontName) StyleConstants.setFontSize(CODE, codeFontSize) StyleConstants.setFontFamily(LINK, fontFamily) StyleConstants.setFontSize(LINK, fontSize) StyleConstants.setLeftIndent(TASK_PARAGRAPH_STYLE, UISettings.instance.checkIndent.toFloat()) StyleConstants.setRightIndent(TASK_PARAGRAPH_STYLE, 0f) StyleConstants.setSpaceAbove(TASK_PARAGRAPH_STYLE, 24.0f) StyleConstants.setSpaceBelow(TASK_PARAGRAPH_STYLE, 0.0f) StyleConstants.setLineSpacing(TASK_PARAGRAPH_STYLE, 0.2f) StyleConstants.setLeftIndent(INTERNAL_PARAGRAPH_STYLE, UISettings.instance.checkIndent.toFloat()) StyleConstants.setRightIndent(INTERNAL_PARAGRAPH_STYLE, 0f) StyleConstants.setSpaceAbove(INTERNAL_PARAGRAPH_STYLE, 8.0f) StyleConstants.setSpaceBelow(INTERNAL_PARAGRAPH_STYLE, 0.0f) StyleConstants.setLineSpacing(INTERNAL_PARAGRAPH_STYLE, 0.2f) StyleConstants.setLineSpacing(BALLOON_STYLE, 0.2f) StyleConstants.setLeftIndent(BALLOON_STYLE, UISettings.instance.balloonIndent.toFloat()) StyleConstants.setForeground(REGULAR, textColor) StyleConstants.setForeground(BOLD, textColor) StyleConstants.setForeground(SHORTCUT, UISettings.instance.shortcutTextColor) StyleConstants.setForeground(LINK, UISettings.instance.lessonLinkColor) StyleConstants.setForeground(CODE, codeForegroundColor) } fun messagesNumber(): Int = activeMessages.size @Suppress("SameParameterValue") private fun removeMessagesRange(startIdx: Int, endIdx: Int, list: MutableList<LessonMessage>) { if (startIdx == endIdx) return list.subList(startIdx, endIdx).clear() } fun clearRestoreMessages(): () -> Rectangle? { removeMessagesRange(0, restoreMessages.size, restoreMessages) redrawMessages() val lastOrNull = activeMessages.lastOrNull() return { lastOrNull?.let { getRectangleToScroll(it) } } } fun removeInactiveMessages(number: Int) { removeMessagesRange(0, number, inactiveMessages) redrawMessages() } fun resetMessagesNumber(number: Int): () -> Rectangle? { val move = activeMessages.subList(number, activeMessages.size) move.forEach { it.state = MessageState.INACTIVE } inactiveMessages.addAll(0, move) move.clear() return clearRestoreMessages() } fun getCurrentMessageRectangle(): Rectangle? { val lessonMessage = restoreMessages.lastOrNull() ?: activeMessages.lastOrNull() ?: return null return getRectangleToScroll(lessonMessage) } private fun insertText(text: String, attributeSet: AttributeSet) { document.insertString(insertOffset, text, attributeSet) styledDocument.setParagraphAttributes(insertOffset, text.length - 1, paragraphStyle, true) insertOffset += text.length } fun addMessage(messageParts: List<MessagePart>, properties: MessageProperties = MessageProperties()): () -> Rectangle? { val lessonMessage = LessonMessage(messageParts, properties.state, properties.visualIndex, properties.useInternalParagraphStyle) when (properties.state) { MessageState.INACTIVE -> inactiveMessages MessageState.RESTORE -> restoreMessages else -> activeMessages }.add(lessonMessage) redrawMessages() return { getRectangleToScroll(lessonMessage) } } fun removeMessage(index: Int) { activeMessages.removeAt(index) } private fun getRectangleToScroll(lessonMessage: LessonMessage): Rectangle? { val startRect = modelToView2D(lessonMessage.start + 1)?.toRectangle() ?: return null val endRect = modelToView2D(lessonMessage.end - 1)?.toRectangle() ?: return null return Rectangle(startRect.x, startRect.y - activeTaskInset, endRect.x + endRect.width - startRect.x, endRect.y + endRect.height - startRect.y + activeTaskInset * 2) } fun redrawMessages() { initStyleConstants() ranges.clear() text = "" insertOffset = 0 var previous: LessonMessage? = null for (lessonMessage in allLessonMessages()) { paragraphStyle = when { previous?.useInternalParagraphStyle == true -> INTERNAL_PARAGRAPH_STYLE panelMode -> TASK_PARAGRAPH_STYLE else -> BALLOON_STYLE } val messageParts: List<MessagePart> = lessonMessage.messageParts lessonMessage.start = insertOffset if (insertOffset != 0) insertText("\n", paragraphStyle) for (part in messageParts) { val startOffset = insertOffset part.startOffset = startOffset when (part.type) { MessagePart.MessageType.TEXT_REGULAR -> insertText(part.text, REGULAR) MessagePart.MessageType.TEXT_BOLD -> insertText(part.text, BOLD) MessagePart.MessageType.SHORTCUT -> appendShortcut(part)?.let { ranges.add(it) } MessagePart.MessageType.CODE -> insertText(part.text, CODE) MessagePart.MessageType.CHECK -> insertText(part.text, ROBOTO) MessagePart.MessageType.LINK -> appendLink(part)?.let { ranges.add(it) } MessagePart.MessageType.ICON_IDX -> LearningUiManager.iconMap[part.text]?.let { addPlaceholderForIcon(it) } MessagePart.MessageType.PROPOSE_RESTORE -> insertText(part.text, BOLD) MessagePart.MessageType.LINE_BREAK -> { insertText("\n", REGULAR) paragraphStyle = INTERNAL_PARAGRAPH_STYLE } } part.endOffset = insertOffset } lessonMessage.end = insertOffset if (lessonMessage.state == MessageState.INACTIVE) { setInactiveStyle(lessonMessage) } previous = lessonMessage } } private fun addPlaceholderForIcon(icon: Icon) { var placeholder = " " while (this.getFontMetrics(this.font).stringWidth(placeholder) <= icon.iconWidth) { placeholder += " " } placeholder += " " insertText(placeholder, REGULAR) } fun passPreviousMessages() { for (message in activeMessages) { message.state = MessageState.PASSED } redrawMessages() } private fun setInactiveStyle(lessonMessage: LessonMessage) { styledDocument.setCharacterAttributes(lessonMessage.start, lessonMessage.end, INACTIVE, false) } fun clear() { text = "" activeMessages.clear() restoreMessages.clear() inactiveMessages.clear() ranges.clear() } /** * Appends link inside JTextPane to Run another lesson * @param messagePart - should have LINK type. message.runnable starts when the message has been clicked. */ @Throws(BadLocationException::class) private fun appendLink(messagePart: MessagePart): RangeData? { val clickRange = appendClickableRange(messagePart.text, LINK) val runnable = messagePart.runnable ?: return null return RangeData(clickRange) { _, _ -> runnable.run() } } private fun appendShortcut(messagePart: MessagePart): RangeData? { val range = appendClickableRange(messagePart.text, SHORTCUT) val actionId = messagePart.link ?: return null val clickRange = IntRange(range.first + 1, range.last - 1) // exclude around spaces return RangeData(clickRange) { p, h -> showShortcutBalloon(p, h, actionId) } } private fun showShortcutBalloon(point: Point2D, height: Int, actionName: String?) { if (actionName == null) return showActionKeyPopup(this, point.toPoint(), height, actionName) } private fun appendClickableRange(clickable: String, attributeSet: SimpleAttributeSet): IntRange { val startLink = insertOffset insertText(clickable, attributeSet) val endLink = insertOffset return startLink..endLink } override fun paintComponent(g: Graphics) { adjustCodeFontSize(g) try { paintMessages(g) } catch (e: BadLocationException) { LOG.warn(e) } super.paintComponent(g) paintLessonCheckmarks(g) drawTaskNumbers(g) } private fun adjustCodeFontSize(g: Graphics) { val fontSize = StyleConstants.getFontSize(CODE) val labelFont = UISettings.instance.plainFont val (numberFont, _, _) = getNumbersFont(labelFont, g) if (numberFont.size != fontSize) { StyleConstants.setFontSize(CODE, numberFont.size) codeFontSize = numberFont.size redrawMessages() } } private fun paintLessonCheckmarks(g: Graphics) { val plainFont = UISettings.instance.plainFont val fontMetrics = g.getFontMetrics(plainFont) val height = if (g is Graphics2D) letterHeight(plainFont, g, "A") else fontMetrics.height val baseLineOffset = fontMetrics.ascent + fontMetrics.leading for (lessonMessage in allLessonMessages()) { var startOffset = lessonMessage.start if (startOffset != 0) startOffset++ val rectangle = modelToView2D(startOffset).toRectangle() val icon = if (lessonMessage.state == MessageState.PASSED) { FeaturesTrainerIcons.Img.GreenCheckmark } else if (!LessonManager.instance.lessonIsRunning()) { AllIcons.General.Information } else continue val xShift = icon.iconWidth + UISettings.instance.numberTaskIndent val y = rectangle.y + baseLineOffset - (height + icon.iconHeight + 1) / 2 icon.paintIcon(this, g, rectangle.x - xShift, y) } } private data class FontSearchResult(val numberFont: Font, val numberHeight: Int, val textLetterHeight: Int) private fun drawTaskNumbers(g: Graphics) { val oldFont = g.font val labelFont = UISettings.instance.plainFont val (numberFont, numberHeight, textLetterHeight) = getNumbersFont(labelFont, g) val textFontMetrics = g.getFontMetrics(labelFont) val baseLineOffset = textFontMetrics.ascent + textFontMetrics.leading g.font = numberFont fun paintNumber(lessonMessage: LessonMessage, color: Color) { var startOffset = lessonMessage.start if (startOffset != 0) startOffset++ val s = lessonMessage.visualIndex?.toString()?.padStart(2, '0') ?: return val width = textFontMetrics.stringWidth(s) val modelToView2D = modelToView2D(startOffset) val rectangle = modelToView2D.toRectangle() val xOffset = rectangle.x - (width + UISettings.instance.numberTaskIndent) val baseLineY = rectangle.y + baseLineOffset val yOffset = baseLineY + (numberHeight - textLetterHeight) val backupColor = g.color g.color = color GraphicsUtil.setupAAPainting(g) g.drawString(s, xOffset, yOffset) g.color = backupColor } for (lessonMessage in inactiveMessages) { paintNumber(lessonMessage, UISettings.instance.futureTaskNumberColor) } if (activeMessages.lastOrNull()?.state != MessageState.PASSED || !panelMode) { // lesson can be opened as passed val firstActiveMessage = firstActiveMessage() if (firstActiveMessage != null) { val color = if (panelMode) UISettings.instance.activeTaskNumberColor else UISettings.instance.tooltipTaskNumberColor paintNumber(firstActiveMessage, color) } } g.font = oldFont } private fun getNumbersFont(textFont: Font, g: Graphics): FontSearchResult { val style = Font.PLAIN val monoFontName = FontPreferences.DEFAULT_FONT_NAME if (g is Graphics2D) { val textHeight = letterHeight(textFont, g, "A") var size = textFont.size var numberHeight = 0 lateinit var numberFont: Font fun calculateHeight(): Int { numberFont = Font(monoFontName, style, size) numberHeight = letterHeight(numberFont, g, "0") return numberHeight } calculateHeight() if (numberHeight > textHeight) { size-- while (calculateHeight() >= textHeight) { size-- } size++ calculateHeight() } else if (numberHeight < textHeight) { size++ while (calculateHeight() < textHeight) { size++ } } return FontSearchResult(numberFont, numberHeight, textHeight) } return FontSearchResult(Font(monoFontName, style, textFont.size), 0, 0) } private fun letterHeight(font: Font, g: Graphics2D, str: String): Int { val gv: GlyphVector = font.createGlyphVector(g.fontRenderContext, str) return gv.getGlyphMetrics(0).bounds2D.height.roundToInt() } @Throws(BadLocationException::class) private fun paintMessages(g: Graphics) { val g2d = g as Graphics2D for (lessonMessage in allLessonMessages()) { val myMessages = lessonMessage.messageParts for (myMessage in myMessages) { @Suppress("NON_EXHAUSTIVE_WHEN") when (myMessage.type) { MessagePart.MessageType.SHORTCUT -> { val bg = UISettings.instance.shortcutBackgroundColor val needColor = if (lessonMessage.state == MessageState.INACTIVE) Color(bg.red, bg.green, bg.blue, 255 * 3 / 10) else bg for (part in myMessage.splitMe()) { drawRectangleAroundText(part, g2d, needColor) { r2d -> g2d.fill(r2d) } } } MessagePart.MessageType.CODE -> { val needColor = UISettings.instance.codeBorderColor drawRectangleAroundText(myMessage, g2d, needColor) { r2d -> if (panelMode) { g2d.draw(r2d) } else { g2d.fill(r2d) } } } MessagePart.MessageType.ICON_IDX -> { val rect = modelToView2D(myMessage.startOffset + 1) val icon = LearningUiManager.iconMap[myMessage.text] icon?.paintIcon(this, g2d, rect.x.toInt(), rect.y.toInt()) } } } } val lastActiveMessage = activeMessages.lastOrNull() val firstActiveMessage = firstActiveMessage() if (panelMode && lastActiveMessage != null && lastActiveMessage.state == MessageState.NORMAL) { val c = UISettings.instance.activeTaskBorder val a = if (totalAnimation == 0) 255 else 255 * currentAnimation / totalAnimation val needColor = Color(c.red, c.green, c.blue, a) drawRectangleAroundMessage(firstActiveMessage, lastActiveMessage, g2d, needColor) } } private fun firstActiveMessage(): LessonMessage? = activeMessages.indexOfLast { it.state == MessageState.PASSED } .takeIf { it != -1 && it < activeMessages.size - 1 } ?.let { activeMessages[it + 1] } ?: activeMessages.firstOrNull() private fun drawRectangleAroundText(myMessage: MessagePart, g2d: Graphics2D, needColor: Color, draw: (r2d: RoundRectangle2D) -> Unit) { val startOffset = myMessage.startOffset val endOffset = myMessage.endOffset val rectangleStart = modelToView2D(startOffset) val rectangleEnd = modelToView2D(endOffset) val color = g2d.color val fontSize = UISettings.instance.fontSize g2d.color = needColor g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) val shift = if (SystemInfo.isMac) 1f else 2f val r2d = RoundRectangle2D.Double(rectangleStart.x - 2 * indent, rectangleStart.y - indent + JBUIScale.scale(shift), rectangleEnd.x - rectangleStart.x + 4 * indent, (fontSize + 2 * indent).toDouble(), arc.toDouble(), arc.toDouble()) draw(r2d) g2d.color = color } private fun drawRectangleAroundMessage(lastPassedMessage: LessonMessage? = null, lastActiveMessage: LessonMessage, g2d: Graphics2D, needColor: Color) { val startOffset = lastPassedMessage?.let { if (it.start == 0) 0 else it.start + 1 } ?: 0 val endOffset = lastActiveMessage.end val topLineY = modelToView2D(startOffset).y val bottomLineY = modelToView2D(endOffset - 1).let { it.y + it.height } val textHeight = bottomLineY - topLineY val color = g2d.color g2d.color = needColor g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) val xOffset = JBUI.scale(2).toDouble() val yOffset = topLineY - activeTaskInset val width = this.bounds.width - activeTaskInset - xOffset - JBUIScale.scale(2) // 1 + 1 line width val height = textHeight + 2 * activeTaskInset - JBUIScale.scale(2) g2d.draw(RoundRectangle2D.Double(xOffset, yOffset, width, height, arc.toDouble(), arc.toDouble())) g2d.color = color } override fun getMaximumSize(): Dimension { return preferredSize } companion object { private val LOG = Logger.getInstance(LessonMessagePane::class.java) //arc & indent for shortcut back plate private val arc by lazy { JBUI.scale(4) } private val indent by lazy { JBUI.scale(2) } private val activeTaskInset by lazy { JBUI.scale(12) } private fun Point2D.toPoint(): Point { return Point(x.roundToInt(), y.roundToInt()) } private fun Rectangle2D.toRectangle(): Rectangle { return Rectangle(x.roundToInt(), y.roundToInt(), width.roundToInt(), height.roundToInt()) } } }
apache-2.0
cd6f5390df2768f33d90351058ccbce9
37.259197
158
0.692775
4.375406
false
false
false
false
PaleoCrafter/VanillaImmersion
src/main/kotlin/de/mineformers/vanillaimmersion/block/Anvil.kt
1
2095
package de.mineformers.vanillaimmersion.block import de.mineformers.vanillaimmersion.tileentity.AnvilLogic import de.mineformers.vanillaimmersion.util.spill import net.minecraft.block.BlockAnvil import net.minecraft.block.SoundType import net.minecraft.block.state.IBlockState import net.minecraft.entity.player.EntityPlayer import net.minecraft.util.EnumFacing import net.minecraft.util.EnumHand import net.minecraft.util.ResourceLocation import net.minecraft.util.math.BlockPos import net.minecraft.world.World /** * Immersive Anvil implementation. * Derives from the Vanilla anvil to allow substitution later on. * Adds a tile entity to the anvil, but this does not break Vanilla compatibility. */ open class Anvil : BlockAnvil() { init { setHardness(5.0F) soundType = SoundType.ANVIL setResistance(2000.0F) unlocalizedName = "anvil" registryName = ResourceLocation("minecraft", "anvil") } /** * Handles right clicks for the anvil. * Does not do anything since interaction is handled through * [RepairHandler][de.mineformers.vanillaimmersion.immersion.RepairHandler]. */ override fun onBlockActivated(world: World, pos: BlockPos, state: IBlockState, player: EntityPlayer, hand: EnumHand, side: EnumFacing, hitX: Float, hitY: Float, hitZ: Float) = true /** * Drops the anvil's contents when it's broken. */ override fun breakBlock(world: World, pos: BlockPos, state: IBlockState) { val tile = world.getTileEntity(pos) if (tile is AnvilLogic) { tile.inventory.spill(world, pos) world.updateComparatorOutputLevel(pos, this) } super.breakBlock(world, pos, state) } /** * We need to override this since the Vanilla anvil does not have a TileEntity. */ override fun hasTileEntity(state: IBlockState?) = true /** * Create the anvil's TileEntity. */ override fun createTileEntity(world: World?, state: IBlockState?) = AnvilLogic() }
mit
a1af8ab97047b2dead5bebba4f19f891
34.525424
97
0.689737
4.466951
false
false
false
false
smmribeiro/intellij-community
plugins/editorconfig/src/org/editorconfig/language/codeinsight/documentation/EditorConfigDocumentationProvider.kt
2
2340
// 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.editorconfig.language.codeinsight.documentation import com.intellij.lang.documentation.DocumentationProvider import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.psi.PsiWhiteSpace import org.editorconfig.language.psi.interfaces.EditorConfigDescribableElement import org.editorconfig.language.schema.descriptors.EditorConfigDescriptor import org.editorconfig.language.util.EditorConfigPsiTreeUtil.getParentOfType import org.jetbrains.annotations.Nls import kotlin.math.max class EditorConfigDocumentationProvider : DocumentationProvider { override fun generateDoc(element: PsiElement, originalElement: PsiElement?): @Nls String? { element as? EditorConfigDocumentationHolderElement ?: return null return element.descriptor?.documentation } override fun getQuickNavigateInfo(element: PsiElement, originalElement: PsiElement?): @Nls String? { element as? EditorConfigDocumentationHolderElement ?: return null return element.descriptor?.documentation } override fun getDocumentationElementForLookupItem( psiManager: PsiManager, lookupElement: Any, contextElement: PsiElement ): PsiElement? = when (lookupElement) { is EditorConfigDescriptor -> EditorConfigDocumentationHolderElement(psiManager, lookupElement) else -> null } override fun getCustomDocumentationElement(editor: Editor, file: PsiFile, contextElement: PsiElement?, targetOffset: Int): PsiElement? { contextElement ?: return null if (contextElement !is PsiWhiteSpace) { val describable = contextElement.getParentOfType<EditorConfigDescribableElement>() val descriptor = describable?.getDescriptor(false) return EditorConfigDocumentationHolderElement(file.manager, descriptor) } val offset = max(0, targetOffset - 1) val psiBeforeCaret = file.findElementAt(offset) val describable = psiBeforeCaret?.getParentOfType<EditorConfigDescribableElement>() val descriptor = describable?.getDescriptor(false) ?: return null return EditorConfigDocumentationHolderElement(file.manager, descriptor) } }
apache-2.0
299d0abc717ab5b5db3f7f3be702ebd1
45.8
158
0.803419
5.27027
false
true
false
false
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/ide/bookmark/BookmarksListProviderService.kt
9
2561
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.bookmark import com.intellij.ide.favoritesTreeView.FavoritesListProvider import com.intellij.openapi.project.Project import com.intellij.ui.CommonActionsPanel.Buttons import java.util.Collections.unmodifiableList import java.util.concurrent.atomic.AtomicReference import javax.swing.JComponent class BookmarksListProviderService(project: Project) { private val reference = AtomicReference<List<BookmarksListProvider>>() init { BookmarksListProvider.EP.addChangeListener(project, { reference.set(null) }, project) FavoritesListProvider.EP_NAME.getPoint(project).addChangeListener({ reference.set(null) }, project) } companion object { fun findProvider(project: Project, predicate: (BookmarksListProvider) -> Boolean) = getProviders(project).find(predicate) fun getProviders(project: Project): List<BookmarksListProvider> { if (project.isDisposed) return emptyList() val reference = project.getService(BookmarksListProviderService::class.java)?.reference ?: return emptyList() return reference.get() ?: createProviders(project).also { reference.set(it) } } private fun createProviders(project: Project): List<BookmarksListProvider> { val providers = BookmarksListProvider.EP.getExtensions(project).toMutableList() FavoritesListProvider.EP_NAME.getExtensionList(project).mapTo(providers) { Adapter(project, it) } providers.sortByDescending { it.weight } return unmodifiableList(providers) } } private class Adapter(private val project: Project, private val provider: FavoritesListProvider) : BookmarksListProvider { override fun getProject() = project override fun getWeight() = provider.weight override fun createNode() = provider.createFavoriteListNode(project) override fun getEditActionText() = provider.getCustomName(Buttons.EDIT) override fun canEdit(selection: Any) = provider.willHandle(Buttons.EDIT, project, setOf(selection)) override fun performEdit(selection: Any, parent: JComponent) = provider.handle(Buttons.EDIT, project, setOf(selection), parent) override fun getDeleteActionText() = provider.getCustomName(Buttons.REMOVE) override fun canDelete(selection: List<*>) = provider.willHandle(Buttons.REMOVE, project, selection.toSet()) override fun performDelete(selection: List<*>, parent: JComponent) = provider.handle(Buttons.REMOVE, project, selection.toSet(), parent) } }
apache-2.0
48d3cbda02ee31035fb337a85752a600
52.354167
140
0.773916
4.573214
false
false
false
false
bhubie/Expander
app/src/main/kotlin/com/wanderfar/expander/Models/MacroConstants.kt
1
1183
/* * Expander: Text Expansion Application * Copyright (C) 2016 Brett Huber * * 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.wanderfar.expander.Models object MacroConstants { val IMMEDIATELY = 0 val ON_A_SPACE = 1 val ON_A_PERIOD = 2 val ON_A_SPACE_OR_PERIOD = 3 val SORT_BY_NAME = 1 val SORT_BY_USAGE_COUNT = 2 val SORT_BY_LAST_USED = 3 //val IMMEDIETELY_PATTERN = "($1)(\\s|\\.|\\.\\s)" //val ON_A_SPACE_PATTERN = "($1)(\\s)" //val ON_A_PERIOD_PATTERN = "($1)(\\.)" //val ON_A_SPACE_OR_PERIOD_PATTERN = "($1)" }
gpl-3.0
9cb2ca526ced03963b42f5cbbefe8e3b
28.6
72
0.674556
3.531343
false
false
false
false
vector-im/vector-android
vector/src/main/java/im/vector/fragments/roomwidgets/RoomWidgetPermissionBottomSheet.kt
2
4500
/* * Copyright 2019 New Vector 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 im.vector.fragments.roomwidgets import android.content.DialogInterface import android.os.Build import android.os.Parcelable import android.text.Spannable import android.text.SpannableStringBuilder import android.text.style.BulletSpan import android.widget.ImageView import android.widget.TextView import butterknife.BindView import butterknife.OnClick import com.airbnb.mvrx.MvRx import com.airbnb.mvrx.fragmentViewModel import com.airbnb.mvrx.withState import im.vector.R import im.vector.extensions.withArgs import im.vector.fragments.VectorBaseBottomSheetDialogFragment import im.vector.util.VectorUtils import im.vector.widgets.Widget import kotlinx.android.parcel.Parcelize class RoomWidgetPermissionBottomSheet : VectorBaseBottomSheetDialogFragment() { override fun getLayoutResId(): Int = R.layout.bottom_sheet_room_widget_permission private val viewModel: RoomWidgetPermissionViewModel by fragmentViewModel() @BindView(R.id.bottom_sheet_widget_permission_shared_info) lateinit var sharedInfoTextView: TextView @BindView(R.id.bottom_sheet_widget_permission_owner_id) lateinit var authorIdText: TextView @BindView(R.id.bottom_sheet_widget_permission_owner_display_name) lateinit var authorNameText: TextView @BindView(R.id.bottom_sheet_widget_permission_owner_avatar) lateinit var authorAvatarView: ImageView var onFinish: ((Boolean) -> Unit)? = null override fun invalidate() = withState(viewModel) { state -> authorIdText.text = state.authorId authorNameText.text = state.authorName ?: "" VectorUtils.loadUserAvatar(requireContext(), viewModel.session, authorAvatarView, state.authorAvatarUrl, state.authorId, state.authorName) val domain = state.widgetDomain ?: "" val infoBuilder = SpannableStringBuilder() .append(getString( R.string.room_widget_permission_webview_shared_info_title .takeIf { state.isWebviewWidget } ?: R.string.room_widget_permission_shared_info_title, "'$domain'")) infoBuilder.append("\n") state.permissionsList?.forEach { infoBuilder.append("\n") val bulletPoint = getString(it) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { infoBuilder.append(bulletPoint, BulletSpan(resources.getDimension(R.dimen.quote_gap).toInt()), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } else { val start = infoBuilder.length infoBuilder.append(bulletPoint) infoBuilder.setSpan( BulletSpan(resources.getDimension(R.dimen.quote_gap).toInt()), start, bulletPoint.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) } } infoBuilder.append("\n") sharedInfoTextView.text = infoBuilder } @OnClick(R.id.bottom_sheet_widget_permission_decline_button) fun doDecline() { viewModel.blockWidget() //optimistic dismiss dismiss() onFinish?.invoke(false) } @OnClick(R.id.bottom_sheet_widget_permission_continue_button) fun doAccept() { viewModel.allowWidget() onFinish?.invoke(true) //optimistic dismiss dismiss() } override fun onCancel(dialog: DialogInterface?) { super.onCancel(dialog) onFinish?.invoke(false) } @Parcelize data class FragArgs( val widget: Widget, val mxId: String ) : Parcelable companion object { fun newInstance(matrixId: String, widget: Widget) = RoomWidgetPermissionBottomSheet().withArgs { putParcelable(MvRx.KEY_ARG, FragArgs(widget, matrixId)) } } }
apache-2.0
7a3a37de8bbf89f95006941faa14d4b1
33.358779
146
0.673111
4.610656
false
false
false
false
josmas/MovesDiary
app/src/main/java/org/josmas/movesdiary/db/DB.kt
1
2844
package org.josmas.movesdiary.db import android.content.Context import org.jetbrains.anko.db.* import android.database.sqlite.SQLiteDatabase import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.info import org.josmas.movesdiary.App import org.josmas.movesdiary.Credentials import org.josmas.movesdiary.UserProfile class DB(ctx: Context = App.instance) : ManagedSQLiteOpenHelper(ctx, DB_NAME, null, DB_VERSION) { companion object { val DB_NAME = "MovesDiaryDb.db" val DB_VERSION = 2 val instance: DB by lazy { DB() } } override fun onCreate(db: SQLiteDatabase) { //TODO (jos) need to find a way to DRY table names and attributes (here and in the object below) db.createTable("Credentials", true, "token_type" to TEXT, "expires_in" to INTEGER, "access_token" to TEXT, "user_id" to INTEGER, "refresh_token" to TEXT) } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { db.dropTable("Credentials", true) db.dropTable("UserProfile", true) onCreate(db) /** * The Profile API returns more fields than the ones below, but we don't need to store them, at * least for now. */ db.createTable("UserProfile", true, "userId" to INTEGER, "firstDate" to TEXT, "language" to TEXT, "locale" to TEXT) } } object dbOperations: AnkoLogger { val database: DB = DB.instance fun insertCredentials(cred: Credentials) : Long { var returnCode = -1L database.use { val returnDelete = delete("Credentials", "") info("Delete successful if it's not -1? " + returnDelete) returnCode = insert("Credentials", "token_type" to cred.token_type, "access_token" to cred.access_token, "expires_in" to cred.expires_in, "user_id" to cred.user_id, "refresh_token" to cred.refresh_token) } return returnCode; } fun getAccessToken(): String { var accessToken: String = "" database.use { val result = select("Credentials", "access_token").limit(1) accessToken = result.parseOpt(StringParser) ?: "" } return accessToken; } fun insertUserProfile(userProf: UserProfile) : Long { var returnCode = -1L database.use { val returnDelete = delete("UserProfile", "") // Keeping only 1 active userProfile for now info("Delete successful if it's not -1? " + returnDelete) returnCode = insert("UserProfile", "userId" to userProf.userId, "firstDate" to userProf.profile.firstDate, "language" to userProf.profile.localization.language, "locale" to userProf.profile.localization.locale) info("I am called; I am insertUserProfile INSIDE DATABASE.USE with a returnCode of: " + returnCode) } return returnCode; } }
mit
fdf786fc7102ccc28d2f71b3b5e24623
30.611111
105
0.660689
3.928177
false
false
false
false
AVnetWS/Hentoid
app/src/main/java/me/devsaki/hentoid/fragments/preferences/PreferencesFragment.kt
1
12000
package me.devsaki.hentoid.fragments.preferences import android.content.DialogInterface import android.content.SharedPreferences import android.net.Uri import android.os.Build import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.commit import androidx.lifecycle.ViewModelProvider import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import androidx.preference.PreferenceScreen import com.google.android.material.dialog.MaterialAlertDialogBuilder import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposables import io.reactivex.schedulers.Schedulers import me.devsaki.hentoid.R import me.devsaki.hentoid.activities.DrawerEditActivity import me.devsaki.hentoid.activities.PinPreferenceActivity import me.devsaki.hentoid.core.startLocalActivity import me.devsaki.hentoid.core.withArguments import me.devsaki.hentoid.database.ObjectBoxDAO import me.devsaki.hentoid.fragments.ProgressDialogFragment import me.devsaki.hentoid.services.UpdateCheckService import me.devsaki.hentoid.util.FileHelper import me.devsaki.hentoid.util.Preferences import me.devsaki.hentoid.util.ThemeHelper import me.devsaki.hentoid.util.ToastHelper import me.devsaki.hentoid.viewmodels.PreferencesViewModel import me.devsaki.hentoid.viewmodels.ViewModelFactory import me.devsaki.hentoid.workers.ExternalImportWorker import me.devsaki.hentoid.workers.ImportWorker import me.devsaki.hentoid.workers.UpdateDownloadWorker class PreferencesFragment : PreferenceFragmentCompat(), SharedPreferences.OnSharedPreferenceChangeListener { lateinit var viewModel: PreferencesViewModel private var rootView: View? = null companion object { private const val KEY_ROOT = "root" fun newInstance(rootKey: String?): PreferencesFragment { val fragment = PreferencesFragment() if (rootKey != null) { val args = Bundle() args.putCharSequence(KEY_ROOT, rootKey) fragment.arguments = args } return fragment } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val arguments = arguments if (arguments != null && arguments.containsKey(KEY_ROOT)) { val root = arguments.getCharSequence(KEY_ROOT) if (root != null) preferenceScreen = findPreference(root) } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) rootView = view val vmFactory = ViewModelFactory(requireActivity().application) viewModel = ViewModelProvider(requireActivity(), vmFactory)[PreferencesViewModel::class.java] } override fun onResume() { super.onResume() preferenceScreen.sharedPreferences .registerOnSharedPreferenceChangeListener(this) } override fun onDestroy() { preferenceScreen.sharedPreferences .unregisterOnSharedPreferenceChangeListener(this) rootView = null // Avoid leaks super.onDestroy() } override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.preferences, rootKey) onHentoidFolderChanged() onExternalFolderChanged() populateMemoryUsage() } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { when (key) { Preferences.Key.COLOR_THEME -> onPrefColorThemeChanged() Preferences.Key.DL_THREADS_QUANTITY_LISTS, Preferences.Key.APP_PREVIEW, Preferences.Key.ANALYTICS_PREFERENCE -> onPrefRequiringRestartChanged() Preferences.Key.SETTINGS_FOLDER, Preferences.Key.SD_STORAGE_URI -> onHentoidFolderChanged() Preferences.Key.EXTERNAL_LIBRARY_URI -> onExternalFolderChanged() } } override fun onPreferenceTreeClick(preference: Preference): Boolean = when (preference.key) { Preferences.Key.DRAWER_SOURCES -> { requireContext().startLocalActivity<DrawerEditActivity>() true } Preferences.Key.EXTERNAL_LIBRARY -> { if (ExternalImportWorker.isRunning(requireContext())) { ToastHelper.toast(R.string.pref_import_running) } else { LibRefreshDialogFragment.invoke(parentFragmentManager, false, true, true) } true } Preferences.Key.EXTERNAL_LIBRARY_DETACH -> { MaterialAlertDialogBuilder( requireContext(), ThemeHelper.getIdForCurrentTheme(requireContext(), R.style.Theme_Light_Dialog) ) .setIcon(R.drawable.ic_warning) .setCancelable(true) .setTitle(R.string.app_name) .setMessage(R.string.prefs_ask_detach_external_library) .setPositiveButton( R.string.yes ) { dialog1: DialogInterface, _: Int -> dialog1.dismiss() Preferences.setExternalLibraryUri("") viewModel.removeAllExternalContent() ToastHelper.toast(R.string.prefs_external_library_detached) } .setNegativeButton( R.string.no ) { dialog12: DialogInterface, _: Int -> dialog12.dismiss() } .create() .show() true } Preferences.Key.REFRESH_LIBRARY -> { if (ImportWorker.isRunning(requireContext())) { ToastHelper.toast(R.string.pref_import_running) } else { LibRefreshDialogFragment.invoke(parentFragmentManager, true, false, false) } true } Preferences.Key.DELETE_ALL_EXCEPT_FAVS -> { onDeleteAllExceptFavourites() true } Preferences.Key.VIEWER_RENDERING -> { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) ToastHelper.toast(R.string.pref_viewer_rendering_no_android5) true } Preferences.Key.SETTINGS_FOLDER -> { if (ImportWorker.isRunning(requireContext())) { ToastHelper.toast(R.string.pref_import_running) } else { LibRefreshDialogFragment.invoke(parentFragmentManager, false, true, false) } true } Preferences.Key.MEMORY_USAGE -> { MemoryUsageDialogFragment.invoke(parentFragmentManager) true } Preferences.Key.APP_LOCK -> { requireContext().startLocalActivity<PinPreferenceActivity>() true } Preferences.Key.CHECK_UPDATE_MANUAL -> { onCheckUpdatePrefClick() true } else -> super.onPreferenceTreeClick(preference) } override fun onNavigateToScreen(preferenceScreen: PreferenceScreen) { val preferenceFragment = PreferencesFragment().withArguments { putString(ARG_PREFERENCE_ROOT, preferenceScreen.key) } parentFragmentManager.commit(true) { replace(android.R.id.content, preferenceFragment) addToBackStack(null) // This triggers a memory leak in LeakCanary but is _not_ a leak : see https://stackoverflow.com/questions/27913009/memory-leak-in-fragmentmanager } } private fun onCheckUpdatePrefClick() { if (!UpdateDownloadWorker.isRunning(requireContext())) { val intent = UpdateCheckService.makeIntent(requireContext(), true) requireContext().startService(intent) } } private fun onPrefRequiringRestartChanged() { ToastHelper.toast(R.string.restart_needed) } private fun onHentoidFolderChanged() { val storageFolderPref: Preference? = findPreference(Preferences.Key.SETTINGS_FOLDER) as Preference? val uri = Uri.parse(Preferences.getStorageUri()) storageFolderPref?.summary = FileHelper.getFullPathFromTreeUri(requireContext(), uri) } private fun onExternalFolderChanged() { val storageFolderPref: Preference? = findPreference(Preferences.Key.EXTERNAL_LIBRARY) as Preference? val uri = Uri.parse(Preferences.getExternalLibraryUri()) storageFolderPref?.summary = FileHelper.getFullPathFromTreeUri(requireContext(), uri) // Enable/disable sub-prefs val deleteExternalLibrary: Preference? = findPreference(Preferences.Key.EXTERNAL_LIBRARY_DELETE) as Preference? deleteExternalLibrary?.isEnabled = (uri.toString().isNotEmpty()) val detachExternalLibrary: Preference? = findPreference(Preferences.Key.EXTERNAL_LIBRARY_DETACH) as Preference? detachExternalLibrary?.isEnabled = (uri.toString().isNotEmpty()) } private fun onPrefColorThemeChanged() { ThemeHelper.applyTheme(requireActivity() as AppCompatActivity) } private fun populateMemoryUsage() { val folder = FileHelper.getFolderFromTreeUriString(requireContext(), Preferences.getStorageUri()) ?: return val memUsagePref: Preference? = findPreference(Preferences.Key.MEMORY_USAGE) as Preference? memUsagePref?.summary = resources.getString( R.string.pref_memory_usage_summary, FileHelper.MemoryUsageFigures(requireContext(), folder).freeUsageRatio100 ) } private fun onDeleteAllExceptFavourites() { val dao = ObjectBoxDAO(activity) var searchDisposable = Disposables.empty() searchDisposable = Single.fromCallable { dao.selectStoredContentIds(true, false, -1, false) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { list -> MaterialAlertDialogBuilder( requireContext(), ThemeHelper.getIdForCurrentTheme( requireContext(), R.style.Theme_Light_Dialog ) ) .setIcon(R.drawable.ic_warning) .setCancelable(false) .setTitle(R.string.app_name) .setMessage(getString(R.string.pref_ask_delete_all_except_favs, list.size)) .setPositiveButton( R.string.yes ) { dialog1: DialogInterface, _: Int -> dao.cleanup() dialog1.dismiss() searchDisposable.dispose() ProgressDialogFragment.invoke( parentFragmentManager, resources.getString(R.string.delete_title), resources.getString(R.string.books) ) viewModel.deleteAllItemsExceptFavourites() } .setNegativeButton( R.string.no ) { dialog12: DialogInterface, _: Int -> dao.cleanup() dialog12.dismiss() } .create() .show() } } }
apache-2.0
9f2f830b1e4d4bf599647ddcd4406b8a
40.525952
179
0.60775
5.540166
false
false
false
false
npryce/snodge
common/src/main/com/natpryce/xmlk/translate_dom.kt
1
2639
package com.natpryce.xmlk import org.w3c.dom.Attr import org.w3c.dom.CDATASection import org.w3c.dom.Comment import org.w3c.dom.DOMImplementation import org.w3c.dom.Document import org.w3c.dom.Element import org.w3c.dom.Node import org.w3c.dom.NodeList import org.w3c.dom.ProcessingInstruction import org.w3c.dom.Text fun Document.toXmlDocument(): XmlDocument = XmlDocument(childNodes.map { node -> node.toXmlNode()}) private fun Node.toXmlNode(): XmlNode = when(this) { is Element -> this.toXmlElement() is Text -> XmlText(data, asCData = false) is CDATASection -> XmlText(data, asCData = true) is ProcessingInstruction -> this.toXmlProcessingInstruction() is Comment -> XmlComment(textContent ?: "") else -> throw IllegalArgumentException("cannot convert ${this::class.simpleName} to XmlNode") } @Suppress("UNNECESSARY_SAFE_CALL") // Required for JVM platform but not JS platform private fun ProcessingInstruction.toXmlProcessingInstruction() = XmlProcessingInstruction(target, data?.takeIf { it.isNotEmpty() }) private fun Element.toXmlElement(): XmlElement { return XmlElement( name = QName(localName, namespaceURI, prefix), attributes = (0 until attributes.length) .map { i -> attributes.item(i) as Attr } .associate{ QName(it.localName, it.namespaceURI, it.prefix) to it.value }, children = childNodes.map { it.toXmlNode() }) } private fun NodeList.map(f: (Node)->XmlNode): List<XmlNode> = (0 until length).map { f(this.item(it)!!) } fun XmlDocument.toDOM(implementation: DOMImplementation = defaultDOMImplementation()): Document { return implementation.createEmptyDocument() .also { doc: Document -> children.forEach { child -> doc.appendChild(child.toDOM(doc)) } } } private fun XmlNode.toDOM(doc: Document): Node = when (this) { is XmlText -> if (asCData) doc.createCDATASection(text) else doc.createTextNode(text) is XmlElement -> doc.createElementNS(name.namespaceURI, name.toDOM()).also { element -> attributes.forEach { (attrName, attrValue) -> element.setAttributeNS(attrName.namespaceURI, attrName.toDOM(), attrValue) } children.forEach { child -> element.appendChild(child.toDOM(doc)) } } is XmlComment -> doc.createComment(text) is XmlProcessingInstruction -> { doc.createProcessingInstruction(target, data ?: "") } } private fun QName.toDOM() = (prefix?.plus(":") ?: "") + localPart
apache-2.0
2e86a3edf1153b69c2ca8567e7b5774e
36.7
101
0.663888
4.022866
false
false
false
false
AlmasB/Zephyria
src/main/kotlin/com/almasb/zeph/data/Weapons.kt
1
7443
package com.almasb.zeph.data import com.almasb.zeph.combat.Attribute.* import com.almasb.zeph.combat.Element.WATER import com.almasb.zeph.combat.Stat import com.almasb.zeph.combat.Stat.* import com.almasb.zeph.combat.effect import com.almasb.zeph.combat.runIfChance import com.almasb.zeph.item.ItemLevel.EPIC import com.almasb.zeph.item.WeaponType.* import com.almasb.zeph.item.weapon /** * Weapons id range [4000-4999]. * * @author Almas Baimagambetov ([email protected]) */ class Weapons { val Maces = Maces() val OneHandedSwords = OneHandedSwords() val OneHandedAxes = OneHandedAxes() val Daggers = Daggers() val Spears = Spears() val Rods = Rods() val Shields = Shields() val TwoHandedSwords = TwoHandedSwords() val TwoHandedAxes = TwoHandedAxes() val Katars = Katars() val Bows = Bows() } // MACES 4500? class Maces { val HANDS = weapon { desc { id = 4000 name = "Hands" description = "That's right, go kill everyone with your bare hands." textureName = "items/weapons/hands.png" } type = MACE } } // public static final String HALLSTATT_SWORD = "A sword favored by gladiators, it is especially designed for battles against armored enemies"; // public static final String KAMPILAN_SWORD = "A thin sword designed to be easily bent, light, and very elastic"; // public static final String MACHETE = "A strong cleaver-like sword"; // public static final String TEGA_SWORD = "A ceremonial sword used by gravekeeper's to lead the dead to the great beyond"; // public static final String SCHIAVONA_SWORD = "A popular sword among mercenary soldiers"; // public static final String COLICHERMARDE_SWORD = "S"; class OneHandedSwords { val PRACTICE_SWORD = weapon { desc { id = 4100 name = "Practice Sword" description = "A basic one-handed sword." } type = ONE_H_SWORD pureDamage = 15 } val IRON_SWORD = weapon { desc { id = 4101 name = "Iron Sword" description = "A standard warrior's sword." } type = ONE_H_SWORD pureDamage = 25 } val SCIMITAR = weapon { desc { id = 4102 name = "Scimitar" description = "A balanced sword with good parrying characteristics." } type = ONE_H_SWORD pureDamage = 35 AGILITY +1 DEXTERITY +1 } val STEEL_SWORD = weapon { desc { id = 4103 name = "Steel Sword" description = "A sword made of strongest steel." } type = ONE_H_SWORD pureDamage = 38 } val GUARD_SWORD = weapon { desc { id = 4104 name = "Guard Sword" description = "A long sword typically used by royal guards. On attack has 10% chance to increase ATK by 15 for 3 seconds" } type = ONE_H_SWORD pureDamage = 35 onAttackScript = { attacker, _ -> runIfChance(10) { attacker.addEffect(effect(description) { duration = 3.0 ATK +15 }) } } } } class OneHandedAxes { // 1H AXES 4300 } class Daggers { val KNIFE = weapon { desc { id = 4001 name = "Knife" description = "A simple knife with a poor blade." } type = DAGGER pureDamage = 10 } val GUT_RIPPER = weapon { desc { id = 4050 name = "Gut Ripper" description = "A fierce weapon that punctures and ruptures enemies with vicious and lightning fast blows." } type = DAGGER itemLevel = EPIC pureDamage = 100 AGILITY +4 DEXTERITY +4 LUCK +1 } val DEMONIC_BLADE = weapon { desc { id = 4051 name = "Demonic Blade" description = "A dagger that once belonged to a demonic prince. Significantly increases critical chance at the cost of defense." } type = DAGGER itemLevel = EPIC pureDamage = 50 DEF -50 CRIT_CHANCE +100 } } // SPEARS 4700 class Spears { } // RODS 4900 class Rods { } class Shields { } class TwoHandedSwords { val CLAYMORE = weapon { desc { id = 4200 name = "Claymore" description = "Large, double-edged broad sword" } type = TWO_H_SWORD pureDamage = 35 STRENGTH +1 } val BROADSWORD = weapon { desc { id = 4201 name = "Broadsword" description = "A sword with a wide, double sided blade." } type = TWO_H_SWORD pureDamage = 28 LUCK +1 } val BATTLESWORD = weapon { desc { id = 4202 name = "Battlesword" description = "A terrifying two-handed sword that is said to stimulate the nerves in order to kill, once it's in the wearer's hands." } type = TWO_H_SWORD pureDamage = 44 STRENGTH +2 VITALITY +1 } val LONGSWORD = weapon { desc { id = 4203 name = "Longsword" description = "A two-handed sword with straight double-edged blade." } type = TWO_H_SWORD pureDamage = 33 AGILITY +1 DEXTERITY +2 } val FROSTMOURNE = weapon { desc { id = 4250 name = "Frostmourne" description = "The legendary sword of the Ice Dungeon's King." textureName = "items/weapons/frostmourne.png" } itemLevel = EPIC type = TWO_H_SWORD pureDamage = 130 element = WATER STRENGTH +3 DEXTERITY +5 } } class TwoHandedAxes { // 2H AXES 4400 val SOUL_REAPER = weapon { desc { id = 4400 name = "Soul Reaper" description = "Forged in the depths of Aesmir, it is said the wielder can feel the weapon crave the souls of its enemies.\n" + "Steals 3 SP on attack." textureName = "items/weapons/soul_reaper.png" } itemLevel = EPIC type = TWO_H_AXE pureDamage = 170 onAttackScript = { attacker, target -> target.sp.damage(3.0) attacker.sp.restore(3.0) } STRENGTH +7 VITALITY +4 DEXTERITY +2 MAX_SP +20 } } // KATARS 4600 class Katars { } // BOWS 4800 class Bows { // fun DRAGON_CLAW() = listOf<Component>( // Description(4800, "Dragon's Claw", "A mythical bow made of claws of the legendary dragon. Contains dragon's wisdom and loyal to only one master throughout his whole life. Grants dragon's and earlier owner's wisdom and knowledge to the new master.", "items/weapons/dragon_claw.png"), // WeaponDataComponent(ItemLevel.EPIC, WeaponType.BOW, 130) // .withRune(Rune(Attribute.WISDOM, 3)) // .withRune(Rune(Attribute.DEXTERITY, 4)) // .withRune(Rune(Attribute.LUCK, 1)) // .withElement(Element.FIRE) // ) // // // } }
gpl-2.0
df528ec30bdd675deae9c47b79419bca
22.935691
300
0.548032
3.730827
false
false
false
false
markusfisch/BinaryEye
app/src/main/kotlin/de/markusfisch/android/binaryeye/database/Database.kt
1
9145
package de.markusfisch.android.binaryeye.database import android.content.ContentValues import android.content.Context import android.database.Cursor import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import de.markusfisch.android.binaryeye.app.prefs class Database { private lateinit var db: SQLiteDatabase fun open(context: Context) { db = OpenHelper(context).writableDatabase } fun getScans(query: String? = null): Cursor? = db.rawQuery( """SELECT $SCANS_ID, $SCANS_DATETIME, $SCANS_NAME, $SCANS_CONTENT, $SCANS_FORMAT FROM $SCANS ${getWhereClause(query)} ORDER BY $SCANS_DATETIME DESC """.trimMargin(), getWhereArguments(query) ) fun getScansDetailed(query: String? = null): Cursor? = db.rawQuery( """SELECT $SCANS_ID, $SCANS_DATETIME, $SCANS_NAME, $SCANS_CONTENT, $SCANS_RAW, $SCANS_FORMAT, $SCANS_ERROR_CORRECTION_LEVEL, $SCANS_VERSION_NUMBER, $SCANS_SEQUENCE_SIZE, $SCANS_SEQUENCE_INDEX, $SCANS_SEQUENCE_ID, $SCANS_GTIN_COUNTRY, $SCANS_GTIN_ADD_ON, $SCANS_GTIN_PRICE, $SCANS_GTIN_ISSUE_NUMBER FROM $SCANS ${getWhereClause(query)} ORDER BY $SCANS_DATETIME DESC """.trimMargin(), getWhereArguments(query) ) private fun getWhereClause( query: String?, prefix: String = "WHERE" ) = if (query?.isNotEmpty() == true) { """$prefix $SCANS_CONTENT LIKE ? OR $SCANS_NAME LIKE ?""" } else { "" } private fun getWhereArguments( query: String? ) = if (query?.isNotEmpty() == true) { val instr = "%$query%" arrayOf(instr, instr) } else { null } fun getScan(id: Long): Scan? = db.rawQuery( """SELECT $SCANS_ID, $SCANS_DATETIME, $SCANS_NAME, $SCANS_CONTENT, $SCANS_RAW, $SCANS_FORMAT, $SCANS_ERROR_CORRECTION_LEVEL, $SCANS_VERSION_NUMBER, $SCANS_SEQUENCE_SIZE, $SCANS_SEQUENCE_INDEX, $SCANS_SEQUENCE_ID, $SCANS_GTIN_COUNTRY, $SCANS_GTIN_ADD_ON, $SCANS_GTIN_PRICE, $SCANS_GTIN_ISSUE_NUMBER FROM $SCANS WHERE $SCANS_ID = ? """.trimMargin(), arrayOf("$id") )?.use { if (it.moveToFirst()) { Scan( it.getString(SCANS_CONTENT), it.getBlob(SCANS_RAW), it.getString(SCANS_FORMAT), it.getString(SCANS_ERROR_CORRECTION_LEVEL), it.getInt(SCANS_VERSION_NUMBER), it.getInt(SCANS_SEQUENCE_SIZE), it.getInt(SCANS_SEQUENCE_INDEX), it.getString(SCANS_SEQUENCE_ID), it.getString(SCANS_GTIN_COUNTRY), it.getString(SCANS_GTIN_ADD_ON), it.getString(SCANS_GTIN_PRICE), it.getString(SCANS_GTIN_ISSUE_NUMBER), it.getString(SCANS_DATETIME), it.getLong(SCANS_ID) ) } else { null } } fun insertScan(scan: Scan): Long = db.insert( SCANS, null, ContentValues().apply { put(SCANS_DATETIME, scan.dateTime) val isRaw = scan.raw != null if (isRaw) { put(SCANS_CONTENT, "") put(SCANS_RAW, scan.raw) } else { put(SCANS_CONTENT, scan.content) } put(SCANS_FORMAT, scan.format) scan.errorCorrectionLevel?.let { put(SCANS_ERROR_CORRECTION_LEVEL, it) } put(SCANS_VERSION_NUMBER, scan.versionNumber) put(SCANS_SEQUENCE_SIZE, scan.sequenceSize) put(SCANS_SEQUENCE_INDEX, scan.sequenceIndex) put(SCANS_SEQUENCE_ID, scan.sequenceId) scan.country?.let { put(SCANS_GTIN_COUNTRY, it) } scan.addOn?.let { put(SCANS_GTIN_ADD_ON, it) } scan.price?.let { put(SCANS_GTIN_PRICE, it) } scan.issueNumber?.let { put(SCANS_GTIN_ISSUE_NUMBER, it) } if (prefs.ignoreConsecutiveDuplicates) { val id = getIdOfLastScan( get(SCANS_CONTENT) as String, if (isRaw) get(SCANS_RAW) as ByteArray else null, scan.format ) if (id > 0L) { return id } } } ) private fun getIdOfLastScan( content: String, raw: ByteArray?, format: String ): Long = db.rawQuery( """SELECT $SCANS_ID, $SCANS_CONTENT, $SCANS_RAW, $SCANS_FORMAT FROM $SCANS ORDER BY $SCANS_ID DESC LIMIT 1 """.trimMargin(), null )?.use { if (it.count > 0 && it.moveToFirst() && it.getString(SCANS_CONTENT) == content && (raw == null || it.getBlob(SCANS_RAW) ?.contentEquals(raw) == true) && it.getString(SCANS_FORMAT) == format ) { it.getLong(SCANS_ID) } else { 0L } } ?: 0L fun removeScan(id: Long) { db.delete(SCANS, "$SCANS_ID = ?", arrayOf("$id")) } fun removeScans(query: String? = null) { db.delete(SCANS, getWhereClause(query, ""), getWhereArguments(query)) } fun renameScan(id: Long, name: String) { val cv = ContentValues() cv.put(SCANS_NAME, name) db.update(SCANS, cv, "$SCANS_ID = ?", arrayOf("$id")) } private class OpenHelper(context: Context) : SQLiteOpenHelper(context, FILE_NAME, null, 5) { override fun onCreate(db: SQLiteDatabase) { createScans(db) } override fun onUpgrade( db: SQLiteDatabase, oldVersion: Int, newVersion: Int ) { if (oldVersion < 2) { addRawColumn(db) } if (oldVersion < 3) { addMetaDataColumns(db) } if (oldVersion < 4) { addNameColumn(db) } if (oldVersion < 5) { migrateToZxingCpp(db) } } } companion object { const val FILE_NAME = "history.db" const val SCANS = "scans" const val SCANS_ID = "_id" const val SCANS_DATETIME = "_datetime" const val SCANS_NAME = "name" const val SCANS_CONTENT = "content" const val SCANS_RAW = "raw" const val SCANS_FORMAT = "format" const val SCANS_ERROR_CORRECTION_LEVEL = "error_correction_level" const val SCANS_VERSION_NUMBER = "version_number" const val SCANS_ISSUE_NUMBER = "issue_number" const val SCANS_ORIENTATION = "orientation" const val SCANS_OTHER_META_DATA = "other_meta_data" const val SCANS_PDF417_EXTRA_METADATA = "pdf417_extra_metadata" const val SCANS_POSSIBLE_COUNTRY = "possible_country" const val SCANS_SUGGESTED_PRICE = "suggested_price" const val SCANS_UPC_EAN_EXTENSION = "upc_ean_extension" const val SCANS_SEQUENCE_SIZE = "sequence_size" const val SCANS_SEQUENCE_INDEX = "sequence_index" const val SCANS_SEQUENCE_ID = "sequence_id" const val SCANS_GTIN_COUNTRY = "gtin_country" const val SCANS_GTIN_ADD_ON = "gtin_add_on" const val SCANS_GTIN_PRICE = "gtin_price" const val SCANS_GTIN_ISSUE_NUMBER = "gtin_issue_number" private fun createScans(db: SQLiteDatabase) { db.execSQL("DROP TABLE IF EXISTS $SCANS".trimMargin()) db.execSQL( """CREATE TABLE $SCANS ( $SCANS_ID INTEGER PRIMARY KEY AUTOINCREMENT, $SCANS_DATETIME DATETIME NOT NULL, $SCANS_NAME TEXT, $SCANS_CONTENT TEXT NOT NULL, $SCANS_RAW BLOB, $SCANS_FORMAT TEXT NOT NULL, $SCANS_ERROR_CORRECTION_LEVEL TEXT, $SCANS_VERSION_NUMBER INTEGER, $SCANS_SEQUENCE_SIZE INTEGER, $SCANS_SEQUENCE_INDEX INTEGER, $SCANS_SEQUENCE_ID TEXT, $SCANS_GTIN_COUNTRY TEXT, $SCANS_GTIN_ADD_ON TEXT, $SCANS_GTIN_PRICE TEXT, $SCANS_GTIN_ISSUE_NUMBER TEXT )""".trimMargin() ) } private fun addRawColumn(db: SQLiteDatabase) { db.execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_RAW BLOB".trimMargin()) } private fun addMetaDataColumns(db: SQLiteDatabase) { db.apply { execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_ERROR_CORRECTION_LEVEL TEXT".trimMargin()) execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_ISSUE_NUMBER INT".trimMargin()) execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_ORIENTATION INT".trimMargin()) execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_OTHER_META_DATA TEXT".trimMargin()) execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_PDF417_EXTRA_METADATA TEXT".trimMargin()) execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_POSSIBLE_COUNTRY TEXT".trimMargin()) execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_SUGGESTED_PRICE TEXT".trimMargin()) execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_UPC_EAN_EXTENSION TEXT".trimMargin()) } } private fun addNameColumn(db: SQLiteDatabase) { db.execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_NAME TEXT".trimMargin()) } private fun migrateToZxingCpp(db: SQLiteDatabase) { db.apply { execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_VERSION_NUMBER INTEGER".trimMargin()) execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_SEQUENCE_SIZE INTEGER".trimMargin()) execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_SEQUENCE_INDEX INTEGER".trimMargin()) execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_SEQUENCE_ID TEXT".trimMargin()) execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_GTIN_COUNTRY TEXT".trimMargin()) execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_GTIN_ADD_ON TEXT".trimMargin()) execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_GTIN_PRICE TEXT".trimMargin()) execSQL("ALTER TABLE $SCANS ADD COLUMN $SCANS_GTIN_ISSUE_NUMBER TEXT".trimMargin()) execSQL("UPDATE $SCANS SET $SCANS_SEQUENCE_SIZE = -1") execSQL("UPDATE $SCANS SET $SCANS_SEQUENCE_INDEX = -1") execSQL("UPDATE $SCANS SET $SCANS_GTIN_COUNTRY = $SCANS_POSSIBLE_COUNTRY") execSQL("UPDATE $SCANS SET $SCANS_GTIN_ADD_ON = $SCANS_UPC_EAN_EXTENSION") execSQL("UPDATE $SCANS SET $SCANS_GTIN_PRICE = $SCANS_SUGGESTED_PRICE") execSQL("UPDATE $SCANS SET $SCANS_GTIN_ISSUE_NUMBER = $SCANS_ISSUE_NUMBER") } } } }
mit
600bdd94b4c6da6e22037ccbbc1d82ed
28.595469
92
0.677419
2.950952
false
false
false
false
BlueBoxWare/LibGDXPlugin
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/json/GdxJsonElementFactory.kt
1
2378
package com.gmail.blueboxware.libgdxplugin.filetypes.json import com.gmail.blueboxware.libgdxplugin.filetypes.json.psi.GdxJsonFile import com.gmail.blueboxware.libgdxplugin.filetypes.json.psi.GdxJsonPropertyName import com.gmail.blueboxware.libgdxplugin.filetypes.json.psi.GdxJsonValue import com.gmail.blueboxware.libgdxplugin.utils.childOfType import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElement import com.intellij.psi.PsiFileFactory import com.intellij.psi.PsiWhiteSpace /* * Copyright 2019 Blue Box Ware * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ class GdxJsonElementFactory(private val project: Project) { fun createQuotedValueString(value: String): GdxJsonValue? { val content = "\"${StringUtil.escapeStringCharacters(value)}\"" return createElement(content) } fun createPropertyName(name: String, doQuote: Boolean): GdxJsonPropertyName? { val quote = if (doQuote) "\"" else "" val content = "{ $quote${StringUtil.escapeStringCharacters(name)}$quote: bar }" return createElement(content) } fun createNewline(): PsiWhiteSpace? = createElement("f\n", '\n') private inline fun <reified T : PsiElement> createElement(content: String, character: Char): T? = createElement(content, content.indexOf(character)) private inline fun <reified T : PsiElement> createElement(content: String, position: Int): T? = createFile(content)?.findElementAt(position) as? T private inline fun <reified T : PsiElement> createElement(content: String): T? = createFile(content)?.childOfType() private fun createFile(content: String) = PsiFileFactory .getInstance(project) .createFileFromText("dummy.lson", LibGDXJsonFileType.INSTANCE, content) as? GdxJsonFile }
apache-2.0
161ec6d9a5e574cc80523f53f72a0444
40
101
0.742641
4.461538
false
false
false
false
ChainsDD/RxPreferences
lib/src/test/kotlin/com/noshufou/rxpreferences/MockSharedPreferences.kt
1
4172
package com.noshufou.rxpreferences import android.content.SharedPreferences class MockSharedPreferences : SharedPreferences { private val preferences = mutableMapOf<String, Any>() override fun contains(key: String): Boolean = preferences.contains(key) override fun getAll(): Map<String, Any> = preferences.toMap() override fun getBoolean(key: String, value: Boolean): Boolean { if (!preferences.contains(key)) return value return preferences[key] as? Boolean ?: throw ClassCastException("$key is not a Boolean") } override fun getFloat(key: String, value: Float): Float { if (!preferences.contains(key)) return value return preferences[key] as? Float ?: throw ClassCastException("$key is not a Float") } override fun getInt(key: String, value: Int): Int { if (!preferences.contains(key)) return value return preferences[key] as? Int ?: throw ClassCastException("$key is not an Int") } override fun getLong(key: String, value: Long): Long { if (!preferences.containsKey(key)) return value return preferences[key] as? Long ?: throw ClassCastException("$key is not a Long") } override fun getString(key: String, value: String): String { if (!preferences.containsKey(key)) return value return preferences[key] as? String ?: throw ClassCastException("$key is not a String") } override fun getStringSet(key: String, value: Set<String>): Set<String> { if (!preferences.containsKey(key)) return value @Suppress("UNCHECKED_CAST") // Inserts into preferences are checked down in the editor return preferences[key] as? Set<String> ?: throw ClassCastException("$key is not a Set<String>") } override fun edit(): SharedPreferences.Editor = Editor() private val listeners = mutableSetOf<SharedPreferences.OnSharedPreferenceChangeListener>() override fun registerOnSharedPreferenceChangeListener(listener: SharedPreferences.OnSharedPreferenceChangeListener) { listeners += listener } override fun unregisterOnSharedPreferenceChangeListener(listener: SharedPreferences.OnSharedPreferenceChangeListener) { listeners -= listener } private inner class Editor : SharedPreferences.Editor { private var shouldClear: Boolean = false private val pendingChanges = mutableMapOf<String, Any>() private val pendingRemovals = mutableSetOf<String>() override fun clear(): SharedPreferences.Editor { shouldClear = true return this } override fun remove(key: String): SharedPreferences.Editor { pendingRemovals += key return this } override fun putBoolean(key: String, value: Boolean): SharedPreferences.Editor { pendingChanges[key] = value return this } override fun putFloat(key: String, value: Float): SharedPreferences.Editor { pendingChanges[key] = value return this } override fun putInt(key: String, value: Int): SharedPreferences.Editor { pendingChanges[key] = value return this } override fun putLong(key: String, value: Long): SharedPreferences.Editor { pendingChanges[key] = value return this } override fun putString(key: String, value: String): SharedPreferences.Editor { pendingChanges[key] = value return this } override fun putStringSet(key: String, value: Set<String>): SharedPreferences.Editor { pendingChanges[key] = value return this } override fun commit(): Boolean { if (shouldClear) preferences.clear() pendingRemovals.forEach { preferences.remove(it) } preferences.putAll(pendingChanges) pendingChanges.forEach { key, _ -> listeners.forEach { it.onSharedPreferenceChanged(this@MockSharedPreferences, key) } } return true } override fun apply() { commit() } } }
mit
c99a8c598a412395dcf253f5128a765b
34.666667
123
0.648849
5.307888
false
false
false
false
fobo66/BookcrossingMobile
app/src/main/java/com/bookcrossing/mobile/ui/main/MainActivity.kt
1
8533
/* * Copyright 2019 Andrey Mukamolov * * 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.bookcrossing.mobile.ui.main import android.os.Bundle import android.os.PersistableBundle import android.view.MenuItem import android.view.View import androidx.appcompat.widget.Toolbar import androidx.appcompat.widget.Toolbar.OnMenuItemClickListener import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.app.ActivityOptionsCompat import androidx.core.content.edit import androidx.core.os.bundleOf import androidx.drawerlayout.widget.DrawerLayout import androidx.navigation.ActivityNavigatorExtras import androidx.navigation.NavController import androidx.navigation.findNavController import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.setupWithNavController import androidx.preference.PreferenceManager import butterknife.BindView import butterknife.ButterKnife import com.bookcrossing.mobile.R import com.bookcrossing.mobile.ui.base.BaseActivity import com.bookcrossing.mobile.util.EXTRA_KEY import com.bookcrossing.mobile.util.EXTRA_TARGET_FRAGMENT import com.bookcrossing.mobile.util.KEY_CONSENT_STATUS import com.bookcrossing.mobile.util.PRIVACY_POLICY_URL import com.bookcrossing.mobile.util.listeners.BookListener import com.firebase.ui.auth.AuthUI import com.google.ads.consent.ConsentForm import com.google.ads.consent.ConsentFormListener import com.google.ads.consent.ConsentInfoUpdateListener import com.google.ads.consent.ConsentInformation import com.google.ads.consent.ConsentStatus import com.google.android.material.appbar.AppBarLayout import com.google.android.material.navigation.NavigationView import dev.chrisbanes.insetter.doOnApplyWindowInsets import timber.log.Timber import java.net.MalformedURLException import java.net.URL class MainActivity : BaseActivity(), BookListener, OnMenuItemClickListener { @BindView(R.id.coord_layout) lateinit var coordinatorLayout: CoordinatorLayout @BindView(R.id.toolbar) lateinit var toolbar: Toolbar @BindView(R.id.mainAppBarLayout) lateinit var toolbarContainer: AppBarLayout @BindView(R.id.nav_view) lateinit var navigationView: NavigationView @BindView(R.id.drawer_layout) lateinit var drawer: DrawerLayout private val navController: NavController by lazy { val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment navHostFragment.navController } override fun onCreate(savedInstanceState: Bundle?) { setTheme(R.style.AppTheme) super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) ButterKnife.bind(this) coordinatorLayout.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_STABLE) toolbarContainer.doOnApplyWindowInsets { view, windowInsets, initial -> view.setPadding( initial.paddings.left, windowInsets.systemWindowInsetTop + initial.paddings.top, initial.paddings.right, initial.paddings.bottom ) } setupToolbar() checkForConsent() resolveNavigationToFragment(savedInstanceState) } override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) { super.onSaveInstanceState(outState, outPersistentState) outState.putBundle("navHostState", findNavController(R.id.nav_host_fragment).saveState()) } private fun setupToolbar() { val appBarConfiguration = AppBarConfiguration(navController.graph, drawer) toolbar.setupWithNavController(navController, appBarConfiguration) navigationView.setupWithNavController(navController) toolbar.inflateMenu(R.menu.menu_main) toolbar.setOnMenuItemClickListener(this) } private fun checkForConsent() { val consentInformation = ConsentInformation.getInstance(this) val publisherIds = arrayOf(resources.getString(R.string.admob_publisher_id)) consentInformation.requestConsentInfoUpdate(publisherIds, object : ConsentInfoUpdateListener { override fun onConsentInfoUpdated(consentStatus: ConsentStatus) { if (consentInformation.isRequestLocationInEeaOrUnknown) { if (consentStatus == ConsentStatus.UNKNOWN) { val privacyUrl: URL try { privacyUrl = URL(PRIVACY_POLICY_URL) } catch (e: MalformedURLException) { throw IllegalArgumentException("Privacy policy URL was malformed", e) } val form = ConsentForm.Builder(this@MainActivity, privacyUrl).withListener( object : ConsentFormListener() { override fun onConsentFormLoaded() { Timber.d("onConsentFormLoaded: Consent form loaded successfully.") } override fun onConsentFormOpened() { Timber.d("onConsentFormOpened: Consent form was displayed.") } override fun onConsentFormClosed( consentStatus: ConsentStatus?, userPrefersAdFree: Boolean? ) { Timber.d("onConsentFormClosed: $consentStatus") saveConsentStatus(consentStatus) } override fun onConsentFormError(errorDescription: String?) { Timber.d("User's consent status failed to update: $errorDescription") } }).withPersonalizedAdsOption().withNonPersonalizedAdsOption().build() form.load() form.show() } else { saveConsentStatus(consentStatus) } } } override fun onFailedToUpdateConsentInfo(errorDescription: String) { Timber.d("User's consent status failed to update: $errorDescription") } }) } private fun saveConsentStatus(consentStatus: ConsentStatus?) { PreferenceManager.getDefaultSharedPreferences(applicationContext) .edit { putString(KEY_CONSENT_STATUS, consentStatus?.toString()) } } private fun resolveNavigationToFragment(savedInstanceState: Bundle?) { if (intent != null) { val destinationFragment = intent.getStringExtra(EXTRA_TARGET_FRAGMENT) when { destinationFragment != null -> when { "BookReleaseFragment".equals( destinationFragment, ignoreCase = true ) -> navController.navigate(R.id.bookReleaseFragment) "ProfileFragment".equals( destinationFragment, ignoreCase = true ) -> navController.navigate(R.id.profileFragment) "MapsFragment".equals( destinationFragment, ignoreCase = true ) -> navController.navigate(R.id.mapsFragment) } savedInstanceState != null -> navController.restoreState( savedInstanceState.getBundle( "navHostState" ) ) } } } override fun onMenuItemClick(item: MenuItem): Boolean { return when (item.itemId) { R.id.menu_action_search -> { findNavController(R.id.nav_host_fragment).navigate(R.id.searchFragment) item.expandActionView() true } R.id.menu_action_logout -> { AuthUI.getInstance().signOut(this).addOnCompleteListener { finish() } true } else -> false } } override fun onBookSelected(bookKey: String) { val bookActivityArgs = bundleOf(EXTRA_KEY to bookKey) val extras = ActivityNavigatorExtras(ActivityOptionsCompat.makeSceneTransitionAnimation(this)) findNavController(R.id.nav_host_fragment).navigate( R.id.bookActivity, bookActivityArgs, null, extras ) } override fun onBookReleased(bookKey: String) { findNavController(R.id.nav_host_fragment).popBackStack() onBookSelected(bookKey) } override fun onBookAdd() { findNavController(R.id.nav_host_fragment).navigate(R.id.bookReleaseFragment) } }
apache-2.0
af323ef415a5030cb6f2edb694545770
34.857143
98
0.715575
4.823629
false
false
false
false
AlmasB/FXGL
fxgl-entity/src/main/kotlin/com/almasb/fxgl/entity/components/TypeComponent.kt
1
1435
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.entity.components import com.almasb.fxgl.core.serialization.Bundle import com.almasb.fxgl.entity.component.CoreComponent import com.almasb.fxgl.entity.component.SerializableComponent import java.io.Serializable /** * Represents an entity type. * * @author Almas Baimagambetov (AlmasB) ([email protected]) */ @CoreComponent class TypeComponent /** * Constructs a component with given type. * Note: although the type could be any object, it is recommended * that an enum is used to represent types. * * @param type entity type */ @JvmOverloads constructor(type: Serializable = SObject()) : ObjectComponent<Serializable>(type), SerializableComponent { /** * @param type entity type * @return true iff this type component is of given type */ fun isType(type: Any) = value == type override fun toString() = "Type($value)" override fun write(bundle: Bundle) { bundle.put("value", value) } override fun read(bundle: Bundle) { value = bundle.get("value") } private class SObject : Serializable { override fun toString() = "NONE" companion object { private const val serialVersionUID = -1L } } override fun isComponentInjectionRequired(): Boolean = false }
mit
43bdf6787005215e1ae21b6d7276d37e
24.642857
120
0.686411
4.171512
false
false
false
false
joseph-roque/BowlingCompanion
app/src/main/java/ca/josephroque/bowlingcompanion/statistics/list/StatisticsListFragment.kt
1
2346
package ca.josephroque.bowlingcompanion.statistics.list import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import ca.josephroque.bowlingcompanion.R import ca.josephroque.bowlingcompanion.common.fragments.ListFragment import ca.josephroque.bowlingcompanion.common.interfaces.IIdentifiable import ca.josephroque.bowlingcompanion.statistics.unit.StatisticsUnit import kotlinx.coroutines.experimental.CommonPool import kotlinx.coroutines.experimental.Deferred import kotlinx.coroutines.experimental.async /** * Copyright (C) 2018 Joseph Roque * * A fragment which displays the stats of a [StatisticsUnit] in a list. */ class StatisticsListFragment : ListFragment<StatisticListItem, StatisticsRecyclerViewAdapter>() { companion object { @Suppress("unused") private const val TAG = "StatisticsListFragment" private const val ARG_UNIT = "${TAG}_unit" fun newInstance(unit: StatisticsUnit): StatisticsListFragment { return StatisticsListFragment().apply { arguments = Bundle().apply { putParcelable(ARG_UNIT, unit) } } } } override val emptyViewImage = R.drawable.empty_view_statistics override val emptyViewText = R.string.empty_view_statistics private lateinit var unit: StatisticsUnit // MARK: Lifecycle functions override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { unit = arguments?.getParcelable(ARG_UNIT)!! return super.onCreateView(inflater, container, savedInstanceState) } override fun onStop() { super.onStop() unit.clearCache() } // MARK: BaseFragment override fun updateToolbarTitle() { // Intentionally left blank } // MARK: ListFragment override fun buildAdapter(): StatisticsRecyclerViewAdapter { return StatisticsRecyclerViewAdapter(emptyList(), this) } override fun fetchItems(): Deferred<MutableList<StatisticListItem>> { context?.let { return unit.getStatistics(it) } return async(CommonPool) { mutableListOf<StatisticListItem>() } } } /** An item to display in the list of statistics. */ interface StatisticListItem : IIdentifiable
mit
97b7289285a8218c1cee3168ff9f9cf6
29.868421
116
0.716539
5.111111
false
false
false
false
commons-app/apps-android-commons
app/src/main/java/fr/free/nrw/commons/customselector/database/UploadedStatus.kt
5
812
package fr.free.nrw.commons.customselector.database import androidx.room.Entity import androidx.room.Index import androidx.room.PrimaryKey import java.util.* /** * Entity class for Uploaded Status. */ @Entity(tableName = "uploaded_table", indices = [Index(value = ["modifiedImageSHA1"], unique = true)]) data class UploadedStatus( /** * Original image sha1. */ @PrimaryKey val imageSHA1 : String, /** * Modified image sha1 (after exif changes). */ val modifiedImageSHA1 : String, /** * imageSHA1 query result from API. */ var imageResult : Boolean, /** * modifiedImageSHA1 query result from API. */ var modifiedImageResult : Boolean, /** * lastUpdated for data validation. */ var lastUpdated : Date? = null )
apache-2.0
ea81030215fec163285873e3fa72c1ca
19.820513
102
0.644089
4.06
false
false
false
false
ajalt/clikt
clikt/src/commonMain/kotlin/com/github/ajalt/clikt/parameters/internal/NullableLateinit.kt
1
1044
package com.github.ajalt.clikt.parameters.internal import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty /** * A container for a value that is initialized after the container is created. * * Similar to a lateinit variable, but allows nullable types. If the value is not set before * being read, it will return null if T is nullable, or throw an IllegalStateException otherwise. */ internal class NullableLateinit<T>(private val errorMessage: String) : ReadWriteProperty<Any, T> { private object UNINITIALIZED private var value: Any? = UNINITIALIZED override fun getValue(thisRef: Any, property: KProperty<*>): T { if (value === UNINITIALIZED) throw IllegalStateException(errorMessage) try { @Suppress("UNCHECKED_CAST") return value as T } catch (e: ClassCastException) { throw IllegalStateException(errorMessage) } } override fun setValue(thisRef: Any, property: KProperty<*>, value: T) { this.value = value } }
apache-2.0
923f4ef6ed881484a74f3a565353050f
32.677419
98
0.698276
4.81106
false
false
false
false
ujpv/intellij-rust
src/main/kotlin/org/rust/ide/idea/RustModuleType.kt
1
743
package org.rust.ide.idea import com.intellij.openapi.module.ModuleType import com.intellij.openapi.module.ModuleTypeManager import org.rust.ide.icons.RustIcons import javax.swing.Icon class RustModuleType : ModuleType<RustModuleBuilder>(ID) { override fun getNodeIcon(isOpened: Boolean): Icon = RustIcons.RUST override fun createModuleBuilder(): RustModuleBuilder = RustModuleBuilder() override fun getDescription(): String = "Rust module" override fun getName(): String = "Rust" override fun getBigIcon(): Icon = RustIcons.RUST_BIG companion object { private val ID = "RUST_MODULE" val INSTANCE: RustModuleType by lazy { ModuleTypeManager.getInstance().findByID(ID) as RustModuleType } } }
mit
482a9699c82e73a26c712840d7d551e2
31.304348
111
0.748318
4.370588
false
false
false
false
sdeleuze/reactor-core
reactor-core/src/test/kotlin/reactor/util/function/TupleExtensionsTests.kt
1
2649
/* * Copyright (c) 2011-2017 Pivotal Software Inc, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package reactor.util.function import org.junit.Assert.assertEquals import org.junit.Test object O1; object O2; object O3; object O4 object O5; object O6; object O7; object O8 class TupleDestructuringTests { @Test fun destructureTuple2() { val (t1, t2) = Tuples.of(O1, O2) assertEquals(t1, O1) assertEquals(t2, O2) } @Test fun destructureTuple3() { val (t1, t2, t3) = Tuples.of(O1, O2, O3) assertEquals(t1, O1) assertEquals(t2, O2) assertEquals(t3, O3) } @Test fun destructureTuple4() { val (t1, t2, t3, t4) = Tuples.of(O1, O2, O3, O4) assertEquals(t1, O1) assertEquals(t2, O2) assertEquals(t3, O3) assertEquals(t4, O4) } @Test fun destructureTuple5() { val (t1, t2, t3, t4, t5) = Tuples.of(O1, O2, O3, O4, O5) assertEquals(t1, O1) assertEquals(t2, O2) assertEquals(t3, O3) assertEquals(t4, O4) assertEquals(t5, O5) } @Test fun destructureTuple6() { val (t1, t2, t3, t4, t5, t6) = Tuples.of(O1, O2, O3, O4, O5, O6) assertEquals(t1, O1) assertEquals(t2, O2) assertEquals(t3, O3) assertEquals(t4, O4) assertEquals(t5, O5) assertEquals(t6, O6) } @Test fun destructureTuple7() { val (t1, t2, t3, t4, t5, t6, t7) = Tuples.of(O1, O2, O3, O4, O5, O6, O7) assertEquals(t1, O1) assertEquals(t2, O2) assertEquals(t3, O3) assertEquals(t4, O4) assertEquals(t5, O5) assertEquals(t6, O6) assertEquals(t7, O7) } @Test fun destructureTuple8() { val (t1, t2, t3, t4, t5, t6, t7, t8) = Tuples.of(O1, O2, O3, O4, O5, O6, O7, O8) assertEquals(t1, O1) assertEquals(t2, O2) assertEquals(t3, O3) assertEquals(t4, O4) assertEquals(t5, O5) assertEquals(t6, O6) assertEquals(t7, O7) assertEquals(t8, O8) } }
apache-2.0
67cae7206b2bc0be81ccc8e83be69864
26.59375
88
0.597206
2.943333
false
true
false
false
christophpickl/gadsu
src/main/kotlin/at/cpickl/gadsu/app.kt
1
5680
package at.cpickl.gadsu import at.cpickl.gadsu.development.Development import at.cpickl.gadsu.development.ShowDevWindowEvent import at.cpickl.gadsu.global.AppStartupEvent import at.cpickl.gadsu.global.GADSU_DIRECTORY import at.cpickl.gadsu.global.GadsuSystemProperty import at.cpickl.gadsu.global.GlobalExceptionHandler import at.cpickl.gadsu.global.QuitAskEvent import at.cpickl.gadsu.global.QuitEvent import at.cpickl.gadsu.persistence.GADSU_DATABASE_DIRECTORY import at.cpickl.gadsu.preferences.Prefs import at.cpickl.gadsu.preferences.ShowPreferencesEvent import at.cpickl.gadsu.service.GADSU_LOG_FILE import at.cpickl.gadsu.service.LogConfigurator import at.cpickl.gadsu.service.MetaInf import at.cpickl.gadsu.start.Args import at.cpickl.gadsu.start.ArgsActionException import at.cpickl.gadsu.start.ArgsActionExecutor import at.cpickl.gadsu.start.GadsuModule import at.cpickl.gadsu.start.parseArgsOrHelp import at.cpickl.gadsu.view.MacHandler import at.cpickl.gadsu.view.MainFrame import at.cpickl.gadsu.view.ShowAboutDialogEvent import com.github.christophpickl.kpotpourri.common.logging.LOG import com.google.common.eventbus.EventBus import com.google.common.net.HostAndPort import com.google.inject.Guice import java.util.Arrays import javax.inject.Inject import javax.swing.SwingUtilities /** * This name will also show up in the native mac app, so dont rename that class. */ object Gadsu { private val log = LOG {} @JvmStatic fun main(cliArgs: Array<String>) { val args = parseArgsOrHelp(cliArgs, false) ?: return initLogging(args.debug) initSwingLookAndFeel() try { start(args) } catch (e: ArgsActionException) { log.error("Invalid CLI arguments! " + Arrays.toString(cliArgs), e) System.err.println("You entered an invalid CLI argument: '" + Arrays.toString(cliArgs) + "'! Exception message: " + e.message) } } private fun initLogging(debug: Boolean) { if (GadsuSystemProperty.disableLog.isEnabledOrFalse()) { println("Gadsu log configuration disabled. (most likely because tests come with own log config)") } else { LogConfigurator(debug).configureLog() } } private fun start(args: Args) { log.info("************************************************************************************************") log.info("************************************************************************************************") log.info("************************************************************************************************") GlobalExceptionHandler.register() log.debug("====> GUICE START") val guice = Guice.createInjector(GadsuModule(args)) log.debug("====> GUICE END") if (args.action != null) { log.info("User requested to start custom action '{}'.", args.action) guice.getInstance(ArgsActionExecutor::class.java).execute(args.action) guice.getInstance(EventBus::class.java).post(QuitEvent()) return } val app = guice.getInstance(GadsuGuiceStarter::class.java) GlobalExceptionHandler.mainFrame = guice.getInstance(MainFrame::class.java).asJFrame() app.start() } } class GadsuGuiceStarter @Inject constructor( private val frame: MainFrame, private val bus: EventBus, private val mac: MacHandler, private val mainFrame: MainFrame, private val prefs: Prefs, private val metaInf: MetaInf ) { private val log = LOG {} fun start() { logInfo() enableProxy() registerMacHandler() SwingUtilities.invokeLater { bus.post(AppStartupEvent()) frame.start() if (Development.ENABLED) { if (Development.SHOW_DEV_WINDOW_AT_STARTUP) { bus.post(ShowDevWindowEvent()) mainFrame.requestFocus() } } } } private fun enableProxy() { if (prefs.preferencesData.proxy != null) { val proxy = prefs.preferencesData.proxy!! val hostAndPort = HostAndPort.fromString(proxy).withDefaultPort(8080) log.info("Enabling proxy: '{}'", hostAndPort) System.setProperty("http.proxyHost", hostAndPort.host) System.setProperty("http.proxyPort", hostAndPort.port.toString()) System.setProperty("https.proxyHost", hostAndPort.host) System.setProperty("https.proxyPort", hostAndPort.port.toString()) } } private fun logInfo() { log.info("") log.info("") log.info { """ _____ _ / ____| | | | | __ __ _ __| | ___ _ _ | | |_ | / _` | / _` |/ __|| | | | | |__| || (_| || (_| |\__ \| |_| | \_____| \__,_| \__,_||___/ \__,_| v${metaInf.applicationVersion.toLabel()} -==================================================================- Gadsu directory: ${GADSU_DIRECTORY.absolutePath} Database directory: ${GADSU_DATABASE_DIRECTORY.absolutePath} Log file: ${GADSU_LOG_FILE.absolutePath} -==================================================================- """ } } private fun registerMacHandler() { if (!mac.isEnabled()) { log.debug("registerMacHandler() not enabled") return } log.debug("Enabling mac specific handlers.") mac.registerAbout { bus.post(ShowAboutDialogEvent()) } mac.registerPreferences { bus.post(ShowPreferencesEvent()) } mac.registerQuit { bus.post(QuitAskEvent()) } } }
apache-2.0
58ec5c6b223169cc68b968bf40409843
34.5
138
0.590845
4.359171
false
false
false
false
gatheringhallstudios/MHGenDatabase
app/src/main/java/com/ghstudios/android/data/classes/Monster.kt
1
668
package com.ghstudios.android.data.classes import com.ghstudios.android.ITintedIcon import com.ghstudios.android.mhgendatabase.R /* * Class for Monster */ class Monster : ITintedIcon { /* Getters and Setters */ var id: Long = -1 // Monster id var name = "" // Monster name var jpnName = "" // Japanese name var monsterClass = MonsterClass.LARGE var fileLocation = "" // File location for image /** * Bitwise flags assembled as an integer. * flags are hasLR/hasHR/hasG */ var metadata = 0 override fun getIconResourceString(): String { return fileLocation } }
mit
265768a5602a9a3307945b9cb7302088
21.266667
55
0.621257
4.175
false
false
false
false
simonorono/pradera_baja
asistencia/src/main/kotlin/pb/asistencia/controller/Asistencia.kt
1
2755
/* * Copyright 2016 Simón Oroñ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 pb.asistencia.controller import javafx.event.ActionEvent import javafx.fxml.FXML import javafx.scene.control.TextField import javafx.scene.input.KeyCode import javafx.scene.input.KeyEvent import pb.asistencia.data.DB import pb.asistencia.data.Persona import pb.asistencia.data.TipoEvento import pb.common.gui.Message import pb.common.date.formatDateTime import java.time.LocalDateTime @Suppress("UNUSED_PARAMETER") class Asistencia { @FXML var cedula: TextField? = null @FXML fun markClick(event: ActionEvent) { determinar(cedula!!.text); } @FXML public fun keyPressedCedula(event: KeyEvent) { if (event.code == KeyCode.ENTER) { determinar(cedula!!.text) } } private fun isValidCedula(c: String): Boolean { try { Integer.parseInt(c); return true; } catch (e: NumberFormatException) { return false; } } private fun determinar(c: String) { if (isValidCedula(c)) { val persona = DB.getPersonaByCedula(c.toInt()) if (persona != null) { if (DB.marcoEvento(persona.getId(), TipoEvento.ENTRADA)) { if (DB.marcoEvento(persona.getId(), TipoEvento.SALIDA)) { Message.error("Su turno ya ha cerrado") } else { marcar(persona, TipoEvento.SALIDA) } } else { marcar(persona, TipoEvento.ENTRADA) } } else { Message.error("La cédula no está registrada") } } else { Message.error("La cédula es invalida"); } cedula!!.clear() cedula!!.requestFocus() } private fun marcar(persona: Persona, tipo: TipoEvento) { val now = LocalDateTime.now() DB.marcarEvento(now, tipo, persona.getId()) val evento = when (tipo) { TipoEvento.ENTRADA -> "Entrada" TipoEvento.SALIDA -> "Salida" } Message.info("$evento marcada: $persona (${now.formatDateTime()})") } }
apache-2.0
801ab2423342fbb6502b87349aa7f736
28.569892
77
0.607273
3.846154
false
false
false
false
luoyuan800/NeverEnd
server_core/src/cn/luo/yuan/maze/server/persistence/ShopTable.kt
1
5090
package cn.luo.yuan.maze.server.persistence import cn.luo.yuan.maze.model.Accessory import cn.luo.yuan.maze.model.Element import cn.luo.yuan.maze.model.SellItem import cn.luo.yuan.maze.model.goods.Goods import cn.luo.yuan.serialize.FileObjectTable import cn.luo.yuan.maze.server.LogHelper import cn.luo.yuan.maze.persistence.DatabaseConnection import cn.luo.yuan.maze.utils.Random import java.io.File import java.sql.Connection import java.sql.Statement /** * Copyright @Luo * Created by Gavin Luo on 7/13/2017. */ class ShopTable(private val database: DatabaseConnection, fileRoot: File) { private var accessoryDb: FileObjectTable<Accessory>? = null private val random = Random(System.currentTimeMillis()) init { initIfNeed() accessoryDb = FileObjectTable(Accessory::class.java, fileRoot) } private fun initIfNeed() { var statement: Statement? = null var connection: Connection? = null try { connection = database.getConnection() statement = connection.createStatement() statement.execute("CREATE TABLE IF NOT EXISTS `shop` ( `id` VARCHAR(100) NOT NULL, `type` VARCHAR(100) NOT NULL, `cost` INTEGER UNSIGNED DEFAULT 0, `count` INTEGER UNSIGNED DEFAULT 0, `sold` INTEGER UNSIGNED DEFAULT 0, `on_sell` TINYINT UNSIGNED DEFAULT 0, `ref` VARCHAR(255), `special` TINYINT UNSIGNED DEFAULT 0, PRIMARY KEY (`id`)) ENGINE = InnoDB;") } catch (e: Exception) { LogHelper.error(e) } finally { statement?.close() connection?.close() } } fun getAllSelling(): List<SellItem> { var con: Connection? = null var stat: Statement? = null val list = mutableListOf<SellItem>() try { con = database.getConnection() stat = con.createStatement() val s = "select * from shop where on_sell = 1 and count > 0" LogHelper.debug("execute sql : " + s); val rs = stat.executeQuery(s); LogHelper.debug("sql return result: " + rs.row) while (rs.next() && list.size < 15) { val type = rs.getString("type") val sellItem = SellItem() sellItem.id = rs.getString("id") sellItem.price = rs.getLong("cost") sellItem.special = rs.getBoolean("special") when (type) { "goods" -> { val ins = Class.forName(rs.getString("ref")).newInstance() (ins as Goods).setCount(1) ins.price = sellItem.price sellItem.count = 4 sellItem.instance = ins sellItem.desc = ins.desc sellItem.type = "物品" sellItem.name = ins.name list.add(sellItem) } "accessory" -> { if (random.nextBoolean()) { val acc = accessoryDb!!.loadObject(rs.getString("ref")) if (acc != null) { acc.element = random.randomItem(Element.values()) sellItem.count = 1; sellItem.instance = acc sellItem.color = acc.color sellItem.author = acc.author sellItem.desc = acc.desc sellItem.effects = acc.effects sellItem.type = acc.type sellItem.name = acc.displayName list.add(sellItem) } } } } LogHelper.debug("return shop item result: " + list) } } finally { stat?.close() con?.close() } return list } fun sell(item: SellItem) { val conn = database.getConnection() val stat = conn.createStatement() stat.execute("update shop set count = count - " + item.count + ", sold = sold + " + item.count + " where id = '" + item.id + "'") stat.close() conn.close() } fun add(item: Any) { val conn = database.getConnection() try { when (item) { is Accessory -> { accessoryDb?.save(item) val state = conn.prepareStatement("insert into shop(id, type, cost, count,ref) values(?,?,?,?,?)") state.setString(1, item.id) state.setString(2, "accessory") state.setLong(3, 1000000) state.setLong(4, 100) state.setString(5, item.id) state.execute() state.close() } } } catch (e: Exception) { LogHelper.error(e) } conn.close() } }
bsd-3-clause
1281d166c9c5981ae044199fae9fa0cc
38.123077
365
0.502556
4.632058
false
false
false
false
spark/photon-tinker-android
app/src/main/java/io/particle/android/sdk/utils/Snackbars.kt
1
1425
package io.particle.android.sdk.utils import android.app.Activity import android.view.View import android.view.ViewGroup import androidx.annotation.StringRes import com.google.android.material.snackbar.BaseTransientBottomBar.Behavior import com.google.android.material.snackbar.Snackbar import io.particle.commonui.dpToPx enum class SnackbarDuration(val intVal: Int) { LENGTH_SHORT(-1), LENGTH_LONG(0), LENGTH_INDEFINITE(-2) } fun View?.snackbar( message: CharSequence, duration: SnackbarDuration = SnackbarDuration.LENGTH_SHORT ) { if (this == null) { return } val snackbar = Snackbar.make(this, message, duration.intVal) // set elevation to ensure we actually display above all other views snackbar.view.elevation = dpToPx(12, this.context).toFloat() snackbar.show() } fun Activity?.snackbarInRootView( message: CharSequence, duration: SnackbarDuration = SnackbarDuration.LENGTH_SHORT ) { if (this == null) { return } val contentRoot = (this.findViewById(android.R.id.content) as ViewGroup) val myRoot = contentRoot.getChildAt(0) Snackbar.make(myRoot, message, duration.intVal).show() } fun Activity?.snackbarInRootView( @StringRes messageId: Int, duration: SnackbarDuration = SnackbarDuration.LENGTH_SHORT ) { if (this == null) { return } this.snackbarInRootView(getString(messageId), duration) }
apache-2.0
72fce328e6c579de170c5a5a606bf3dc
25.388889
76
0.724211
4.036827
false
false
false
false
fluttercommunity/plus_plugins
packages/network_info_plus/network_info_plus/android/src/main/kotlin/dev/fluttercommunity/plus/network_info/NetworkInfoPlusPlugin.kt
1
1671
package dev.fluttercommunity.plus.network_info import android.content.Context import android.net.ConnectivityManager import android.net.wifi.WifiManager import android.os.Build import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding import io.flutter.plugin.common.BinaryMessenger import io.flutter.plugin.common.MethodChannel /** NetworkInfoPlusPlugin */ class NetworkInfoPlusPlugin : FlutterPlugin { private lateinit var methodChannel: MethodChannel override fun onAttachedToEngine(binding: FlutterPluginBinding) { setupChannels(binding.binaryMessenger, binding.applicationContext) } override fun onDetachedFromEngine(binding: FlutterPluginBinding) { methodChannel.setMethodCallHandler(null) } private fun setupChannels(messenger: BinaryMessenger, context: Context) { methodChannel = MethodChannel(messenger, CHANNEL) val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager var connectivityManager: ConnectivityManager? = null if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { connectivityManager = context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager } val networkInfo = NetworkInfo(wifiManager, connectivityManager) val methodChannelHandler = NetworkInfoMethodChannelHandler(networkInfo) methodChannel.setMethodCallHandler(methodChannelHandler) } companion object { private const val CHANNEL = "dev.fluttercommunity.plus/network_info" } }
bsd-3-clause
43bfeacfe2d31d6bad83d826604ad06b
37.860465
130
0.774387
5.141538
false
false
false
false
facebook/litho
litho-coroutines-kotlin/src/test/kotlin/com/facebook/litho/UseCoroutineTest.kt
1
9760
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.litho import androidx.test.ext.junit.runners.AndroidJUnit4 import com.facebook.litho.testing.LithoViewRule import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.test.TestCoroutineDispatcher import kotlinx.coroutines.test.setMain import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith /** Unit tests for [useCoroutine]. */ @OptIn(ExperimentalCoroutinesApi::class) @RunWith(AndroidJUnit4::class) class UseCoroutineTest { @Rule @JvmField val lithoViewRule = LithoViewRule() private val testDispatcher = TestCoroutineDispatcher() @Before fun setUp() { testDispatcher.pauseDispatcher() Dispatchers.setMain(testDispatcher) } @Test fun `coroutine is launched and canceled`() { val useCoroutineCalls = mutableListOf<String>() class UseCoroutineComponent : KComponent() { override fun ComponentScope.render(): Component { useCoroutine { useCoroutineCalls += "launch" try { awaitCancellation() } finally { useCoroutineCalls += "cancel" } } return Row() } } val lithoView = lithoViewRule.render { UseCoroutineComponent() } testDispatcher.runCurrent() lithoView.detachFromWindow().release() testDispatcher.runCurrent() assertThat(useCoroutineCalls).containsExactly("launch", "cancel") } @Test fun `coroutine restarted on each update`() { val useCoroutineCalls = mutableListOf<String>() class UseCoroutineComponent(val seq: Int) : KComponent() { override fun ComponentScope.render(): Component { useCoroutine { useCoroutineCalls += "attach $seq" try { awaitCancellation() } finally { useCoroutineCalls += "detach $seq" } } return Row() } } val lithoView = lithoViewRule.render { UseCoroutineComponent(seq = 0) } testDispatcher.runCurrent() assertThat(useCoroutineCalls).containsExactly("attach 0") useCoroutineCalls.clear() lithoView.setRoot(UseCoroutineComponent(seq = 1)) testDispatcher.runCurrent() assertThat(useCoroutineCalls).containsExactly("detach 0", "attach 1") useCoroutineCalls.clear() lithoView.release() testDispatcher.runCurrent() assertThat(useCoroutineCalls).containsExactly("detach 1") } @Test fun `coroutine only restarted if dependency changes`() { val useCoroutineCalls = mutableListOf<String>() class UseCoroutineComponent(val dep: Int, val seq: Int) : KComponent() { override fun ComponentScope.render(): Component { useCoroutine(dep) { useCoroutineCalls += "attach $seq" try { awaitCancellation() } finally { useCoroutineCalls += "detach $seq" } } return Row() } } val lithoView = lithoViewRule.render { UseCoroutineComponent(dep = 0, seq = 0) } testDispatcher.runCurrent() assertThat(useCoroutineCalls).containsExactly("attach 0") useCoroutineCalls.clear() lithoView.setRoot(UseCoroutineComponent(dep = 0, seq = 1)) testDispatcher.runCurrent() assertThat(useCoroutineCalls).isEmpty() useCoroutineCalls.clear() lithoView.setRoot(UseCoroutineComponent(dep = 1, seq = 2)) testDispatcher.runCurrent() assertThat(useCoroutineCalls).containsExactly("detach 0", "attach 2") useCoroutineCalls.clear() lithoView.release() testDispatcher.runCurrent() assertThat(useCoroutineCalls).containsExactly("detach 2") } @Test fun `coroutine only restarts if nullable dependency changes`() { val useCoroutineCalls = mutableListOf<String>() class UseCoroutineComponent(val dep: Int?, val seq: Int) : KComponent() { override fun ComponentScope.render(): Component { useCoroutine(dep) { useCoroutineCalls += "attach $seq" try { awaitCancellation() } finally { useCoroutineCalls += "detach $seq" } } return Row() } } val lithoView = lithoViewRule.render { UseCoroutineComponent(dep = null, seq = 0) } testDispatcher.runCurrent() assertThat(useCoroutineCalls).containsExactly("attach 0") useCoroutineCalls.clear() lithoView.setRoot(UseCoroutineComponent(dep = null, seq = 1)) testDispatcher.runCurrent() assertThat(useCoroutineCalls).isEmpty() useCoroutineCalls.clear() lithoView.setRoot(UseCoroutineComponent(dep = 1, seq = 2)) testDispatcher.runCurrent() assertThat(useCoroutineCalls).containsExactly("detach 0", "attach 2") useCoroutineCalls.clear() lithoView.setRoot(UseCoroutineComponent(dep = null, seq = 3)) testDispatcher.runCurrent() assertThat(useCoroutineCalls).containsExactly("detach 2", "attach 3") useCoroutineCalls.clear() lithoView.release() testDispatcher.runCurrent() assertThat(useCoroutineCalls).containsExactly("detach 3") } @Test fun `coroutine only restarts if any dependency changes`() { val useCoroutineCalls = mutableListOf<String>() class UseCoroutineComponent( val dep1: Int, val dep2: Int, val seq: Int, ) : KComponent() { override fun ComponentScope.render(): Component { useCoroutine(dep1, dep2) { useCoroutineCalls += "attach $dep1:$dep2:$seq" try { awaitCancellation() } finally { useCoroutineCalls += "detach $dep1:$dep2:$seq" } } return Row() } } val lithoView = lithoViewRule.render { UseCoroutineComponent(dep1 = 0, dep2 = 0, seq = 0) } testDispatcher.runCurrent() assertThat(useCoroutineCalls).containsExactly("attach 0:0:0") useCoroutineCalls.clear() lithoView.setRoot(UseCoroutineComponent(dep1 = 0, dep2 = 0, seq = 1)) testDispatcher.runCurrent() assertThat(useCoroutineCalls).isEmpty() useCoroutineCalls.clear() lithoView.setRoot(UseCoroutineComponent(dep1 = 0, dep2 = 1, seq = 2)) testDispatcher.runCurrent() assertThat(useCoroutineCalls).containsExactly("detach 0:0:0", "attach 0:1:2") useCoroutineCalls.clear() lithoView.setRoot(UseCoroutineComponent(dep1 = 1, dep2 = 1, seq = 3)) testDispatcher.runCurrent() assertThat(useCoroutineCalls).containsExactly("detach 0:1:2", "attach 1:1:3") useCoroutineCalls.clear() lithoView.setRoot(UseCoroutineComponent(dep1 = 2, dep2 = 2, seq = 4)) testDispatcher.runCurrent() assertThat(useCoroutineCalls).containsExactly("detach 1:1:3", "attach 2:2:4") useCoroutineCalls.clear() lithoView.release() testDispatcher.runCurrent() assertThat(useCoroutineCalls).containsExactly("detach 2:2:4") } @Test fun `multiple coroutines are launched independently`() { val useCoroutineCalls = mutableListOf<String>() class UseCoroutineComponent(val dep1: Int, val dep2: Int, val dep3: Int, val seq: Int) : KComponent() { override fun ComponentScope.render(): Component? { useCoroutine(dep1) { useCoroutineCalls += "dep1: attach $seq" try { awaitCancellation() } finally { useCoroutineCalls += "dep1: detach $seq" } } useCoroutine(dep2) { useCoroutineCalls += "dep2: attach $seq" try { awaitCancellation() } finally { useCoroutineCalls += "dep2: detach $seq" } } useCoroutine(dep3) { useCoroutineCalls += "dep3: attach $seq" try { awaitCancellation() } finally { useCoroutineCalls += "dep3: detach $seq" } } return Row() } } val lithoView = lithoViewRule.render { UseCoroutineComponent(dep1 = 0, dep2 = 0, dep3 = 0, seq = 0) } testDispatcher.runCurrent() assertThat(useCoroutineCalls) .containsExactly("dep1: attach 0", "dep2: attach 0", "dep3: attach 0") useCoroutineCalls.clear() lithoView.setRoot(UseCoroutineComponent(dep1 = 0, dep2 = 1, dep3 = 0, seq = 1)) testDispatcher.runCurrent() assertThat(useCoroutineCalls).containsExactly("dep2: detach 0", "dep2: attach 1") useCoroutineCalls.clear() lithoView.setRoot(UseCoroutineComponent(dep1 = 1, dep2 = 1, dep3 = 1, seq = 2)) testDispatcher.runCurrent() assertThat(useCoroutineCalls) .containsExactly("dep1: detach 0", "dep1: attach 2", "dep3: detach 0", "dep3: attach 2") useCoroutineCalls.clear() lithoView.setRoot(UseCoroutineComponent(dep1 = 1, dep2 = 1, dep3 = 1, seq = 3)) testDispatcher.runCurrent() assertThat(useCoroutineCalls).isEmpty() useCoroutineCalls.clear() lithoView.release() testDispatcher.runCurrent() assertThat(useCoroutineCalls) .containsExactly("dep1: detach 2", "dep2: detach 1", "dep3: detach 2") } }
apache-2.0
4c52846bdd3f5afe0c011cc8f03722ec
29.030769
96
0.665676
4.410303
false
true
false
false
owncloud/android
owncloudApp/src/main/java/com/owncloud/android/presentation/viewmodels/settings/SettingsSecurityViewModel.kt
2
2924
/** * ownCloud Android client application * * @author Juan Carlos Garrote Gascón * * Copyright (C) 2021 ownCloud GmbH. * <p> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * <p> * 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. * <p> * 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.owncloud.android.presentation.viewmodels.settings import androidx.lifecycle.ViewModel import com.owncloud.android.R import com.owncloud.android.data.preferences.datasources.SharedPreferencesProvider import com.owncloud.android.enums.LockEnforcedType import com.owncloud.android.enums.LockEnforcedType.Companion.parseFromInteger import com.owncloud.android.presentation.ui.security.BiometricActivity import com.owncloud.android.presentation.ui.security.LockTimeout import com.owncloud.android.presentation.ui.security.passcode.PassCodeActivity import com.owncloud.android.presentation.ui.security.PatternActivity import com.owncloud.android.presentation.ui.settings.fragments.SettingsSecurityFragment import com.owncloud.android.providers.MdmProvider import com.owncloud.android.providers.MdmProvider.Companion.NO_MDM_RESTRICTION_YET import com.owncloud.android.utils.CONFIGURATION_LOCK_DELAY_TIME class SettingsSecurityViewModel( private val preferencesProvider: SharedPreferencesProvider, private val mdmProvider: MdmProvider, ) : ViewModel() { fun isPatternSet() = preferencesProvider.getBoolean(PatternActivity.PREFERENCE_SET_PATTERN, false) fun isPasscodeSet() = preferencesProvider.getBoolean(PassCodeActivity.PREFERENCE_SET_PASSCODE, false) fun setPrefLockAccessDocumentProvider(value: Boolean) = preferencesProvider.putBoolean(SettingsSecurityFragment.PREFERENCE_LOCK_ACCESS_FROM_DOCUMENT_PROVIDER, value) fun setPrefTouchesWithOtherVisibleWindows(value: Boolean) = preferencesProvider.putBoolean(SettingsSecurityFragment.PREFERENCE_TOUCHES_WITH_OTHER_VISIBLE_WINDOWS, value) fun getBiometricsState(): Boolean = preferencesProvider.getBoolean(BiometricActivity.PREFERENCE_SET_BIOMETRIC, false) fun isSecurityEnforcedEnabled() = parseFromInteger(mdmProvider.getBrandingInteger(NO_MDM_RESTRICTION_YET, R.integer.lock_enforced)) != LockEnforcedType.DISABLED fun isLockDelayEnforcedEnabled() = LockTimeout.parseFromInteger( mdmProvider.getBrandingInteger( mdmKey = CONFIGURATION_LOCK_DELAY_TIME, integerKey = R.integer.lock_delay_enforced ) ) != LockTimeout.DISABLED }
gpl-2.0
17e13adefd6ed344e0d244e64e7d81cc
45.396825
134
0.79781
4.343239
false
false
false
false
jdinkla/groovy-java-ray-tracer
src/main/kotlin/net/dinkla/raytracer/samplers/Hammersley.kt
1
693
package net.dinkla.raytracer.samplers import net.dinkla.raytracer.math.Point2D class Hammersley : IGenerator { protected fun phi(ij: Int): Double { var j = ij var x = 0.0 var f = 0.5 while (j > 0) { x += f * (j % 2) j /= 2 f *= 0.5 } return x } override fun generateSamples(numSamples: Int, numSets: Int, samples: MutableList<Point2D>) { for (p in 0 until numSets) { for (j in 0 until numSamples) { val pv = Point2D(j.toDouble() / numSamples.toDouble(), phi(j)) samples.add(pv) } } } }
apache-2.0
77f1819d33f67cf4b82e4460ef0c4c34
21.896552
96
0.47619
3.871508
false
false
false
false
tmarsteel/compiler-fiddle
src/compiler/ast/type/TypeReference.kt
1
2146
/* * Copyright 2018 Tobias Marstaller * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. */ package compiler.ast.type import compiler.binding.context.CTContext import compiler.binding.type.BaseTypeReference import compiler.lexer.IdentifierToken open class TypeReference( val declaredName: String, val isNullable: Boolean, open val modifier: TypeModifier? = null, val isInferred: Boolean = false, val declaringNameToken: IdentifierToken? = null ) { constructor(declaringNameToken: IdentifierToken, isNullable: Boolean, modifier: TypeModifier? = null, isInferred: Boolean = false) : this(declaringNameToken.value, isNullable, modifier, isInferred, declaringNameToken) open fun modifiedWith(modifier: TypeModifier): TypeReference { // TODO: implement type modifiers return TypeReference(declaredName, isNullable, modifier) } open fun nonNull(): TypeReference = TypeReference(declaredName, false, modifier, isInferred, declaringNameToken) open fun nullable(): TypeReference = TypeReference(declaredName, true, modifier, isInferred, declaringNameToken); open fun asInferred(): TypeReference = TypeReference(declaredName, isNullable, modifier, true, declaringNameToken) open fun resolveWithin(context: CTContext): BaseTypeReference? { val baseType = context.resolveAnyType(this) return if (baseType != null) BaseTypeReference(this, context, baseType) else null } }
lgpl-3.0
ec15903c60c7343a6910baf2f1d92c5d
41.94
134
0.754893
4.665217
false
false
false
false
Ekito/koin
koin-projects/koin-core/src/test/java/org/koin/dsl/BeanDefinitionTest.kt
1
3834
package org.koin.dsl import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test import org.koin.Simple import org.koin.core.definition.Definitions import org.koin.core.definition.Kind import org.koin.core.definition.Options import org.koin.core.instance.InstanceContext import org.koin.core.parameter.emptyParametersHolder import org.koin.core.qualifier.named import org.koin.test.getBeanDefinition import org.koin.test.getInstanceFactory class BeanDefinitionTest { val koin = koinApplication { }.koin val rootScope = koin._scopeRegistry.rootScope @Test fun `equals definitions`() { val def1 = Definitions.createSingle( definition = { Simple.ComponentA() }, scopeQualifier = rootScope._scopeDefinition.qualifier, options = Options() ) val def2 = Definitions.createSingle( definition = { Simple.ComponentA() }, scopeQualifier = rootScope._scopeDefinition.qualifier, options = Options() ) assertEquals(def1, def2) } @Test fun `scope definition`() { val def1 = Definitions.createSingle( definition = { Simple.ComponentA() }, scopeQualifier = rootScope._scopeDefinition.qualifier, options = Options() ) assertEquals(rootScope._scopeDefinition.qualifier, def1.scopeQualifier) assertEquals(Kind.Single, def1.kind) assertEquals(rootScope._scopeDefinition.qualifier, def1.scopeQualifier) } @Test fun `equals definitions - but diff kind`() { val def1 = Definitions.createSingle( definition = { Simple.ComponentA() }, scopeQualifier = rootScope._scopeDefinition.qualifier, options = Options() ) val def2 = Definitions.createSingle( definition = { Simple.ComponentA() }, scopeQualifier = rootScope._scopeDefinition.qualifier, options = Options() ) assertEquals(def1, def2) } @Test fun `definition kind`() { val app = koinApplication { modules( module { single { Simple.ComponentA() } factory { Simple.ComponentB(get()) } } ) } val defA = app.getBeanDefinition(Simple.ComponentA::class) ?: error("no definition found") assertEquals(Kind.Single, defA.kind) val defB = app.getBeanDefinition(Simple.ComponentB::class) ?: error("no definition found") assertEquals(Kind.Factory, defB.kind) } @Test fun `definition name`() { val name = named("A") val app = koinApplication { modules( module { single(name) { Simple.ComponentA() } factory { Simple.ComponentB(get()) } } ) } val defA = app.getBeanDefinition(Simple.ComponentA::class) ?: error("no definition found") assertEquals(name, defA.qualifier) val defB = app.getBeanDefinition(Simple.ComponentB::class) ?: error("no definition found") assertTrue(defB.qualifier == null) } @Test fun `definition function`() { val app = koinApplication { modules( module { single { Simple.ComponentA() } } ) } app.getBeanDefinition(Simple.ComponentA::class) ?: error("no definition found") val instance = app.getInstanceFactory(Simple.ComponentA::class)!!.get( InstanceContext( app.koin, rootScope, _parameters = { emptyParametersHolder() }) ) assertEquals(instance, app.koin.get<Simple.ComponentA>()) } }
apache-2.0
0514b3b501511f75c96046e9975a9044
30.694215
98
0.595462
4.959897
false
true
false
false
josesamuel/remoter
remoter/src/main/java/remoter/compiler/kbuilder/IntParamBuilder.kt
1
3456
package remoter.compiler.kbuilder import com.squareup.kotlinpoet.FunSpec import javax.lang.model.element.Element import javax.lang.model.element.ExecutableElement import javax.lang.model.element.VariableElement import javax.lang.model.type.TypeKind import javax.lang.model.type.TypeMirror /** * A [ParamBuilder] for int type parameters */ internal class IntParamBuilder(remoterInterfaceElement: Element, bindingManager: KBindingManager) : ParamBuilder(remoterInterfaceElement, bindingManager) { override fun writeParamsToProxy(param: VariableElement, paramType: ParamType, methodBuilder: FunSpec.Builder) { if (param.asType().kind == TypeKind.ARRAY) { if (paramType == ParamType.OUT) { writeArrayOutParamsToProxy(param, methodBuilder) } else { methodBuilder.addStatement("$DATA.writeIntArray(" + param.simpleName + ")") } } else { methodBuilder.addStatement("$DATA.writeInt(" + param.simpleName + ")") } } override fun readResultsFromStub(methodElement: ExecutableElement, resultType: TypeMirror, methodBuilder: FunSpec.Builder) { if (resultType.kind == TypeKind.ARRAY) { methodBuilder.addStatement("$REPLY.writeIntArray($RESULT)") } else { methodBuilder.addStatement("$REPLY.writeInt($RESULT)") } } override fun readResultsFromProxy(methodType: ExecutableElement, methodBuilder: FunSpec.Builder) { val resultMirror = methodType.getReturnAsTypeMirror() val resultType = methodType.getReturnAsKotlinType() if (resultMirror.kind == TypeKind.ARRAY) { val suffix = if (resultType.isNullable) "" else "!!" methodBuilder.addStatement("$RESULT = $REPLY.createIntArray()$suffix") } else { methodBuilder.addStatement("$RESULT = $REPLY.readInt()") } } override fun readOutResultsFromStub(param: VariableElement, paramType: ParamType, paramName: String, methodBuilder: FunSpec.Builder) { if (param.asType().kind == TypeKind.ARRAY) { methodBuilder.addStatement("$REPLY.writeIntArray($paramName)") } } override fun writeParamsToStub(methodType: ExecutableElement, param: VariableElement, paramType: ParamType, paramName: String, methodBuilder: FunSpec.Builder) { super.writeParamsToStub(methodType, param, paramType, paramName, methodBuilder) if (param.asType().kind == TypeKind.ARRAY) { if (paramType == ParamType.OUT) { writeOutParamsToStub(param, paramType, paramName, methodBuilder) } else { val suffix = if (param.isNullable()) "" else "!!" methodBuilder.addStatement("$paramName = $DATA.createIntArray()$suffix") } } else { methodBuilder.addStatement("$paramName = $DATA.readInt()") } } override fun readOutParamsFromProxy(param: VariableElement, paramType: ParamType, methodBuilder: FunSpec.Builder) { if (param.asType().kind == TypeKind.ARRAY && paramType != ParamType.IN) { if (param.isNullable()){ methodBuilder.beginControlFlow("if (${param.simpleName} != null)") } methodBuilder.addStatement("$REPLY.readIntArray(" + param.simpleName + ")") if (param.isNullable()){ methodBuilder.endControlFlow() } } } }
apache-2.0
df3ed11be96363394fe0da1fa2e5137f
42.746835
164
0.65625
5.07489
false
false
false
false
Kotlin/dokka
plugins/gfm/src/main/kotlin/org/jetbrains/dokka/gfm/gfmTemplating.kt
1
986
package org.jetbrains.dokka.gfm import org.jetbrains.dokka.base.templating.toJsonString import org.jetbrains.dokka.links.DRI import com.fasterxml.jackson.annotation.JsonTypeInfo import com.fasterxml.jackson.annotation.JsonTypeInfo.Id.CLASS @JsonTypeInfo(use = CLASS) sealed class GfmCommand { companion object { private const val delimiter = "\u1680" val templateCommandRegex: Regex = Regex("<!---$delimiter GfmCommand ([^$delimiter ]*)$delimiter--->(.+?)(?=<!---$delimiter)<!---$delimiter--->") val MatchResult.command get() = groupValues[1] val MatchResult.label get() = groupValues[2] fun Appendable.templateCommand(command: GfmCommand, content: Appendable.() -> Unit) { append("<!---$delimiter GfmCommand ${toJsonString(command)}$delimiter--->") content() append("<!---$delimiter--->") } } } class ResolveLinkGfmCommand(val dri: DRI) : GfmCommand()
apache-2.0
bbb6cfdb3db7d70174838908d3cc0d79
34.214286
122
0.646045
4.213675
false
false
false
false
AllanWang/Frost-for-Facebook
app/src/main/kotlin/com/pitchedapps/frost/web/FrostUrlOverlayValidator.kt
1
4636
/* * Copyright 2018 Allan Wang * * 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.pitchedapps.frost.web import ca.allanwang.kau.utils.runOnUiThread import com.pitchedapps.frost.activities.WebOverlayActivity import com.pitchedapps.frost.activities.WebOverlayActivityBase import com.pitchedapps.frost.contracts.VideoViewHolder import com.pitchedapps.frost.facebook.FbItem import com.pitchedapps.frost.facebook.USER_AGENT_DESKTOP_CONST import com.pitchedapps.frost.facebook.formattedFbUrl import com.pitchedapps.frost.utils.L import com.pitchedapps.frost.utils.isFacebookUrl import com.pitchedapps.frost.utils.isImageUrl import com.pitchedapps.frost.utils.isIndependent import com.pitchedapps.frost.utils.isIndirectImageUrl import com.pitchedapps.frost.utils.isMessengerUrl import com.pitchedapps.frost.utils.isVideoUrl import com.pitchedapps.frost.utils.launchImageActivity import com.pitchedapps.frost.utils.launchWebOverlay import com.pitchedapps.frost.utils.launchWebOverlayDesktop import com.pitchedapps.frost.utils.launchWebOverlayMobile import com.pitchedapps.frost.views.FrostWebView /** * Created by Allan Wang on 2017-08-15. * * Due to the nature of facebook href's, many links cannot be resolved on a new window and must * instead by loaded in the current page This helper method will collect all known cases and launch * the overlay accordingly Returns [true] (default) if action is consumed, [false] otherwise * * Note that this is not always called on the main thread! UI related methods should always be * posted or they may not be properly executed. * * If the request already comes from an instance of [WebOverlayActivity], we will then judge whether * the user agent string should be changed. All propagated results will return false, as we have no * need of sending a new intent to the same activity */ fun FrostWebView.requestWebOverlay(url: String): Boolean { @Suppress("NAME_SHADOWING") val url = url.formattedFbUrl L.v { "Request web overlay: $url" } val context = context // finalize reference if (url.isVideoUrl && context is VideoViewHolder) { L.d { "Found video through overlay" } context.runOnUiThread { context.showVideo(url) } return true } if (url.isIndirectImageUrl) { L.d { "Found indirect fb image" } context.launchImageActivity(url, cookie = fbCookie.webCookie) return true } if (url.isImageUrl) { L.d { "Found fb image" } context.launchImageActivity(url) return true } if (!url.isIndependent) { L.d { "Forbid overlay switch" } return false } if (!prefs.overlayEnabled) return false if (context is WebOverlayActivityBase) { val shouldUseDesktop = url.isFacebookUrl || url.isMessengerUrl // already overlay; manage user agent if (userAgentString != USER_AGENT_DESKTOP_CONST && shouldUseDesktop) { L._i { "Switch to desktop agent overlay" } context.launchWebOverlayDesktop(url, fbCookie, prefs) return true } if (userAgentString == USER_AGENT_DESKTOP_CONST && !shouldUseDesktop) { L._i { "Switch from desktop agent" } context.launchWebOverlayMobile(url, fbCookie, prefs) return true } L._i { "return false switch" } return false } L.v { "Request web overlay passed" } context.launchWebOverlay(url, fbCookie, prefs) return true } /** If the url contains any one of the whitelist segments, switch to the chat overlay */ val messageWhitelist: Set<String> = setOf(FbItem.MESSAGES, FbItem.CHAT, FbItem.FEED_MOST_RECENT, FbItem.FEED_TOP_STORIES) .mapTo(mutableSetOf(), FbItem::url) @Deprecated( message = "Should not be used in production as we only support one user agent at a time." ) val String.shouldUseDesktopAgent: Boolean get() = when { contains("story.php") -> false // do not use desktop for comment section contains("/events/") -> false // do not use for events (namely the map) contains("/messages") -> true // must use for messages else -> false // default to normal user agent }
gpl-3.0
cd0f60d09367358f34436ae958fcc3f1
40.026549
100
0.745686
4.041848
false
false
false
false
AllanWang/Frost-for-Facebook
app/src/test/kotlin/com/pitchedapps/frost/utils/CoroutineTest.kt
1
2610
/* * Copyright 2018 Allan Wang * * 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.pitchedapps.frost.utils import java.util.concurrent.Executors import kotlin.coroutines.EmptyCoroutineContext import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.asCoroutineDispatcher import kotlinx.coroutines.async import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.count import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.takeWhile import kotlinx.coroutines.joinAll import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking /** Collection of tests around coroutines */ class CoroutineTest { private fun <T : Any> SharedFlow<T?>.takeUntilNull(): Flow<T> = takeWhile { it != null }.filterNotNull() /** Sanity check to ensure that contexts are being honoured */ @Test fun contextSwitching() { val mainTag = "main-test" val mainDispatcher = Executors.newSingleThreadExecutor { r -> Thread(r, mainTag) }.asCoroutineDispatcher() val flow = MutableSharedFlow<String?>(100) runBlocking(Dispatchers.IO) { launch(mainDispatcher) { flow.takeUntilNull().collect { thread -> assertTrue( Thread.currentThread().name.startsWith(mainTag), "Channel should be received in main thread" ) assertFalse(thread.startsWith(mainTag), "Channel execution should not be in main thread") } } listOf(EmptyCoroutineContext, Dispatchers.IO, Dispatchers.Default, Dispatchers.IO) .map { async(it) { flow.emit(Thread.currentThread().name) } } .joinAll() flow.emit(null) val count = flow.takeUntilNull().count() assertEquals(4, count, "Not all events received") } } }
gpl-3.0
9879f60fd7751e20456537f65445b4c3
35.760563
99
0.738697
4.492255
false
true
false
false
chrisbanes/tivi
ui/showseasons/src/main/java/app/tivi/showdetails/seasons/ShowSeasonsViewModel.kt
1
2956
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.showdetails.seasons import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import app.tivi.api.UiMessageManager import app.tivi.domain.interactors.UpdateShowSeasons import app.tivi.domain.observers.ObserveShowDetails import app.tivi.domain.observers.ObserveShowSeasonsEpisodesWatches import app.tivi.util.Logger import app.tivi.util.ObservableLoadingCounter import app.tivi.util.collectStatus import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel internal class ShowSeasonsViewModel @Inject constructor( savedStateHandle: SavedStateHandle, observeShowDetails: ObserveShowDetails, observeShowSeasons: ObserveShowSeasonsEpisodesWatches, private val updateShowSeasons: UpdateShowSeasons, private val logger: Logger ) : ViewModel() { private val showId: Long = savedStateHandle["showId"]!! private val loadingState = ObservableLoadingCounter() private val uiMessageManager = UiMessageManager() val state: StateFlow<ShowSeasonsViewState> = combine( observeShowSeasons.flow, observeShowDetails.flow, loadingState.observable, uiMessageManager.message ) { seasons, show, refreshing, message -> ShowSeasonsViewState( show = show, seasons = seasons, refreshing = refreshing, message = message ) }.stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(), initialValue = ShowSeasonsViewState.Empty ) init { observeShowDetails(ObserveShowDetails.Params(showId)) observeShowSeasons(ObserveShowSeasonsEpisodesWatches.Params(showId)) refresh(false) } fun refresh(fromUser: Boolean = true) { viewModelScope.launch { updateShowSeasons( UpdateShowSeasons.Params(showId, fromUser) ).collectStatus(loadingState, logger, uiMessageManager) } } fun clearMessage(id: Long) { viewModelScope.launch { uiMessageManager.clearMessage(id) } } }
apache-2.0
0b82759c1d3e6a31b31c1a4e9760615e
32.590909
76
0.734438
4.783172
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/multimediacard/impl/MultimediaEditableNote.kt
1
4119
/**************************************************************************************** * Copyright (c) 2013 Bibek Shrestha <[email protected]> * * Copyright (c) 2013 Zaur Molotnikov <[email protected]> * * Copyright (c) 2013 Nicolas Raoul <[email protected]> * * Copyright (c) 2013 Flavio Lerda <[email protected]> * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 3 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************************/ package com.ichi2.anki.multimediacard.impl import com.ichi2.anki.multimediacard.IMultimediaEditableNote import com.ichi2.anki.multimediacard.fields.IField import com.ichi2.libanki.NoteTypeId import org.acra.util.IOUtils import java.util.* /** * Implementation of the editable note. * <p> * Has to be translate to and from anki db format. */ class MultimediaEditableNote : IMultimediaEditableNote { override var isModified = false private set private var mFields: ArrayList<IField?>? = null var modelId: NoteTypeId = 0 /** * Field values in the note editor, before any editing has taken place * These values should not be modified */ private var mInitialFields: ArrayList<IField?>? = null private fun setThisModified() { isModified = true } // package fun setNumFields(numberOfFields: Int) { fieldsPrivate.clear() for (i in 0 until numberOfFields) { fieldsPrivate.add(null) } } private val fieldsPrivate: ArrayList<IField?> get() { if (mFields == null) { mFields = ArrayList(0) } return mFields!! } override val numberOfFields: Int get() = fieldsPrivate.size override fun getField(index: Int): IField? { return if (index in 0 until numberOfFields) { fieldsPrivate[index] } else null } override fun setField(index: Int, field: IField?): Boolean { if (index in 0 until numberOfFields) { // If the same unchanged field is set. if (getField(index) === field) { if (field!!.isModified) { setThisModified() } } else { setThisModified() } fieldsPrivate[index] = field return true } return false } fun freezeInitialFieldValues() { mInitialFields = ArrayList() for (f in mFields!!) { mInitialFields!!.add(cloneField(f)) } } override val initialFieldCount: Int get() = mInitialFields!!.size override fun getInitialField(index: Int): IField? { return cloneField(mInitialFields!![index]) } private fun cloneField(f: IField?): IField? { return IOUtils.deserialize(IField::class.java, IOUtils.serialize(f!!)) } companion object { private const val serialVersionUID = -6161821367135636659L } }
gpl-3.0
b7ad22ca364d59e2b478e767e40d36e2
36.788991
90
0.525856
4.823185
false
false
false
false
prof18/YoutubeParser
youtubeparser/src/main/java/com/prof/youtubeparser/core/CoreJsonParser.kt
1
1888
/* * Copyright 2019 Marco Gomiero * * 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.prof.youtubeparser.core import com.google.gson.GsonBuilder import com.prof.youtubeparser.models.stats.Statistics import com.prof.youtubeparser.models.videos.Video import com.prof.youtubeparser.models.videos.internal.Item import com.prof.youtubeparser.models.videos.internal.Main internal object CoreJsonParser { fun parseVideo(json: String): ParsingResult { val gson = GsonBuilder().create() val data = gson.fromJson(json, Main::class.java) //Begin parsing Json data val nextToken = data.nextPageToken val videos = data.items.map { item -> Video( title = item.snippet?.title, videoId = item.id?.videoId, coverLink = item.getHighQualityThumbnailUrl(), date = item.snippet?.publishedAt ) } return ParsingResult(videos, nextToken) } private fun Item.getHighQualityThumbnailUrl(): String? = this.snippet?.thumbnails?.high?.url fun parseStats(json: String): Statistics { val gson = GsonBuilder().create() val data = gson.fromJson(json, com.prof.youtubeparser.models.stats.internal.Main::class.java) val itemList = data.items return itemList[0].statistics } }
apache-2.0
938ec03bb6dc26acbaaeca7df0ae1036
32.714286
96
0.681144
4.320366
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/advancement/criteria/progress/LanternCriterionProgressBase.kt
1
1801
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.advancement.criteria.progress import org.lanternpowered.api.util.optional.asOptional import org.lanternpowered.api.util.optional.orNull import org.lanternpowered.server.advancement.LanternAdvancementProgress import org.lanternpowered.server.advancement.criteria.AbstractCriterion import org.lanternpowered.server.advancement.criteria.trigger.LanternTrigger import java.time.Instant import java.util.Optional abstract class LanternCriterionProgressBase<T : AbstractCriterion>( criterion: T, progress: LanternAdvancementProgress ) : AbstractCriterionProgress<T>(criterion, progress) { protected var achievingTime: Instant? = null private var attached = false override fun achieved(): Boolean = this.achievingTime != null override fun get(): Optional<Instant> = this.achievingTime.asOptional() override fun attachTrigger() { val trigger = this.criterion.trigger.orNull() ?: return // Only attach once if (this.attached) return this.attached = true (trigger.type as LanternTrigger<*>).add(this.advancementProgress.playerAdvancements, this) } override fun detachTrigger() { val trigger = this.criterion.trigger.orNull() ?: return // Only detach once if (!this.attached) return this.attached = false (trigger.type as LanternTrigger<*>).remove(this.advancementProgress.playerAdvancements, this) } }
mit
af41c15367dfd53b6a9011211c6d4d18
35.755102
101
0.728484
4.435961
false
false
false
false
SimonVT/cathode
cathode/src/main/java/net/simonvt/cathode/ui/suggestions/movies/AnticipatedMoviesFragment.kt
1
4633
/* * Copyright (C) 2016 Simon Vig Therkildsen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.simonvt.cathode.ui.suggestions.movies import android.os.Bundle import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import net.simonvt.cathode.R import net.simonvt.cathode.common.ui.adapter.BaseAdapter import net.simonvt.cathode.entity.Movie import net.simonvt.cathode.jobqueue.JobManager import net.simonvt.cathode.provider.ProviderSchematic.Movies import net.simonvt.cathode.settings.Settings import net.simonvt.cathode.sync.scheduler.MovieTaskScheduler import net.simonvt.cathode.ui.CathodeViewModelFactory import net.simonvt.cathode.ui.lists.ListDialog import net.simonvt.cathode.ui.movies.BaseMoviesAdapter import net.simonvt.cathode.ui.movies.MoviesAdapter import net.simonvt.cathode.ui.movies.MoviesFragment import javax.inject.Inject class AnticipatedMoviesFragment @Inject constructor( jobManager: JobManager, movieScheduler: MovieTaskScheduler ) : MoviesFragment(jobManager, movieScheduler), ListDialog.Callback { @Inject lateinit var viewModelFactory: CathodeViewModelFactory private lateinit var viewModel: AnticipatedMoviesViewModel private lateinit var sortBy: SortBy enum class SortBy(val key: String, val sortOrder: String) { ANTICIPATED("anticipated", Movies.SORT_ANTICIPATED), TITLE("title", Movies.SORT_TITLE); override fun toString(): String { return key } companion object { fun fromValue(value: String) = values().firstOrNull { it.key == value } ?: ANTICIPATED } } override fun onCreate(inState: Bundle?) { sortBy = SortBy.fromValue( Settings.get(requireContext()) .getString(Settings.Sort.MOVIE_ANTICIPATED, SortBy.ANTICIPATED.key)!! ) super.onCreate(inState) setTitle(R.string.title_movies_anticipated) setEmptyText(R.string.movies_loading_anticipated) viewModel = ViewModelProviders.of(this, viewModelFactory).get(AnticipatedMoviesViewModel::class.java) viewModel.loading.observe(this, Observer { loading -> setRefreshing(loading) }) viewModel.anticipated.observe(this, observer) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, inState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_swiperefresh_recyclerview, container, false) } override fun onRefresh() { viewModel.refresh() } override fun onMenuItemClick(item: MenuItem): Boolean { when (item.itemId) { R.id.sort_by -> { val items = arrayListOf<ListDialog.Item>() items.add(ListDialog.Item(R.id.sort_anticipated, R.string.sort_anticipated)) items.add(ListDialog.Item(R.id.sort_title, R.string.sort_title)) ListDialog.newInstance(requireFragmentManager(), R.string.action_sort_by, items, this) .show(requireFragmentManager(), DIALOG_SORT) return true } else -> return super.onMenuItemClick(item) } } override fun onItemSelected(id: Int) { when (id) { R.id.sort_anticipated -> if (sortBy != SortBy.ANTICIPATED) { sortBy = SortBy.ANTICIPATED Settings.get(requireContext()) .edit() .putString(Settings.Sort.MOVIE_ANTICIPATED, SortBy.ANTICIPATED.key) .apply() viewModel.setSortBy(sortBy) scrollToTop = true } R.id.sort_title -> if (sortBy != SortBy.TITLE) { sortBy = SortBy.TITLE Settings.get(requireContext()) .edit() .putString(Settings.Sort.MOVIE_ANTICIPATED, SortBy.TITLE.key) .apply() viewModel.setSortBy(sortBy) scrollToTop = true } } } override fun createAdapter(): BaseAdapter<Movie, BaseMoviesAdapter.ViewHolder> { return MoviesAdapter(requireActivity(), this, R.layout.list_row_movie) } companion object { private const val DIALOG_SORT = "net.simonvt.cathode.ui.suggestions.movies.AnticipatedMoviesFragment.sortDialog" } }
apache-2.0
3c536aaba2a0a44d13eb29ba9f59173e
32.330935
95
0.726095
4.136607
false
false
false
false
FHannes/intellij-community
plugins/git4idea/tests/git4idea/tests/GitCommitTest.kt
6
10611
/* * Copyright 2000-2010 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 git4idea.tests import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vcs.Executor.* import com.intellij.openapi.vcs.FileStatus import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.changes.Change import com.intellij.util.containers.ContainerUtil import git4idea.GitUtil import git4idea.changes.GitChangeUtils import git4idea.checkin.GitCheckinEnvironment import git4idea.history.GitHistoryUtils import git4idea.test.* import git4idea.test.createFileStructure import java.io.File import java.util.* class GitCommitTest : GitSingleRepoTest() { override fun getDebugLogCategories() = super.getDebugLogCategories().plus("#" + GitCheckinEnvironment::class.java.name) // IDEA-50318 fun `test merge commit with spaces in path`() { val PATH = "dir with spaces/file with spaces.txt" createFileStructure(myProjectRoot, PATH) addCommit("created some file structure") git("branch feature") val file = File(myProjectPath, PATH) assertTrue("File doesn't exist!", file.exists()) overwrite(file, "my content") addCommit("modified in master") checkout("feature") overwrite(file, "brother content") addCommit("modified in feature") checkout("master") git("merge feature", true) // ignoring non-zero exit-code reporting about conflicts overwrite(file, "merged content") // manually resolving conflict git("add .") updateChangeListManager() val changes = changeListManager.allChanges assertTrue(!changes.isEmpty()) commit(changes) assertNoChanges() } fun `test commit case rename`() { generateCaseRename("a.java", "A.java") val changes = assertChanges() { rename("a.java", "A.java") } commit(changes) assertNoChanges() assertCommitted() { rename("a.java", "A.java") } } fun `test commit case rename + one staged file`() { generateCaseRename("a.java", "A.java") touch("s.java") git("add s.java") val changes = assertChanges() { rename("a.java", "A.java") added("s.java") } commit(changes) assertNoChanges() assertCommitted() { rename("a.java", "A.java") added("s.java") } } fun `test commit case rename + one unstaged file`() { tac("m.java") generateCaseRename("a.java", "A.java") echo("m.java", "unstaged") val changes = assertChanges() { rename("a.java", "A.java") modified("m.java") } commit(changes) assertNoChanges() assertCommitted() { rename("a.java", "A.java") modified("m.java") } } fun `test commit case rename & don't commit one unstaged file`() { tac("m.java") generateCaseRename("a.java", "A.java") echo("m.java", "unstaged") val changes = assertChanges() { rename("a.java", "A.java") modified("m.java") } commit(listOf(changes[0])) assertChanges() { modified("m.java") } assertCommitted() { rename("a.java", "A.java") } } fun `test commit case rename & don't commit one staged file`() { tac("s.java") generateCaseRename("a.java", "A.java") echo("s.java", "staged") git("add s.java") val changes = assertChanges() { rename("a.java", "A.java") modified("s.java") } commit(listOf(changes[0])) assertCommitted() { rename("a.java", "A.java") } assertChanges() { modified("s.java") } assertStagedChanges() { modified("s.java") } } fun `test commit case rename & don't commit one staged simple rename, then rename should remain staged`() { echo("before.txt", "some\ncontent\nere") addCommit("created before.txt") generateCaseRename("a.java", "A.java") git("mv before.txt after.txt") val changes = assertChanges() { rename("a.java", "A.java") rename("before.txt", "after.txt") } commit(listOf(changes[0])) assertCommitted() { rename("a.java", "A.java") } assertChanges() { rename("before.txt", "after.txt") } assertStagedChanges() { rename("before.txt", "after.txt") } } fun `test commit case rename + one unstaged file & don't commit one staged file`() { tac("s.java") tac("m.java") generateCaseRename("a.java", "A.java") echo("s.java", "staged") echo("m.java", "unstaged") git("add s.java m.java") val changes = assertChanges() { rename("a.java", "A.java") modified("s.java") modified("m.java") } commit(listOf(changes[0], changes[2])) assertCommitted() { rename("a.java", "A.java") modified("m.java") } assertChanges() { modified("s.java") } assertStagedChanges() { modified("s.java") } } fun `test commit case rename & don't commit a file which is both staged and unstaged, should reset and restore`() { tac("c.java") generateCaseRename("a.java", "A.java") echo("c.java", "staged") git("add c.java") overwrite("c.java", "unstaged") val changes = assertChanges() { rename("a.java", "A.java") modified("c.java") } commit(listOf(changes[0])) assertCommitted() { rename("a.java", "A.java") } assertChanges() { modified("c.java") } assertStagedChanges() { modified("c.java") } // this is intentional data loss: it is a rare case, while restoring both staged and unstaged part is not so easy, // so we are not doing it, at least until IDEA supports Git index // (which will mean that users will be able to produce such situation intentionally with a help of IDE). assertEquals("unstaged", git("show :c.java")) assertEquals("unstaged", FileUtil.loadFile(File(myProjectPath, "c.java"))) } fun `test commit case rename with additional non-staged changes should commit everything`() { val initialContent = """ some large content to let rename detection work """.trimIndent() touch("a.java", initialContent) addCommit("initial a.java") git("mv -f a.java A.java") val additionalContent = "non-staged content" append("A.java", additionalContent) val changes = assertChanges() { rename("a.java", "A.java") } commit(changes) assertCommitted() { rename("a.java", "A.java") } assertNoChanges() assertEquals(initialContent + additionalContent, git("show HEAD:A.java")) } private fun generateCaseRename(from: String, to: String) { tac(from) git("mv -f $from $to") } private fun commit(changes: Collection<Change>) { val exceptions = myVcs.checkinEnvironment!!.commit(ArrayList(changes), "comment") assertNoExceptions(exceptions) updateChangeListManager() } private fun assertNoChanges() { val changes = changeListManager.getChangesIn(myProjectRoot) assertTrue("We expected no changes but found these: " + GitUtil.getLogString(myProjectPath, changes), changes.isEmpty()) } private fun assertNoExceptions(exceptions: List<VcsException>?) { val ex = ContainerUtil.getFirstItem(exceptions) if (ex != null) { LOG.error(ex) fail("Exception during executing the commit: " + ex.message) } } private fun assertChanges(changes: ChangesBuilder.() -> Unit) : List<Change> { val cb = ChangesBuilder() cb.changes() updateChangeListManager() val allChanges = mutableListOf<Change>() val actualChanges = HashSet(changeListManager.allChanges) for (change in cb.changes) { val found = actualChanges.find(change.matcher) assertNotNull("The change [$change] not found", found) actualChanges.remove(found) allChanges.add(found!!) } assertTrue(actualChanges.isEmpty()) return allChanges } private fun assertStagedChanges(changes: ChangesBuilder.() -> Unit) { val cb = ChangesBuilder() cb.changes() val actualChanges = GitChangeUtils.getStagedChanges(myProject, myProjectRoot) for (change in cb.changes) { val found = actualChanges.find(change.matcher) assertNotNull("The change [$change] is not staged", found) actualChanges.remove(found) } assertTrue(actualChanges.isEmpty()) } private fun assertCommitted(changes: ChangesBuilder.() -> Unit) { val cb = ChangesBuilder() cb.changes() val actualChanges = GitHistoryUtils.history(myProject, myProjectRoot, "-1")[0].changes for (change in cb.changes) { val found = actualChanges.find(change.matcher) assertNotNull("The change [$change] wasn't committed", found) actualChanges.remove(found) } assertTrue(actualChanges.isEmpty()) } class ChangesBuilder { data class AChange(val type: FileStatus, val nameBefore: String?, val nameAfter: String, val matcher: (Change) -> Boolean) { constructor(type: FileStatus, nameAfter: String, matcher: (Change) -> Boolean) : this(type, null, nameAfter, matcher) override fun toString(): String { when (type) { Change.Type.NEW -> return "A: $nameAfter" Change.Type.DELETED -> return "D: $nameAfter" Change.Type.MOVED -> return "M: $nameBefore -> $nameAfter" else -> return "M: $nameAfter" } } } val changes = linkedSetOf<AChange>() fun added(name: String) { assertTrue(changes.add(AChange(FileStatus.ADDED, name) { it.fileStatus == FileStatus.ADDED && it.beforeRevision == null && it.afterRevision!!.file.name == name })) } fun modified(name:String) { assertTrue(changes.add(AChange(FileStatus.MODIFIED, name) { it.fileStatus == FileStatus.MODIFIED && it.beforeRevision!!.file.name == name && it.afterRevision!!.file.name == name })) } fun rename(from: String, to: String) { assertTrue(changes.add(AChange(FileStatus.MODIFIED, from, to) { it.isRenamed && from == it.beforeRevision!!.file.name && to == it.afterRevision!!.file.name })) } } }
apache-2.0
eede5e2655299b1b90ebea638326db3e
27.220745
128
0.645839
3.969697
false
false
false
false
timusus/Shuttle
app/src/main/java/com/simplecity/amp_library/ui/dialog/ArtistBiographyDialog.kt
1
3323
package com.simplecity.amp_library.ui.dialog import android.annotation.SuppressLint import android.app.Dialog import android.content.Context import android.os.Bundle import android.support.v4.app.DialogFragment import android.support.v4.app.FragmentManager import android.text.Html import android.view.LayoutInflater import android.view.View import android.widget.ProgressBar import android.widget.TextView import com.afollestad.materialdialogs.MaterialDialog import com.simplecity.amp_library.R import com.simplecity.amp_library.R.string import com.simplecity.amp_library.http.HttpClient import com.simplecity.amp_library.http.lastfm.LastFmArtist import com.simplecity.amp_library.model.AlbumArtist import com.simplecity.amp_library.utils.ShuttleUtils import retrofit2.Call import retrofit2.Callback import retrofit2.Response class ArtistBiographyDialog : DialogFragment() { private lateinit var artist: AlbumArtist override fun onAttach(context: Context?) { super.onAttach(context) artist = arguments!!.getSerializable(ARG_ARTIST) as AlbumArtist } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { @SuppressLint("InflateParams") val customView = LayoutInflater.from(context).inflate(R.layout.dialog_biography, null, false) val progressBar = customView.findViewById<ProgressBar>(R.id.progress) val message = customView.findViewById<TextView>(R.id.message) HttpClient.getInstance().lastFmService.getLastFmArtistResult(artist.name).enqueue(object : Callback<LastFmArtist> { override fun onResponse(call: Call<LastFmArtist>, response: Response<LastFmArtist>) { progressBar.visibility = View.GONE if (response.isSuccessful) { if (response.body() != null && response.body()!!.artist != null && response.body()!!.artist.bio != null) { val summary = response.body()!!.artist.bio.summary if (ShuttleUtils.hasNougat()) { message.text = Html.fromHtml(summary, Html.FROM_HTML_MODE_COMPACT) } else { message.text = Html.fromHtml(summary) } } else { message.setText(string.no_artist_info) } } } override fun onFailure(call: Call<LastFmArtist>, t: Throwable) { progressBar.visibility = View.GONE message.setText(string.no_artist_info) } }) val builder = MaterialDialog.Builder(context!!) .title(R.string.info) .customView(customView, false) .negativeText(R.string.close) return builder.build() } fun show(fragmentManager: FragmentManager) { show(fragmentManager, TAG) } companion object { private const val TAG = "ArtistBiographyDialog" private const val ARG_ARTIST = "artist" fun newInstance(artist: AlbumArtist): ArtistBiographyDialog { val args = Bundle() args.putSerializable(ARG_ARTIST, artist) val fragment = ArtistBiographyDialog() fragment.arguments = args return fragment } } }
gpl-3.0
9fefc8fce199572b98b9672e154ccb2e
35.130435
126
0.652423
4.747143
false
false
false
false
KawaiiTech/slack-bot
src/main/kotlin/Roomba.kt
1
793
import kotlin.js.Json object Roomba { var local: dynamic = null init { val dorita = require("dorita980") local = dorita.Local("user", "password", "192.168.0.xx") Bot.controller.hears("meido", arrayOf("direct_message", "direct_mention")) { bot, message -> bot.reply(message, "Getting Meido status...") local.getMission() .then { data: Json -> bot.reply(message, data.getPhase()) } .catch { error: String -> bot.reply(message, error) } } } } private fun Json.getPhase(): String { val mission = get("cleanMissionStatus") as Json val phase = mission["phase"] as String return when (phase) { "charge" -> "Meido is charging!" else -> "Meido is $phase" } }
mit
563ca4d14c89734236c8839d9ef6f724
32.041667
100
0.566204
3.705607
false
false
false
false
ansman/okhttp
mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt
2
11097
/* * Copyright (C) 2011 Google 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 mockwebserver3 import java.util.concurrent.TimeUnit import okhttp3.Headers import okhttp3.WebSocketListener import okhttp3.internal.addHeaderLenient import okhttp3.internal.http2.Settings import mockwebserver3.internal.duplex.DuplexResponseBody import okio.Buffer /** A scripted response to be replayed by the mock web server. */ class MockResponse : Cloneable { /** Returns the HTTP response line, such as "HTTP/1.1 200 OK". */ @set:JvmName("status") var status: String = "" private var headersBuilder = Headers.Builder() private var trailersBuilder = Headers.Builder() /** The HTTP headers, such as "Content-Length: 0". */ @set:JvmName("headers") var headers: Headers get() = headersBuilder.build() set(value) { this.headersBuilder = value.newBuilder() } @set:JvmName("trailers") var trailers: Headers get() = trailersBuilder.build() set(value) { this.trailersBuilder = value.newBuilder() } private var body: Buffer? = null var throttleBytesPerPeriod = Long.MAX_VALUE private set private var throttlePeriodAmount = 1L private var throttlePeriodUnit = TimeUnit.SECONDS @set:JvmName("socketPolicy") var socketPolicy = SocketPolicy.KEEP_OPEN /** * Sets the [HTTP/2 error code](https://tools.ietf.org/html/rfc7540#section-7) to be * returned when resetting the stream. * This is only valid with [SocketPolicy.RESET_STREAM_AT_START] and * [SocketPolicy.DO_NOT_READ_REQUEST_BODY]. */ @set:JvmName("http2ErrorCode") var http2ErrorCode = -1 private var bodyDelayAmount = 0L private var bodyDelayUnit = TimeUnit.MILLISECONDS private var headersDelayAmount = 0L private var headersDelayUnit = TimeUnit.MILLISECONDS private var promises = mutableListOf<PushPromise>() var settings: Settings = Settings() private set var webSocketListener: WebSocketListener? = null private set var duplexResponseBody: DuplexResponseBody? = null private set val isDuplex: Boolean get() = duplexResponseBody != null /** Returns the streams the server will push with this response. */ val pushPromises: List<PushPromise> get() = promises /** Creates a new mock response with an empty body. */ init { setResponseCode(200) setHeader("Content-Length", 0L) } public override fun clone(): MockResponse { val result = super.clone() as MockResponse result.headersBuilder = headersBuilder.build().newBuilder() result.promises = promises.toMutableList() return result } @JvmName("-deprecated_getStatus") @Deprecated( message = "moved to var", replaceWith = ReplaceWith(expression = "status"), level = DeprecationLevel.ERROR) fun getStatus(): String = status /** * Sets the status and returns this. * * This was deprecated in OkHttp 4.0 in favor of the [status] val. In OkHttp 4.3 it is * un-deprecated because Java callers can't chain when assigning Kotlin vals. (The getter remains * deprecated). */ fun setStatus(status: String) = apply { this.status = status } fun setResponseCode(code: Int): MockResponse { val reason = when (code) { in 100..199 -> "Informational" in 200..299 -> "OK" in 300..399 -> "Redirection" in 400..499 -> "Client Error" in 500..599 -> "Server Error" else -> "Mock Response" } return apply { status = "HTTP/1.1 $code $reason" } } /** * Removes all HTTP headers including any "Content-Length" and "Transfer-encoding" headers that * were added by default. */ fun clearHeaders() = apply { headersBuilder = Headers.Builder() } /** * Adds [header] as an HTTP header. For well-formed HTTP [header] should contain a * name followed by a colon and a value. */ fun addHeader(header: String) = apply { headersBuilder.add(header) } /** * Adds a new header with the name and value. This may be used to add multiple headers with the * same name. */ fun addHeader(name: String, value: Any) = apply { headersBuilder.add(name, value.toString()) } /** * Adds a new header with the name and value. This may be used to add multiple headers with the * same name. Unlike [addHeader] this does not validate the name and * value. */ fun addHeaderLenient(name: String, value: Any) = apply { addHeaderLenient(headersBuilder, name, value.toString()) } /** * Removes all headers named [name], then adds a new header with the name and value. */ fun setHeader(name: String, value: Any) = apply { removeHeader(name) addHeader(name, value) } /** Removes all headers named [name]. */ fun removeHeader(name: String) = apply { headersBuilder.removeAll(name) } /** Returns a copy of the raw HTTP payload. */ fun getBody(): Buffer? = body?.clone() fun setBody(body: Buffer) = apply { setHeader("Content-Length", body.size) this.body = body.clone() // Defensive copy. } /** Sets the response body to the UTF-8 encoded bytes of [body]. */ fun setBody(body: String): MockResponse = setBody(Buffer().writeUtf8(body)) fun setBody(duplexResponseBody: DuplexResponseBody) = apply { this.duplexResponseBody = duplexResponseBody } /** * Sets the response body to [body], chunked every [maxChunkSize] bytes. */ fun setChunkedBody(body: Buffer, maxChunkSize: Int) = apply { removeHeader("Content-Length") headersBuilder.add(CHUNKED_BODY_HEADER) val bytesOut = Buffer() while (!body.exhausted()) { val chunkSize = minOf(body.size, maxChunkSize.toLong()) bytesOut.writeHexadecimalUnsignedLong(chunkSize) bytesOut.writeUtf8("\r\n") bytesOut.write(body, chunkSize) bytesOut.writeUtf8("\r\n") } bytesOut.writeUtf8("0\r\n") // Last chunk. Trailers follow! this.body = bytesOut } /** * Sets the response body to the UTF-8 encoded bytes of [body], * chunked every [maxChunkSize] bytes. */ fun setChunkedBody(body: String, maxChunkSize: Int): MockResponse = setChunkedBody(Buffer().writeUtf8(body), maxChunkSize) @JvmName("-deprecated_getHeaders") @Deprecated( message = "moved to var", replaceWith = ReplaceWith(expression = "headers"), level = DeprecationLevel.ERROR) fun getHeaders(): Headers = headers /** * Sets the headers and returns this. * * This was deprecated in OkHttp 4.0 in favor of the [headers] val. In OkHttp 4.3 it is * un-deprecated because Java callers can't chain when assigning Kotlin vals. (The getter remains * deprecated). */ fun setHeaders(headers: Headers) = apply { this.headers = headers } @JvmName("-deprecated_getTrailers") @Deprecated( message = "moved to var", replaceWith = ReplaceWith(expression = "trailers"), level = DeprecationLevel.ERROR) fun getTrailers(): Headers = trailers /** * Sets the trailers and returns this. * * This was deprecated in OkHttp 4.0 in favor of the [trailers] val. In OkHttp 4.3 it is * un-deprecated because Java callers can't chain when assigning Kotlin vals. (The getter remains * deprecated). */ fun setTrailers(trailers: Headers) = apply { this.trailers = trailers } @JvmName("-deprecated_getSocketPolicy") @Deprecated( message = "moved to var", replaceWith = ReplaceWith(expression = "socketPolicy"), level = DeprecationLevel.ERROR) fun getSocketPolicy() = socketPolicy /** * Sets the socket policy and returns this. * * This was deprecated in OkHttp 4.0 in favor of the [socketPolicy] val. In OkHttp 4.3 it is * un-deprecated because Java callers can't chain when assigning Kotlin vals. (The getter remains * deprecated). */ fun setSocketPolicy(socketPolicy: SocketPolicy) = apply { this.socketPolicy = socketPolicy } @JvmName("-deprecated_getHttp2ErrorCode") @Deprecated( message = "moved to var", replaceWith = ReplaceWith(expression = "http2ErrorCode"), level = DeprecationLevel.ERROR) fun getHttp2ErrorCode() = http2ErrorCode /** * Sets the HTTP/2 error code and returns this. * * This was deprecated in OkHttp 4.0 in favor of the [http2ErrorCode] val. In OkHttp 4.3 it is * un-deprecated because Java callers can't chain when assigning Kotlin vals. (The getter remains * deprecated). */ fun setHttp2ErrorCode(http2ErrorCode: Int) = apply { this.http2ErrorCode = http2ErrorCode } /** * Throttles the request reader and response writer to sleep for the given period after each * series of [bytesPerPeriod] bytes are transferred. Use this to simulate network behavior. */ fun throttleBody(bytesPerPeriod: Long, period: Long, unit: TimeUnit) = apply { throttleBytesPerPeriod = bytesPerPeriod throttlePeriodAmount = period throttlePeriodUnit = unit } fun getThrottlePeriod(unit: TimeUnit): Long = unit.convert(throttlePeriodAmount, throttlePeriodUnit) /** * Set the delayed time of the response body to [delay]. This applies to the response body * only; response headers are not affected. */ fun setBodyDelay(delay: Long, unit: TimeUnit) = apply { bodyDelayAmount = delay bodyDelayUnit = unit } fun getBodyDelay(unit: TimeUnit): Long = unit.convert(bodyDelayAmount, bodyDelayUnit) fun setHeadersDelay(delay: Long, unit: TimeUnit) = apply { headersDelayAmount = delay headersDelayUnit = unit } fun getHeadersDelay(unit: TimeUnit): Long = unit.convert(headersDelayAmount, headersDelayUnit) /** * When [protocols][MockWebServer.protocols] include [HTTP_2][okhttp3.Protocol], this attaches a * pushed stream to this response. */ fun withPush(promise: PushPromise) = apply { promises.add(promise) } /** * When [protocols][MockWebServer.protocols] include [HTTP_2][okhttp3.Protocol], this pushes * [settings] before writing the response. */ fun withSettings(settings: Settings) = apply { this.settings = settings } /** * Attempts to perform a web socket upgrade on the connection. * This will overwrite any previously set status or body. */ fun withWebSocketUpgrade(listener: WebSocketListener) = apply { status = "HTTP/1.1 101 Switching Protocols" setHeader("Connection", "Upgrade") setHeader("Upgrade", "websocket") body = null webSocketListener = listener } override fun toString() = status companion object { private const val CHUNKED_BODY_HEADER = "Transfer-encoding: chunked" } }
apache-2.0
e10593bdebf8f2952cef48f5bfc09340
30.436261
99
0.69271
4.23388
false
false
false
false
bravelocation/yeltzland-android
app/src/main/java/com/bravelocation/yeltzlandnew/dataproviders/TwitterDataProvider.kt
1
6122
package com.bravelocation.yeltzlandnew.dataproviders import android.util.Base64 import android.util.Log import com.bravelocation.yeltzlandnew.models.ThreadSafeList import com.bravelocation.yeltzlandnew.tweet.Tweet import com.google.gson.GsonBuilder import okhttp3.* import org.json.JSONObject import java.io.IOException import java.net.URLEncoder import java.util.* interface TwitterDataProviderInterface { fun fetchTweets(completion: ((ThreadSafeList<Tweet>) -> Unit)) val accountName: String } class TwitterDataProvider( private val twitterConsumerKey: String, private val twitterConsumerSecret: String, override val accountName: String, private val tweetCount: Int, ) : TwitterDataProviderInterface { override fun fetchTweets(completion: ((ThreadSafeList<Tweet>) -> Unit)) { val userTimelineURL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" + accountName + "&count=" + tweetCount.toString() + "&exclude_replies=true&tweet_mode=extended" getBearerToken(TweetTokenHandler(userTimelineURL, completion)) } private fun getBearerToken(handler: TokenHandler) { // Fetch bearer token on background thread val client = OkHttpClient() val authorizationValue = base64EncodeString val requestBody: RequestBody = FormBody.Builder() .add("grant_type", "client_credentials") .build() val request: Request = Request.Builder() .url("https://api.twitter.com/oauth2/token") .header("Authorization", "Basic $authorizationValue") .header("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8") .post(requestBody) .build() client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { e.printStackTrace() handler.onCompletion(null) } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { if (!response.isSuccessful) { Log.d("TwitterDataProvider", "Unexpected code $response") } else { val result = response.body?.string() if (result == null) { Log.d("TwitterDataProvider", "Error getting response") handler.onCompletion(null) return } try { // The response should be JSON including "access_token" field, which we will return val parsedJson = JSONObject(result) val token = parsedJson.getString("access_token") handler.onCompletion(token) } catch (e: Exception) { Log.d("TwitterDataProvider", "Error parsing JSON $e") handler.onCompletion(null) } } } }) } private val base64EncodeString: String? get() { try { val consumerKeyRFC1738 = URLEncoder.encode(twitterConsumerKey, "utf-8") val consumerSecretRFC1738 = URLEncoder.encode(twitterConsumerSecret, "utf-8") val concatenateKeyAndSecret = "$consumerKeyRFC1738:$consumerSecretRFC1738" val secretAndKeyData = concatenateKeyAndSecret.toByteArray(charset("ascii")) return Base64.encodeToString(secretAndKeyData, Base64.NO_WRAP) } catch (e: Exception) { Log.d("TwitterDataProvider", "Encoding access token: " + e.message) } return null } private inner class TweetTokenHandler( private val url: String, private val completion: ((ThreadSafeList<Tweet>) -> Unit) ) : TokenHandler { override fun onCompletion(token: String?) { if (token == null) { completion(ThreadSafeList()) return } // Fetch bearer token on background thread val client = OkHttpClient() val request: Request = Request.Builder() .url(url) .header("Authorization", "Bearer $token") .build() client.newCall(request).enqueue(TweetFetcher(completion)) } } private inner class TweetFetcher( private val completion: ((ThreadSafeList<Tweet>) -> Unit), ) : Callback { override fun onFailure(call: Call, e: IOException) { completion(ThreadSafeList()) // Return an empty list on a failure e.printStackTrace() } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { if (!response.isSuccessful) { Log.d("TwitterDataProvider", "Unexpected code $response") completion(ThreadSafeList()) // Return an empty list on an error return } try { val result = response.body?.string() if (result != null) { val gsonBuilder = GsonBuilder() gsonBuilder.setDateFormat("EEE MMM dd HH:mm:ss Z yyyy") val gson = gsonBuilder.create() val parsedTweets = gson.fromJson(result, Array<Tweet>::class.java) val tweets = ThreadSafeList<Tweet>() tweets.resetList(listOf(*parsedTweets)) completion(tweets) Log.d("TwitterDataProvider", "Fetched tweet data successfully") } } catch (e: Exception) { Log.d("TwitterDataProvider", "Problem parsing Twitter JSON " + e.message) completion(ThreadSafeList()) // Return an empty list on an error } } } private interface TokenHandler { fun onCompletion(token: String?) } }
mit
4746e0de0a102fb5a391f86797feba79
36.564417
113
0.570402
5.118729
false
false
false
false
AoEiuV020/PaNovel
api/src/main/java/cc/aoeiuv020/panovel/api/NovelContext.kt
1
11827
package cc.aoeiuv020.panovel.api import cc.aoeiuv020.gson.GsonUtils import cc.aoeiuv020.gson.toBean import cc.aoeiuv020.gson.toJson import cc.aoeiuv020.log.debug import cc.aoeiuv020.panovel.api.site.* import com.google.gson.Gson import okhttp3.Cookie import okhttp3.Headers import org.slf4j.Logger import org.slf4j.LoggerFactory import java.io.File import java.net.MalformedURLException import java.net.URL /** * 小说网站的上下文, * Created by AoEiuV020 on 2017.10.02-15:25:48. */ @Suppress("MemberVisibilityCanPrivate") abstract class NovelContext { companion object { fun getAllSite(): List<NovelContext> = listOf( Piaotian(), Biquge(), Liudatxt(), Qidian(), Sfacg(), Snwx(), Syxs(), Yssm(), Qlwx(), Byzw(), Fenghuaju(), Yllxs(), Mianhuatang(), Gxwztv(), Ymoxuan(), Qingkan(), Ggdown(), Biqugebook(), Guanshuwang(), Jdxs520(), Lread(), Wenxuemi(), Yipinxia(), N360dxs(), N7dsw(), Aileleba(), Gulizw(), N73xs(), Siluke(), Wukong(), Exiaoshuo(), Dajiadu(), Liewen(), Qingkan5(), Bqg5200(), Lewen123(), Zaidudu(), Shangshu(), Haxds(), X23us(), Zhuishu(), N2kzw(), Shu8(), N52ranwen(), Kuxiaoshuo(), Zzdxsw(), Zhuaji(), Uctxt(), Lnovel(), Yidm(), Manhuagui(), SiFang(), Qinxiaoshuo(), N9txs(), N168kanshu(), Yunduwu(), N123du(), Biqugese(), Biqugezhh(), Shoudashu(), Kssw(), Biquge5200(), N69shu(), Kenshuzw(), Wukong0(), Ttkan() ).asReversed() const val sitesVersion = 12 // 用于存取cookie, private val gson: Gson = GsonUtils.gsonBuilder .disableHtmlEscaping() .setPrettyPrinting() .create() /** * 缓存文件夹,可以随时被删除的, */ private var sCacheDir: File? = null fun cache(cacheDir: File?) { this.sCacheDir = cacheDir?.takeIf { (it.exists() && it.isDirectory) || it.mkdirs() } } fun cleanCache() { sCacheDir?.deleteRecursively() } /** * 非缓存,不会随时被删除,不要放太大的东西, */ private var sFilesDir: File? = null fun files(filesDir: File?) { this.sFilesDir = filesDir?.takeIf { (it.exists() && it.isDirectory) || it.mkdirs() } } } @Suppress("MemberVisibilityCanPrivate") protected val logger: Logger = LoggerFactory.getLogger(this.javaClass.simpleName) /** * 用网站名当数据保存目录名,网站名不能重复, */ private val fileName get() = site.name /** * 缓存文件夹,可以随时被删除的, */ @Suppress("MemberVisibilityCanBePrivate") protected val mCacheDir: File? get() = sCacheDir?.resolve(fileName)?.apply { exists() || mkdirs() } /** * 非缓存,不会随时被删除,不要放太大的东西, */ @Suppress("MemberVisibilityCanBePrivate") protected val mFilesDir: File? get() = sFilesDir?.resolve(fileName)?.apply { exists() || mkdirs() } private val cookiesFile: File? get() = mFilesDir?.resolve("cookies") private var _cookies: Map<String, Cookie>? = null // name to Cookie, // 虽然浏览器支持相同name的不同cookie,按domain和path区分,但是这里一个context只有一个网站,不会有多个name, var cookies: Map<String, Cookie> @Synchronized get() = _cookies ?: (cookiesFile?.let { file -> try { file.readText().toBean<Map<String, Cookie>>(gson) } catch (e: Exception) { // 读取失败说明文件损坏,直接删除,下次保存, file.delete() null } } ?: mapOf()).also { _cookies = it } @Synchronized private set(value) { logger.debug { "setCookies $value" } if (value == _cookies) { return } _cookies = value cookiesFile?.writeText(value.toJson(gson)) } private val headersFile: File? get() = mFilesDir?.resolve("headers") private var _headers: Map<String, String>? = null // name to Cookie, // 虽然浏览器支持相同name的不同cookie,按domain和path区分,但是这里一个context只有一个网站,不会有多个name, var headers: Map<String, String> @Synchronized get() = _headers ?: (headersFile?.let { file -> try { file.readText().toBean<Map<String, String>>(gson) } catch (e: Exception) { // 读取失败说明文件损坏,直接删除,下次保存, file.delete() null } } ?: mapOf()).also { _headers = it } @Synchronized private set(value) { logger.debug { "setheaders $value" } if (value == _headers) { return } _headers = value headersFile?.writeText(value.toJson(gson)) } /** * 网站爬虫类里指定的编码, */ open val charset: String? get() = null val defaultCharset: String = "UTF-8" private val charsetFile: File? get() = mFilesDir?.resolve("charset") /** * 强制指定编码的缓存, */ private var _charset: String? = null /** * 强制指定编码, */ var forceCharset: String? @Synchronized get() = _charset ?: (charsetFile?.let { file -> try { file.readText().toBean<String>(gson) } catch (e: Exception) { // 读取失败说明文件损坏,直接删除,下次保存, file.delete() null } }).also { _charset = it } @Synchronized set(value) { logger.debug { "set charset $value" } if (value == _charset) { return } if (!value.isNullOrBlank()) { _charset = value charsetFile?.writeText(value.toJson(gson)) } else { _charset = null charsetFile?.delete() } } fun cleanData() { mFilesDir?.deleteRecursively() } fun cleanCache() { mCacheDir?.deleteRecursively() } /** * 保存okhttp得到的cookie, 不过滤, */ fun putCookies(cookies: List<Cookie>) { this.cookies = this.cookies + cookies.map { it.name() to it } } /** * 保存webView拿到的cookie, 由于只有name=value信息,没有超时之类的, * 过滤一下,value一样的就没必要更新了, */ fun putCookies(cookies: Map<String, Cookie>) { if (cookies.isEmpty()) { return } // 要确保setCookies被调用才会本地保存cookie, this.cookies = this.cookies + cookies.filter { (name, cookie) -> // 只更新value不同的,以免覆盖了okhttp拿到的包含超时等完整信息的cookie, this.cookies[name]?.value() != cookie.value() } } /** * 覆盖保存cookies, */ fun replaceCookies(cookies: Map<String, Cookie>) { this.cookies = cookies } fun removeCookies() { // 只要赋值了就会覆盖本地保存的, this.cookies = mapOf() } /** * 覆盖保存headers, */ fun replaceHeaders(headers: Headers) { val map = HashMap<String, String>(headers.size()) repeat(headers.size()) { map[headers.name(it)] = headers.value(it) } this.headers = map } /** * */ open fun cookieDomainList(): List<String> { val host = URL(site.baseUrl).host val domain = secondLevelDomain(host) return listOf(domain) } protected fun secondLevelDomain(host: String): String { val index1 = host.lastIndexOf('.') val index2 = host.lastIndexOf('.', index1 - 1) return if (index2 == -1) { // 可能没有第二个点.也就是已经是个二级域名, index2会为-1, host } else { host.substring(maxOf(index2, 0)) } } /** * 这个网站是否还有维护, */ open val upkeep: Boolean = true /** * 这个网站停止维护的原因, */ open val reason: String = "" /** * 这个网站是否隐藏, */ open val hide: Boolean = false /** * 这个网站是否需要登录, * 暂未实现具体功能,只做标记, */ open val login: Boolean = false abstract val site: NovelSite /** * 打开网站的话,可能不希望打开根目录,那就重写这个变量, */ val homePage: String get() = site.baseUrl /** * 获取搜索页面的下一页, * TODO: 考虑在搜索结果直接加上关于下一页的,或者干脆不要下一页吧,反正现在搜索结果和下一页分别获取解析页面挺浪费的, * */ open fun getNextPage(extra: String): String? = null /** * 搜索小说名, * */ abstract fun searchNovelName(name: String): List<NovelItem> /** * 获取小说详情页信息, * * @param extra [NovelItem.extra] 尽量直接让这个extra就是bookId, */ abstract fun getNovelDetail(extra: String): NovelDetail /** * 从给定地址找到这本小说, * 要尽可能支持, */ abstract fun getNovelItem(url: String): NovelItem /** * 获取小说章节列表, * * @param extra [NovelDetail.extra] */ abstract fun getNovelChaptersAsc(extra: String): List<NovelChapter> /** * 获取小说章节文本内容, * 正文段不包括开头的空格, * * @param extra [NovelChapter.extra] */ abstract fun getNovelContent( extra: String, listener: ((Long, Long) -> Unit)? = null ): List<String> /** * 判断这个地址是不是属于这个网站, * 默认对比二级域名,正常情况所有三级域名都是一个同一个网站同一个NovelContext的, * 有的网站可能用到站外地址,比如使用了百度搜索,不能单纯缓存host, */ open fun check(url: String): Boolean = try { secondLevelDomain(URL(site.baseUrl).host) == secondLevelDomain(URL(url).host) } catch (_: Exception) { false } /** * 以下几个都是为了得到真实地址,毕竟extra现在支持各种随便写法, * 要快,要能在ui线程使用,不能有网络请求, */ abstract fun getNovelDetailUrl(extra: String): String abstract fun getNovelContentUrl(extra: String): String /** * 尝试从extra获取真实地址, * 只支持extra本身就是完整地址和extra为斜杆/开头的file两种情况, */ protected fun absUrl(extra: String): String = try { // 先尝试extra是否是个合法的地址 // 好像没必要,URL会直接判断, URL(extra) } catch (e: MalformedURLException) { // 再尝试extra当成spec部分,拼接上网站baseUrl, URL(URL(site.baseUrl), extra) }.toExternalForm() /** * 从extra中获取图片URL, 正常直接就是完整路径, * TODO: 考虑缓存主页URL, */ open fun getImage(extra: String): URL = URL(URL(site.baseUrl), extra) }
gpl-3.0
1b3b65b69c86860eef951a54afdce6ef
24.691139
96
0.539076
3.514721
false
false
false
false
henrikfroehling/timekeeper
models/src/main/kotlin/de/froehling/henrik/timekeeper/models/Tag.kt
1
574
package de.froehling.henrik.timekeeper.models import android.graphics.Color import android.support.annotation.ColorInt import io.realm.RealmList import io.realm.RealmObject import io.realm.annotations.PrimaryKey import io.realm.annotations.Required class Tag : RealmObject() { @PrimaryKey var uuid: String? = null @Required var name: String? = null @ColorInt var color: Int = Color.TRANSPARENT var projects: RealmList<Project>? = null var tasks: RealmList<Task>? = null @Required var modified: Long = 0 @Required var created: Long = 0 }
gpl-3.0
7cfbc0203ec4532c511d39dbc76edd7a
21.96
48
0.740418
4.013986
false
false
false
false
cloose/luftbild4p3d
src/main/kotlin/org/luftbild4p3d/osm/Node.kt
1
429
package org.luftbild4p3d.osm import java.math.BigDecimal import javax.xml.bind.annotation.XmlAccessType import javax.xml.bind.annotation.XmlAccessorType import javax.xml.bind.annotation.XmlAttribute @XmlAccessorType(XmlAccessType.FIELD) class Node(@XmlAttribute val id: Long = 0, @XmlAttribute(name ="lat") val latitude: BigDecimal = BigDecimal.ZERO, @XmlAttribute(name ="lon") val longitude: BigDecimal = BigDecimal.ZERO) { }
gpl-3.0
b3066343e82bced54bd6c2f3420373aa
42
188
0.806527
3.698276
false
false
false
false
rsiebert/TVHClient
app/src/main/java/org/tvheadend/tvhclient/ui/features/settings/ConnectionValidator.kt
1
5147
package org.tvheadend.tvhclient.ui.features.settings import org.tvheadend.data.entity.Connection import timber.log.Timber import java.net.URI import java.net.URISyntaxException import java.util.regex.Pattern class ConnectionValidator { fun isConnectionInputValid(connection: Connection): ValidationResult { Timber.d("Validating input before saving") var status = isConnectionNameValid(connection.name) if (status != ValidationResult.Success()) { return status } status = isConnectionUrlValid(connection.serverUrl) if (status != ValidationResult.Success()) { return status } status = isConnectionUrlValid(connection.streamingUrl) if (status != ValidationResult.Success()) { return status } if (connection.isWolEnabled) { status = isConnectionWolPortValid(connection.wolPort) if (status != ValidationResult.Success()) { return status } status = isConnectionWolMacAddressValid(connection.wolMacAddress) if (status != ValidationResult.Success()) { return status } } return ValidationResult.Success() } fun isConnectionNameValid(value: String?): ValidationResult { if (value.isNullOrEmpty()) { return ValidationResult.Failed(ValidationFailureReason.NameEmpty()) } // Check if the name contains only valid characters. val pattern = Pattern.compile("^[0-9a-zA-Z_\\-.]*$") val matcher = pattern.matcher(value) return if (matcher.matches()) { ValidationResult.Success() } else { ValidationResult.Failed(ValidationFailureReason.NameInvalid()) } } fun isConnectionUrlValid(value: String?): ValidationResult { // Do not allow an empty serverUrl if (value.isNullOrEmpty()) { return ValidationResult.Failed(ValidationFailureReason.UrlEmpty()) } lateinit var uri: URI try { uri = URI(value) } catch (e: URISyntaxException) { return ValidationResult.Failed(ValidationFailureReason.UrlSchemeMissing()) } if (uri.scheme.isNullOrEmpty()) { return ValidationResult.Failed(ValidationFailureReason.UrlSchemeMissing()) } if (uri.scheme != "http" && uri.scheme != "https") { return ValidationResult.Failed(ValidationFailureReason.UrlSchemeWrong()) } if (uri.host.isNullOrEmpty()) { return ValidationResult.Failed(ValidationFailureReason.UrlHostMissing()) } if (uri.port == -1) { return ValidationResult.Failed(ValidationFailureReason.UrlPortMissing()) } if (uri.port < 0 || uri.port > 65535) { return ValidationResult.Failed(ValidationFailureReason.UrlPortInvalid()) } if (!uri.userInfo.isNullOrEmpty()) { return ValidationResult.Failed(ValidationFailureReason.UrlUnneededCredentials()) } return ValidationResult.Success() } fun isConnectionWolMacAddressValid(value: String?): ValidationResult { // Do not allow an empty address if (value.isNullOrEmpty()) { return ValidationResult.Failed(ValidationFailureReason.MacAddressEmpty()) } // Check if the MAC address is valid val pattern = Pattern.compile("([0-9a-fA-F]{2}(?::|-|$)){6}") val matcher = pattern.matcher(value) return if (matcher.matches()) { ValidationResult.Success() } else { ValidationResult.Failed(ValidationFailureReason.MacAddressInvalid()) } } fun isConnectionWolPortValid(port: Int): ValidationResult { if (port < 0 || port > 65535) { return ValidationResult.Failed(ValidationFailureReason.UrlPortInvalid()) } return ValidationResult.Success() } } sealed class ValidationResult { data class Success(val message: String = "") : ValidationResult() data class Failed(val reason: ValidationFailureReason) : ValidationResult() } sealed class ValidationFailureReason { data class NameEmpty(val message: String = "") : ValidationFailureReason() data class NameInvalid(val message: String = "") : ValidationFailureReason() data class UrlEmpty(val message: String = "") : ValidationFailureReason() data class UrlSchemeMissing(val message: String = "") : ValidationFailureReason() data class UrlSchemeWrong(val message: String = "") : ValidationFailureReason() data class UrlHostMissing(val message: String = "") : ValidationFailureReason() data class UrlPortMissing(val message: String = "") : ValidationFailureReason() data class UrlPortInvalid(val message: String = "") : ValidationFailureReason() data class UrlUnneededCredentials(val message: String = "") : ValidationFailureReason() data class MacAddressEmpty(val message: String = "") : ValidationFailureReason() data class MacAddressInvalid(val message: String = "") : ValidationFailureReason() }
gpl-3.0
4266ea99cf7fb1ff275a2211e7107728
40.176
92
0.653973
5.080948
false
false
false
false
nemerosa/ontrack
ontrack-extension-license/src/main/java/net/nemerosa/ontrack/extension/license/remote/stripe/StripeModel.kt
1
1452
package net.nemerosa.ontrack.extension.license.remote.stripe import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty @JsonIgnoreProperties(ignoreUnknown = true) data class StripeSubscription( override val id: String, val customer: String, val items: StripeCollection<StripeSubscriptionItem>, override val metadata: Map<String, String>, val status: String, @JsonProperty("current_period_end") val currentPeriodEnd: Long, ) : StripeMetadataContainer { fun extractFirstPrice(): StripePrice = items.data.firstOrNull()?.price ?: error("Stripe subsccription has no price associated with it") fun extractActiveFlag(): Boolean = status == "trialing" || status == "active" } @JsonIgnoreProperties(ignoreUnknown = true) data class StripeCustomer( val id: String, val name: String, ) @JsonIgnoreProperties(ignoreUnknown = true) data class StripeCollection<T>( val data: List<T>, ) @JsonIgnoreProperties(ignoreUnknown = true) data class StripeSubscriptionItem( val id: String, val price: StripePrice, ) @JsonIgnoreProperties(ignoreUnknown = true) data class StripePrice( override val id: String, override val metadata: Map<String, String>, ) : StripeMetadataContainer interface StripeEntity { val id: String } interface StripeMetadataContainer : StripeEntity { val metadata: Map<String, String> }
mit
9b1d42fa5e0ee6c63d56adc69dfc86fe
26.396226
76
0.740358
4.373494
false
false
false
false