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
petrbalat/jlib
src/main/java/cz/softdeluxe/jlib/validation/IcConstraintValidator.kt
1
1163
package cz.softdeluxe.jlib.validation import javax.validation.ConstraintValidator import javax.validation.ConstraintValidatorContext /** * Validator pro overeni IČ firem * viz http://latrine.dgx.cz/jak-overit-platne-ic-a-rodne-cislo * @author Petr Balat */ class IcConstraintValidator : ConstraintValidator<IcValid, String> { override fun initialize(constraint: IcValid) { } override fun isValid(ic: String?, context: ConstraintValidatorContext?): Boolean { if (ic == null || ic.isBlank()) { return true } if (ic.length != ICO_LENGTH) { return false } var soucet = 0 for (it in 0..ICO_LENGTH - 2) { val cislo: Int = ic.substring(it, it + 1).toIntOrNull() ?: return false soucet += cislo * (ICO_LENGTH - it) } val zbytek = soucet % 11 val posledniCislo = ic.substring(ICO_LENGTH - 1, ICO_LENGTH).toInt() when (zbytek) { 0, 10 -> return posledniCislo == 1 1 -> return posledniCislo == 0 else -> return posledniCislo == 11 - zbytek } } } const val ICO_LENGTH = 8
apache-2.0
4c5d400b113dfcc5cbb2a222254dbf0e
26.023256
86
0.599828
3.479042
false
false
false
false
stephan-james/intellij-extend
src/com/sjd/intellijextend/IntelliJExtendComponent.kt
1
3061
/* * Copyright (c) 2019, http://stephan-james.github.io/intellij-extend * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the project nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.sjd.intellijextend import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.options.ShowSettingsUtil import com.intellij.openapi.project.Project import com.intellij.util.xmlb.XmlSerializerUtil @State( name = IntelliJExtend.ID, storages = [Storage(IntelliJExtend.ID + ".xml")] ) class IntelliJExtendComponent : PersistentStateComponent<IntelliJExtendSettings> { private val settings = IntelliJExtendSettings() override fun getState() = settings override fun loadState(state: IntelliJExtendSettings) { XmlSerializerUtil.copyBean(state, settings) } companion object { private val instance get() = ApplicationManager.getApplication().getComponent(IntelliJExtendComponent::class.java) var command get() = instance.state.command set(value) { instance.state.command = value } var transferPath get() = instance.state.transferPath set(value) { instance.state.transferPath = value } fun openSettingsIfNotConfigured(project: Project) = instance.state.valid() || ShowSettingsUtil.getInstance().editConfigurable(project, IntelliJExtendConfiguration()) } }
bsd-3-clause
b6cd1f5c11f3e7452e2c8ccfdb0ebe19
38.753247
129
0.737014
4.874204
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/ide/inspections/RsLint.kt
4
1451
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.inspections import com.intellij.psi.PsiElement import org.rust.lang.core.psi.ext.RsDocAndAttributeOwner import org.rust.lang.core.psi.ext.RsMod import org.rust.lang.core.psi.ext.queryAttributes import org.rust.lang.core.psi.ext.superMods import org.rust.lang.core.psi.ext.ancestors /** * Rust lints. */ enum class RsLint( val id: String, val defaultLevel: RsLintLevel = RsLintLevel.WARN ) { NonSnakeCase("non_snake_case"), NonCamelCaseTypes("non_camel_case_types"), NonUpperCaseGlobals("non_upper_case_globals"), BadStyle("bad_style"); /** * Returns the level of the lint for the given PSI element. */ fun levelFor(el: PsiElement) = explicitLevel(el) ?: superModsLevel(el) ?: defaultLevel private fun explicitLevel(el: PsiElement) = el.ancestors .filterIsInstance<RsDocAndAttributeOwner>() .flatMap { it.queryAttributes.metaItems } .filter { it.metaItemArgs?.metaItemList.orEmpty().any { it.text == id || it.text == BadStyle.id } } .mapNotNull { RsLintLevel.valueForId(it.identifier.text) } .firstOrNull() private fun superModsLevel(el: PsiElement) = el.ancestors .filterIsInstance<RsMod>() .lastOrNull() ?.superMods ?.mapNotNull { explicitLevel(it) }?.firstOrNull() }
mit
3210d5499a529904b730784cedb0abe3
29.87234
107
0.682288
3.730077
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/ide/annotator/RsCargoCheckAnnotator.kt
1
9494
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.annotator import com.google.gson.JsonParser import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.ExternalAnnotator import com.intellij.lang.annotation.HighlightSeverity import com.intellij.lang.annotation.ProblemGroup import com.intellij.openapi.application.Result import com.intellij.openapi.application.WriteAction import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtil import com.intellij.openapi.util.TextRange import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiFile import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiModificationTracker import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.PathUtil import org.apache.commons.lang.StringEscapeUtils.escapeHtml import org.rust.cargo.project.settings.rustSettings import org.rust.cargo.project.settings.toolchain import org.rust.cargo.project.workspace.PackageOrigin import org.rust.cargo.toolchain.* import org.rust.ide.RsConstants import org.rust.lang.core.psi.RsFile import org.rust.lang.core.psi.RsFunction import org.rust.lang.core.psi.ext.RsCompositeElement import org.rust.lang.core.psi.ext.cargoWorkspace import org.rust.lang.core.psi.ext.containingCargoPackage import org.rust.utils.pathAsPath import java.nio.file.Path import java.util.* data class CargoCheckAnnotationInfo( val file: VirtualFile, val toolchain: RustToolchain, val projectPath: Path, val module: Module ) class CargoCheckAnnotationResult(commandOutput: List<String>) { companion object { private val parser = JsonParser() private val messageRegex = """\s*\{\s*"message".*""".toRegex() } val messages: List<CargoTopMessage> = commandOutput .filter { messageRegex.matches(it) } .map { parser.parse(it) } .filter { it.isJsonObject } .mapNotNull { CargoTopMessage.fromJson(it.asJsonObject) } } class RsCargoCheckAnnotator : ExternalAnnotator<CargoCheckAnnotationInfo, CargoCheckAnnotationResult>() { override fun collectInformation(file: PsiFile, editor: Editor, hasErrors: Boolean): CargoCheckAnnotationInfo? { if (file !is RsFile) return null if (!file.project.rustSettings.useCargoCheckAnnotator) return null val ws = file.cargoWorkspace ?: return null val module = ModuleUtil.findModuleForFile(file.virtualFile, file.project) ?: return null val projectRoot = ws.contentRoot ?: return null val toolchain = module.project.toolchain ?: return null return CargoCheckAnnotationInfo(file.virtualFile, toolchain, projectRoot, module) } override fun doAnnotate(info: CargoCheckAnnotationInfo): CargoCheckAnnotationResult? = CachedValuesManager.getManager(info.module.project) .getCachedValue(info.module, { CachedValueProvider.Result.create( checkProject(info), PsiModificationTracker.MODIFICATION_COUNT) }) override fun apply(file: PsiFile, annotationResult: CargoCheckAnnotationResult?, holder: AnnotationHolder) { if (annotationResult == null) return val fileOrigin = (file as? RsCompositeElement)?.containingCargoPackage?.origin if (fileOrigin != PackageOrigin.WORKSPACE) return val doc = file.viewProvider.document ?: error("Can't find document for $file in Cargo check annotator") for (topMessage in annotationResult.messages) { val message = filterMessage(file, doc, topMessage.message) ?: continue holder.createAnnotation(message.severity, message.textRange, message.message, message.htmlTooltip) .apply { problemGroup = ProblemGroup { message.message } setNeedsUpdateOnTyping(true) } } } } // NB: executed asynchronously off EDT, so care must be taken not to access // disposed objects private fun checkProject(info: CargoCheckAnnotationInfo): CargoCheckAnnotationResult? { // We have to save the file to disk to give cargo a chance to check fresh file content. object : WriteAction<Unit>() { override fun run(result: Result<Unit>) { val fileDocumentManager = FileDocumentManager.getInstance() val document = fileDocumentManager.getDocument(info.file) if (document == null) { fileDocumentManager.saveAllDocuments() } else if (fileDocumentManager.isDocumentUnsaved(document)) { fileDocumentManager.saveDocument(document) } } }.execute() val output = info.toolchain.cargo(info.projectPath).checkProject(info.module) if (output.isCancelled) return null return CargoCheckAnnotationResult(output.stdoutLines) } private data class FilteredMessage( val severity: HighlightSeverity, val textRange: TextRange, val message: String, val htmlTooltip: String ) private fun filterMessage(file: PsiFile, document: Document, message: RustcMessage): FilteredMessage? { if (message.message.startsWith("aborting due to") || message.message.startsWith("cannot continue")) { return null } val severity = when (message.level) { "error" -> HighlightSeverity.ERROR "warning" -> HighlightSeverity.WEAK_WARNING else -> HighlightSeverity.INFORMATION } val span = message.spans .firstOrNull { it.is_primary && it.isValid() } // Some error messages are global, and we *could* show then atop of the editor, // but they look rather ugly, so just skip them. ?: return null val syntaxErrors = listOf("expected pattern", "unexpected token") if (syntaxErrors.any { it in span.label.orEmpty() || it in message.message }) { return null } val spanFilePath = PathUtil.toSystemIndependentName(span.file_name) if (!file.virtualFile.path.endsWith(spanFilePath)) return null @Suppress("NAME_SHADOWING") fun toOffset(line: Int, column: Int): Int? { val line = line - 1 val column = column - 1 if (line >= document.lineCount) return null return (document.getLineStartOffset(line) + column) .takeIf { it <= document.textLength } } // The compiler message lines and columns are 1 based while intellij idea are 0 based val startOffset = toOffset(span.line_start, span.column_start) val endOffset = toOffset(span.line_end, span.column_end) var textRange = if (startOffset != null && endOffset != null && startOffset < endOffset) { TextRange(startOffset, endOffset) } else { return null } if ("function is never used" in message.message) { val fn = PsiTreeUtil.findElementOfClassAtOffset(file, textRange.startOffset, RsFunction::class.java, false) if (fn != null && fn.textRange.endOffset == textRange.endOffset) { textRange = fn.identifier.textRange } } val tooltip = with(ArrayList<String>()) { val code = message.code.formatAsLink() add(escapeHtml(message.message) + if (code == null) "" else " $code") if (span.label != null && !message.message.startsWith(span.label)) { add(escapeHtml(span.label)) } message.children .filter { !it.message.isBlank() } .map { "${it.level.capitalize()}: ${escapeHtml(it.message)}" } .forEach { add(it) } this .map { formatLine(it) } .joinToString("<br>") } return FilteredMessage(severity, textRange, message.message, tooltip) } private fun RustcSpan.isValid() = line_end > line_start || (line_end == line_start && column_end >= column_start) private fun ErrorCode?.formatAsLink() = if (this?.code.isNullOrBlank()) null else "<a href=\"${RsConstants.ERROR_INDEX_URL}#${this?.code}\">${this?.code}</a>" private fun formatLine(line: String): String { data class Group(val isList: Boolean, val lines: ArrayList<String>) val (lastGroup, groups) = line.split("\n").fold( Pair(null as Group?, ArrayList<Group>()), { (group: Group?, acc: ArrayList<Group>), line -> val (isListItem, line) = if (line.startsWith("-")) { true to line.substring(2) } else { false to line } when { group == null -> Pair(Group(isListItem, arrayListOf(line)), acc) group.isList == isListItem -> { group.lines.add(line) Pair(group, acc) } else -> { acc.add(group) Pair(Group(isListItem, arrayListOf(line)), acc) } } }) if (lastGroup != null && lastGroup.lines.isNotEmpty()) groups.add(lastGroup) return groups .map { if (it.isList) "<ul>${it.lines.joinToString("<li>", "<li>")}</ul>" else it.lines.joinToString("<br>") }.joinToString() }
mit
2473fbc08e2e8b9c67e8bf75c1dc8265
37.593496
115
0.661892
4.512357
false
false
false
false
wuseal/JsonToKotlinClass
src/main/kotlin/wu/seal/jsontokotlin/ui/AdvancedOtherTab.kt
1
2430
package wu.seal.jsontokotlin.ui import com.intellij.util.ui.JBDimension import wu.seal.jsontokotlin.model.ConfigManager import java.awt.BorderLayout import javax.swing.JPanel /** * others settings tab in config settings dialog * Created by Seal.Wu on 2018/2/6. */ class AdvancedOtherTab(isDoubleBuffered: Boolean) : JPanel(BorderLayout(), isDoubleBuffered) { init { jVerticalLinearLayout { alignLeftComponent { jCheckBox("Enable Comment", ConfigManager.isCommentOff.not(), { isSelected -> ConfigManager.isCommentOff = isSelected.not() }) jCheckBox("Enable Order By Alphabetical", ConfigManager.isOrderByAlphabetical, { isSelected -> ConfigManager.isOrderByAlphabetical = isSelected }) jCheckBox("Enable Inner Class Model", ConfigManager.isInnerClassModel, { isSelected -> ConfigManager.isInnerClassModel = isSelected }) jCheckBox("Enable Map Type when JSON Field Key Is Primitive Type", ConfigManager.enableMapType, { isSelected -> ConfigManager.enableMapType = isSelected }) jCheckBox("Only create annotations when needed", ConfigManager.enableMinimalAnnotation, { isSelected -> ConfigManager.enableMinimalAnnotation = isSelected }) jCheckBox("Auto detect JSON Scheme", ConfigManager.autoDetectJsonScheme, { isSelected -> ConfigManager.autoDetectJsonScheme = isSelected }) jHorizontalLinearLayout { jLabel("Indent (number of space): ") jTextInput(ConfigManager.indent.toString()) { columns = 2 addFocusLostListener { ConfigManager.indent = try { text.toInt() } catch (e: Exception) { text = ConfigManager.indent.toString() ConfigManager.indent } } } } } jHorizontalLinearLayout { jLabel("Parent Class Template: ") jTextInput(ConfigManager.parenClassTemplate) { addFocusLostListener { ConfigManager.parenClassTemplate = text } maximumSize = JBDimension(400, 30) } } } } }
gpl-3.0
4ec1a741fe258c7bf52767de0e9bf779
41.631579
173
0.582305
5.898058
false
true
false
false
paronos/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupCreatorJob.kt
3
1441
package eu.kanade.tachiyomi.data.backup import android.net.Uri import com.evernote.android.job.Job import com.evernote.android.job.JobManager import com.evernote.android.job.JobRequest import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get class BackupCreatorJob : Job() { override fun onRunJob(params: Params): Result { val preferences = Injekt.get<PreferencesHelper>() val backupManager = BackupManager(context) val uri = Uri.parse(preferences.backupsDirectory().getOrDefault()) val flags = BackupCreateService.BACKUP_ALL backupManager.createBackup(uri, flags, true) return Result.SUCCESS } companion object { const val TAG = "BackupCreator" fun setupTask(prefInterval: Int? = null) { val preferences = Injekt.get<PreferencesHelper>() val interval = prefInterval ?: preferences.backupInterval().getOrDefault() if (interval > 0) { JobRequest.Builder(TAG) .setPeriodic(interval * 60 * 60 * 1000L, 10 * 60 * 1000) .setUpdateCurrent(true) .build() .schedule() } } fun cancelTask() { JobManager.instance().cancelAllForTag(TAG) } } }
apache-2.0
046ad790a1fe518c1550df4c41e2bf89
33.309524
86
0.636364
4.648387
false
false
false
false
bornest/KotlinUtils
rx2/src/main/java/com/github/kotlinutils/rx2/extensions/flowable.kt
1
9464
@file:Suppress("NOTHING_TO_INLINE") package com.github.kotlinutils.rx2.extensions import com.github.unitimber.core.extensions.e import io.reactivex.BackpressureStrategy import io.reactivex.Flowable import io.reactivex.FlowableEmitter import io.reactivex.FlowableTransformer import io.reactivex.functions.BiFunction import io.reactivex.functions.Function3 import org.reactivestreams.Publisher //region Creation /** * Returns a Flowable that emits the object this method was called on and then completes */ inline fun <T : Any> T.toSingletonFlowable(): Flowable<T> = Flowable.just(this) /** * Create a [Flowable] * * This method is equivalent to Flowable.create() but allows more idiomatic usage in Kotlin (by leaving lambda parameter outside of the brackets) * * @param T type of items to be emitted by this Flowable * @param backpressureStrategy the backpressure mode to apply if the downstream Subscriber doesn't request (fast) enough * @param source lambda with [FlowableEmitter] parameter that is called when a Subscriber subscribes to the returned Flowable * * @see Flowable.create */ inline fun <T : Any> createFlowable(backpressureStrategy: BackpressureStrategy = BackpressureStrategy.BUFFER, crossinline source: (FlowableEmitter<T>) -> Unit ): Flowable<T> { return Flowable.create<T>( { emitter -> source(emitter) }, backpressureStrategy ) } //endregion //region logging Emitter inline fun FlowableEmitter<*>.loggingOnError(loggingEnabled: Boolean = true, errorMessage: () -> String ) { e(loggingEnabled, null, errorMessage) this.onError(Throwable(errorMessage())) } //endregion //region combineLatest inline fun <reified T1 : Any, T2 : Any, R : Any> flowableCombineLatest(f1: Flowable<T1>, f2: Flowable<T2>, noinline combineFunction: (T1, T2) -> R ): Flowable<R> { return Flowable.combineLatest( f1, f2, BiFunction<T1, T2, R>(combineFunction) ) } inline fun <reified T1 : Any, T2 : Any> flowableCombineLatest(f1: Flowable<T1>, f2: Flowable<T2> ): Flowable<Pair<T1, T2>> { return flowableCombineLatest(f1, f2) { t1, t2 -> t1 to t2 } } inline fun <reified T1 : Any, T2 : Any, T3 : Any, R : Any> flowableCombineLatest(f1: Flowable<T1>, f2: Flowable<T2>, f3: Flowable<T3>, noinline combineFunction: (T1, T2, T3) -> R ): Flowable<R> { return Flowable.combineLatest( f1, f2, f3, Function3<T1, T2, T3, R>(combineFunction) ) } inline fun <reified T1 : Any, T2 : Any, T3 : Any> flowableCombineLatest(f1: Flowable<T1>, f2: Flowable<T2>, f3: Flowable<T3> ): Flowable<Triple<T1, T2, T3>> { return flowableCombineLatest(f1, f2, f3) { t1, t2, t3 -> Triple(t1, t2, t3) } } //endregion //region combineLatestWith inline fun <reified T1 : Any, T2 : Any, R : Any> Flowable<T1>.combineLatestWith(f2: Flowable<T2>, noinline combineFunction: (T1, T2) -> R ): Flowable<R> { return flowableCombineLatest(this, f2, combineFunction) } inline fun <reified T1 : Any, T2 : Any> Flowable<T1>.combineLatestWith(f2: Flowable<T2>): Flowable<Pair<T1, T2>> { return flowableCombineLatest(this, f2) { t1, t2 -> t1 to t2 } } inline fun <reified T1 : Any, T2 : Any, T3 : Any, R : Any> Flowable<T1>.combineLatestWith(f2: Flowable<T2>, f3: Flowable<T3>, noinline combineFunction: (T1, T2, T3) -> R ): Flowable<R> { return flowableCombineLatest(this, f2, f3, combineFunction) } inline fun <reified T1 : Any, T2 : Any, T3 : Any> Flowable<T1>.combineLatestWith(f2: Flowable<T2>, f3: Flowable<T3> ): Flowable<Triple<T1, T2, T3>> { return flowableCombineLatest(this, f2, f3) { t1, t2, t3 -> Triple(t1, t2, t3) } } //endregion //region zip inline fun <reified T1 : Any, T2 : Any, R : Any> flowableZip(f1: Flowable<T1>, f2: Flowable<T2>, noinline zipFunction: (T1, T2) -> R ): Flowable<R> { return Flowable.zip( f1, f2, BiFunction<T1, T2, R>(zipFunction) ) } inline fun <reified T1 : Any, T2 : Any> flowableZip(f1: Flowable<T1>, f2: Flowable<T2> ): Flowable<Pair<T1, T2>> { return flowableZip(f1, f2) { t1, t2 -> t1 to t2 } } inline fun <reified T1 : Any, T2 : Any, T3 : Any, R : Any> flowableZip(f1: Flowable<T1>, f2: Flowable<T2>, f3: Flowable<T3>, noinline zipFunction: (T1, T2, T3) -> R ): Flowable<R> { return Flowable.zip( f1, f2, f3, Function3<T1, T2, T3, R>(zipFunction) ) } inline fun <reified T1 : Any, T2 : Any, T3 : Any> flowableZip(f1: Flowable<T1>, f2: Flowable<T2>, f3: Flowable<T3> ): Flowable<Triple<T1, T2, T3>> { return flowableZip(f1, f2, f3) { t1, t2, t3 -> Triple(t1, t2, t3) } } //endregion //region zipWith inline fun <reified T1 : Any, T2 : Any, R : Any> Flowable<T1>.zipWith(f2: Flowable<T2>, noinline zipFunction: (T1, T2) -> R ): Flowable<R> { return flowableZip(this, f2, zipFunction) } inline fun <reified T1 : Any, T2 : Any> Flowable<T1>.zipWith(f2: Flowable<T2>): Flowable<Pair<T1, T2>> { return flowableZip(this, f2) { t1, t2 -> t1 to t2 } } inline fun <reified T1 : Any, T2 : Any, T3 : Any, R : Any> Flowable<T1>.zipWith(f2: Flowable<T2>, f3: Flowable<T3>, noinline zipFunction: (T1, T2, T3) -> R ): Flowable<R> { return flowableZip(this, f2, f3, zipFunction) } inline fun <reified T1 : Any, T2 : Any, T3 : Any> Flowable<T1>.zipWith(f2: Flowable<T2>, f3: Flowable<T3> ): Flowable<Triple<T1, T2, T3>> { return flowableZip(this, f2, f3) { t1, t2, t3 -> Triple(t1, t2, t3) } } //endregion //region doOn* inline fun <T : Any, R : Any> Flowable<T>.doOnNth(n: Int, crossinline action: (T) -> R): Flowable<T> { return this.compose(object : FlowableTransformer<T, T> { var count = 0 override fun apply(sourceObs: Flowable<T>): Publisher<T> { return sourceObs.doOnNext { count++ if (count == n) { action(it) } } } }) } inline fun <T : Any, R : Any> Flowable<T>.doOnFirst(crossinline action: (T) -> R): Flowable<T> { return this.compose(object : FlowableTransformer<T, T> { var done = false override fun apply(sourceObs: Flowable<T>): Publisher<T> { return sourceObs.doOnNext { if (done) { action(it) done = true } } } }) } inline fun <T : Any, R : Any> Flowable<T>.doOnNextIf(condition: Boolean, crossinline action: (T) -> R ): Flowable<T> { return if (condition) { this.doOnNext { action(it) } } else { this } } //endregion
apache-2.0
c67028de8b6de9abcf6bed208f723132
36.26378
149
0.44907
4.36129
false
true
false
false
blackbbc/Tucao
app/src/main/kotlin/me/sweetll/tucao/business/home/fragment/BangumiFragment.kt
1
6948
package me.sweetll.tucao.business.home.fragment import android.annotation.TargetApi import androidx.databinding.DataBindingUtil import android.os.Build import android.os.Bundle import androidx.core.app.ActivityOptionsCompat import androidx.core.util.Pair import android.transition.ArcMotion import android.transition.ChangeBounds import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.LinearLayoutManager import androidx.transition.TransitionManager import com.bigkoo.convenientbanner.ConvenientBanner import com.chad.library.adapter.base.BaseQuickAdapter import com.chad.library.adapter.base.listener.OnItemChildClickListener import me.sweetll.tucao.R import me.sweetll.tucao.base.BaseFragment import me.sweetll.tucao.business.channel.ChannelDetailActivity import me.sweetll.tucao.business.home.adapter.BangumiAdapter import me.sweetll.tucao.business.home.adapter.BannerHolder import me.sweetll.tucao.business.home.viewmodel.BangumiViewModel import me.sweetll.tucao.business.video.VideoActivity import me.sweetll.tucao.databinding.FragmentBangumiBinding import me.sweetll.tucao.databinding.HeaderBangumiBinding import me.sweetll.tucao.model.raw.Bangumi import me.sweetll.tucao.model.raw.Banner class BangumiFragment : BaseFragment() { lateinit var binding: FragmentBangumiBinding lateinit var headerBinding: HeaderBangumiBinding val viewModel = BangumiViewModel(this) val bangumiAdapter = BangumiAdapter(null) var isLoad = false override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_bangumi, container, false) binding.viewModel = viewModel binding.loading.show() return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.swipeRefresh.isEnabled = false binding.swipeRefresh.setColorSchemeResources(R.color.colorPrimary) binding.swipeRefresh.setOnRefreshListener { viewModel.loadData() } binding.errorStub.setOnInflateListener { _, inflated -> inflated.setOnClickListener { viewModel.loadData() } } setupRecyclerView() loadWhenNeed() if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { initTransition() } } fun setupRecyclerView() { headerBinding = DataBindingUtil.inflate(LayoutInflater.from(activity), R.layout.header_bangumi, binding.root as ViewGroup, false) headerBinding.viewModel = viewModel bangumiAdapter.addHeaderView(headerBinding.root) binding.bangumiRecycler.layoutManager = LinearLayoutManager(activity) binding.bangumiRecycler.adapter = bangumiAdapter binding.bangumiRecycler.addOnItemTouchListener(object: OnItemChildClickListener() { override fun onSimpleItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) { when (view.id) { R.id.card_more -> { ChannelDetailActivity.intentTo(activity!!, view.tag as Int) } R.id.card1, R.id.card2, R.id.card3, R.id.card4 -> { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val coverImg = (((view as ViewGroup).getChildAt(0) as ViewGroup).getChildAt(0) as ViewGroup).getChildAt(0) val titleText = (view.getChildAt(0) as ViewGroup).getChildAt(1) val p1: Pair<View, String> = Pair.create(coverImg, "cover") val p2: Pair<View, String> = Pair.create(titleText, "bg") val cover = titleText.tag as String val options = ActivityOptionsCompat .makeSceneTransitionAnimation(activity!!, p1, p2) VideoActivity.intentTo(activity!!, view.tag as String, cover, options.toBundle()) } else { VideoActivity.intentTo(activity!!, view.tag as String) } } } } }) } @TargetApi(Build.VERSION_CODES.LOLLIPOP) fun initTransition() { val changeBounds = ChangeBounds() val arcMotion = ArcMotion() changeBounds.pathMotion = arcMotion activity!!.window.sharedElementExitTransition = changeBounds activity!!.window.sharedElementReenterTransition = null } override fun setUserVisibleHint(isVisibleToUser: Boolean) { super.setUserVisibleHint(isVisibleToUser) loadWhenNeed() } fun loadWhenNeed() { if (isVisible && userVisibleHint && !isLoad && !binding.swipeRefresh.isRefreshing) { viewModel.loadData() } } fun loadBangumi(bangumi: Bangumi) { if (!isLoad) { isLoad = true TransitionManager.beginDelayedTransition(binding.swipeRefresh) binding.swipeRefresh.isEnabled = true binding.loading.visibility = View.GONE if (binding.errorStub.isInflated) { binding.errorStub.root.visibility = View.GONE } binding.bangumiRecycler.visibility = View.VISIBLE } bangumiAdapter.setNewData(bangumi.recommends) headerBinding.banner.setPages({ BannerHolder() }, bangumi.banners) .setPageIndicator(intArrayOf(R.drawable.indicator_white_circle, R.drawable.indicator_pink_circle)) .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT) .startTurning(3000) } fun loadError() { if (!isLoad) { TransitionManager.beginDelayedTransition(binding.swipeRefresh) binding.loading.visibility = View.GONE if (!binding.errorStub.isInflated) { binding.errorStub.viewStub!!.visibility = View.VISIBLE } else { binding.errorStub.root.visibility = View.VISIBLE } } } fun setRefreshing(isRefreshing: Boolean) { if (isLoad) { binding.swipeRefresh.isRefreshing = isRefreshing } else { TransitionManager.beginDelayedTransition(binding.swipeRefresh) binding.loading.visibility = if (isRefreshing) View.VISIBLE else View.GONE if (isRefreshing) { if (!binding.errorStub.isInflated) { binding.errorStub.viewStub!!.visibility = View.GONE } else { binding.errorStub.root.visibility = View.GONE } } } } }
mit
2de1fda01c79327f7771bab8bf6c3d4b
39.637427
137
0.65141
4.973515
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/jsaddons/TgzPackageExtract.kt
1
17645
/**************************************************************************************** * Copyright (c) 2021 Mani <[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/>. * * * * This file incorporates work covered by the following copyright and permission * * notice: * * * * Copyright (C) 2016 The Android Open Source Project * * <p> * * 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 * * <p> * * http://www.apache.org/licenses/LICENSE-2.0 * * <p> * * 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.ichi2.anki.jsaddons import android.content.Context import android.text.format.Formatter import com.ichi2.anki.R import com.ichi2.anki.UIUtils import com.ichi2.compat.CompatHelper.Companion.compat import com.ichi2.libanki.Utils import org.apache.commons.compress.archivers.ArchiveException import org.apache.commons.compress.archivers.ArchiveStreamFactory import org.apache.commons.compress.archivers.tar.TarArchiveEntry import org.apache.commons.compress.archivers.tar.TarArchiveInputStream import timber.log.Timber import java.io.* import java.util.zip.GZIPInputStream /** * In JS Addons the addon packages are downloaded from npm registry, https://registry.npmjs.org * The file format of downloaded file is tgz, so this class used to extract tgz file to addon directory. * To extract the gzip file considering security the following checks are implemented * * 1. File size of package should be less than 100 MB * 2. During extract the space consumed should be less than half of original availableSpace * 3. The file should not write outside of specified directory * 4. Clean up of temp files * * The following TarUtil.java file used to implement this * https://android.googlesource.com/platform/tools/tradefederation/+/master/src/com/android/tradefed/util/TarUtil.java * * zip slip safety * https://snyk.io/research/zip-slip-vulnerability * * Safely extract files * https://wiki.sei.cmu.edu/confluence/display/java/IDS04-J.+Safely+extract+files+from+ZipInputStream */ /** * addons path typealias, the path is some-addon path inside addons directory * The path structure of some-addon * * AnkiDroid * - addons * - some-addon * - package * - index.js * - README.md * - some-another-addon */ typealias AddonsPackageDir = File class TgzPackageExtract(private val context: Context) { private val GZIP_SIGNATURE = byteArrayOf(0x1f, 0x8b.toByte()) private var requiredMinSpace: Long = 0 private var availableSpace: Long = 0 private val BUFFER = 512 private val TOO_BIG_SIZE: Long = 0x6400000 // max size of unzipped data, 100MB private val TOO_MANY_FILES = 1024 // max number of files private var count = 0 private var total: Long = 0 private var data = ByteArray(BUFFER) /** * Determine whether a file is a gzip. * * @param file the file to check. * @return whether the file is a gzip. * @throws IOException if the file could not be read. */ @Throws(IOException::class) fun isGzip(file: File?): Boolean { val signature = ByteArray(GZIP_SIGNATURE.size) FileInputStream(file).use { stream -> if (stream.read(signature) != signature.size) { return false } } return GZIP_SIGNATURE.contentEquals(signature) } /** * Untar and ungzip a tar.gz file to a AnkiDroid/addons directory. * * @param tarballFile the .tgz file to extract * @param addonsPackageDir the addons package directory, the path is addon path inside addons directory * e.g. AnkiDroid/addons/some-addon/ * @return the temp directory. * @throws FileNotFoundException if .tgz file or ungzipped file i.e. .tar file not found * @throws IOException */ @Throws(Exception::class) fun extractTarGzipToAddonFolder(tarballFile: File, addonsPackageDir: AddonsPackageDir) { require(isGzip(tarballFile)) { context.getString(R.string.not_valid_js_addon, tarballFile.absolutePath) } try { compat.createDirectories(addonsPackageDir) } catch (e: IOException) { UIUtils.showThemedToast(context, context.getString(R.string.could_not_create_dir, addonsPackageDir.absolutePath), false) Timber.w(e) return } // Make sure we have 2x the tar file size in free space (1x for tar file, 1x for unarchived tar file contents requiredMinSpace = tarballFile.length() * 2 availableSpace = Utils.determineBytesAvailable(addonsPackageDir.canonicalPath) InsufficientSpaceException.throwIfInsufficientSpace(context, requiredMinSpace, availableSpace) // If space available then unGZip it val tarTempFile = unGzip(tarballFile, addonsPackageDir) tarTempFile.deleteOnExit() // Make sure we have sufficient free space val unTarSize = calculateUnTarSize(tarTempFile) InsufficientSpaceException.throwIfInsufficientSpace(context, unTarSize, availableSpace) try { // If space available then unTar it unTar(tarTempFile, addonsPackageDir) } catch (e: IOException) { Timber.w("Failed to unTar file") safeDeleteAddonsPackageDir(addonsPackageDir) } finally { tarTempFile.delete() } } /** * UnGZip a file: a .tgz file will become a .tar file. * * @param inputFile The [File] to ungzip * @param outputDir The directory where to put the ungzipped file. * @return a [File] pointing to the ungzipped file. * @throws FileNotFoundException * @throws IOException */ @Throws(FileNotFoundException::class, IOException::class) fun unGzip(inputFile: File, outputDir: File): File { Timber.i("Ungzipping %s to dir %s.", inputFile.absolutePath, outputDir.absolutePath) // remove the '.tgz' extension and add .tar extension val outputFile = File(outputDir, inputFile.nameWithoutExtension + ".tar") count = 0 total = 0 data = ByteArray(BUFFER) try { GZIPInputStream(FileInputStream(inputFile)).use { inputStream -> FileOutputStream(outputFile).use { outputStream -> BufferedOutputStream(outputStream, BUFFER).use { bufferOutput -> // Gzip file size should not not be greater than TOO_BIG_SIZE while (total + BUFFER <= TOO_BIG_SIZE && inputStream.read(data, 0, BUFFER).also { count = it } != -1 ) { bufferOutput.write(data, 0, count) total += count // If space consumed is more than half of original availableSpace, delete file recursively and throw enforceSpaceUsedLessThanHalfAvailable(outputFile) } if (total + BUFFER > TOO_BIG_SIZE) { outputFile.delete() throw IllegalStateException("Gzip file is too big to unGzip") } } } } } catch (e: IOException) { outputFile.delete() throw IllegalStateException("Gzip file is too big to unGzip") } return outputFile } /** * Untar a tar file into a directory. tar.gz file needs to be [.unGzip] first. * * @param inputFile The tar file to extract * @param outputDir the directory where to put the extracted files. * @throws ArchiveException * @throws IOException */ @Throws(Exception::class) fun unTar(inputFile: File, outputDir: File) { Timber.i("Untaring %s to dir %s.", inputFile.absolutePath, outputDir.absolutePath) count = 0 total = 0 data = ByteArray(BUFFER) try { FileInputStream(inputFile).use { inputStream -> ArchiveStreamFactory().createArchiveInputStream("tar", inputStream).use { tarInputStream -> val tarInputStream1 = tarInputStream as TarArchiveInputStream var entry: TarArchiveEntry? = tarInputStream1.nextEntry as TarArchiveEntry while (entry != null) { val outputFile = File(outputDir, entry.name) // Zip Slip Vulnerability https://snyk.io/research/zip-slip-vulnerability zipPathSafety(outputFile, outputDir) if (entry.isDirectory) { unTarDir(inputFile, outputDir, outputFile) } else { unTarFile(tarInputStream, entry, outputDir, outputFile) } entry = tarInputStream.nextEntry as? TarArchiveEntry } } } } catch (e: IOException) { outputDir.deleteRecursively() throw ArchiveException(context.getString(R.string.malicious_archive_exceeds_limit, Formatter.formatFileSize(context, TOO_BIG_SIZE), TOO_MANY_FILES)) } } /** * UnTar file from archive using input stream, entry to output dir * @param tarInputStream TarArchiveInputStream * @param entry TarArchiveEntry * @param outputDir Output directory * @param outputFile Output file * @throws IOException */ @Throws(IOException::class) private fun unTarFile(tarInputStream: TarArchiveInputStream, entry: TarArchiveEntry, outputDir: File, outputFile: File) { Timber.i("Creating output file %s.", outputFile.absolutePath) val currentFile = File(outputDir, entry.name) // this line important otherwise FileNotFoundException val parent = currentFile.parentFile ?: return try { compat.createDirectories(parent) } catch (e: IOException) { // clean up Timber.w(e) throw IOException(context.getString(R.string.could_not_create_dir, parent.absolutePath)) } FileOutputStream(outputFile).use { outputFileStream -> BufferedOutputStream(outputFileStream, BUFFER).use { bufferOutput -> // Tar file should not be greater than TOO_BIG_SIZE while (total + BUFFER <= TOO_BIG_SIZE && tarInputStream.read(data, 0, BUFFER).also { count = it } != -1 ) { bufferOutput.write(data, 0, count) total += count // If space consumed is more than half of original availableSpace, delete file recursively and throw enforceSpaceUsedLessThanHalfAvailable(outputDir) } if (total + BUFFER > TOO_BIG_SIZE) { // remove unused file outputFile.delete() throw IllegalStateException("Tar file is too big to untar") } } } } /** * UnTar directory to output dir * @param inputFile archive input file * @param outputDir Output directory * @param outputFile Output file * @throws IOException */ @Throws(IOException::class) private fun unTarDir(inputFile: File, outputDir: File, outputFile: File) { Timber.i("Untaring %s to dir %s.", inputFile.absolutePath, outputDir.absolutePath) try { Timber.i("Attempting to create output directory %s.", outputFile.absolutePath) compat.createDirectories(outputFile) } catch (e: IOException) { Timber.w(e) throw IOException(context.getString(R.string.could_not_create_dir, outputFile.absolutePath)) } } /** * Ensure that the canonical path of destination directory should be equal to canonical path of output file * Zip Slip Vulnerability https://snyk.io/research/zip-slip-vulnerability * * @param outputFile output file * @param destDirectory destination directory */ @Throws(ArchiveException::class, IOException::class) private fun zipPathSafety(outputFile: File, destDirectory: File) { val destDirCanonicalPath = destDirectory.canonicalPath val outputFileCanonicalPath = outputFile.canonicalPath if (!outputFileCanonicalPath.startsWith(destDirCanonicalPath)) { throw ArchiveException(context.getString(R.string.malicious_archive_entry_outside, outputFileCanonicalPath)) } } /** * Given a tar file, iterate through the entries to determine the total untar size * TODO warning: vulnerable to resource exhaustion attack if entries contain spoofed sizes * * @param tarFile File of unknown total uncompressed size * @return total untar size of tar file */ private fun calculateUnTarSize(tarFile: File): Long { var unTarSize: Long = 0 FileInputStream(tarFile).use { inputStream -> ArchiveStreamFactory().createArchiveInputStream("tar", inputStream).use { tarInputStream -> val tarInputStream1 = tarInputStream as TarArchiveInputStream var entry: TarArchiveEntry? = tarInputStream1.nextEntry as TarArchiveEntry var numOfEntries = 0 while (entry != null) { numOfEntries++ unTarSize += entry.size entry = tarInputStream.nextEntry as? TarArchiveEntry } if (numOfEntries > TOO_MANY_FILES) { throw IllegalStateException("Too many files to untar") } } } return unTarSize } // /** * If space consumed is more than half of original availableSpace, delete file recursively and throw * * @param outputDir output directory */ private fun enforceSpaceUsedLessThanHalfAvailable(outputDir: File) { val newAvailableSpace: Long = Utils.determineBytesAvailable(outputDir.canonicalPath) if (newAvailableSpace <= availableSpace / 2) { throw ArchiveException(context.getString(R.string.file_extract_exceeds_storage_space)) } } class InsufficientSpaceException(val required: Long, val available: Long, val context: Context) : IOException() { companion object { fun throwIfInsufficientSpace(context: Context, requiredMinSpace: Long, availableSpace: Long) { if (requiredMinSpace > availableSpace) { Timber.w("Not enough space, need %d, available %d", Formatter.formatFileSize(context, requiredMinSpace), Formatter.formatFileSize(context, availableSpace)) throw InsufficientSpaceException(requiredMinSpace, availableSpace, context) } } } } private fun safeDeleteAddonsPackageDir(addonsPackageDir: AddonsPackageDir) { if (addonsPackageDir.parent != "addons") { return } addonsPackageDir.deleteRecursively() } }
gpl-3.0
70747b3a2a712d09f0f0f43a1feb3411
42.784119
175
0.582771
5.068946
false
false
false
false
tokenbrowser/token-android-client
app/src/main/java/com/toshi/view/activity/MainActivity.kt
1
6244
package com.toshi.view.activity import android.arch.lifecycle.Observer import android.arch.lifecycle.ViewModelProviders import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.app.AlertDialog import android.support.v7.app.AppCompatActivity import com.aurelhubert.ahbottomnavigation.AHBottomNavigation import com.aurelhubert.ahbottomnavigation.AHBottomNavigationAdapter import com.toshi.R import com.toshi.extensions.getColorById import com.toshi.extensions.isVisible import com.toshi.util.SoundManager import com.toshi.util.sharedPrefs.AppPrefs import com.toshi.view.adapter.NavigationAdapter import com.toshi.view.fragment.toplevel.BackableTopLevelFragment import com.toshi.view.fragment.toplevel.DappFragment import com.toshi.view.fragment.toplevel.TopLevelFragment import com.toshi.viewModel.MainViewModel import kotlinx.android.synthetic.main.activity_main.fragmentContainer import kotlinx.android.synthetic.main.activity_main.navBar import kotlinx.android.synthetic.main.activity_main.networkStatusView class MainActivity : AppCompatActivity() { companion object { const val EXTRA__ACTIVE_TAB = "active_tab" private const val CURRENT_ITEM = "current_item" const val DAPP_TAB = 0 const val CHATS_TAB = 1 const val ME_TAB = 3 } private lateinit var viewModel: MainViewModel private lateinit var navAdapter: NavigationAdapter public override fun onCreate(inState: Bundle?) { super.onCreate(inState) setContentView(R.layout.activity_main) init(inState) } private fun init(inState: Bundle?) { initViewModel() initNavAdapter() initNavBar() trySelectTabFromIntent(inState) handleHasBackedUpPhrase() showFirstRunDialog() initObservers() } private fun initViewModel() { viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java) } private fun initNavAdapter() { navAdapter = NavigationAdapter(this, R.menu.navigation) } private val tabListener = AHBottomNavigation.OnTabSelectedListener { position, wasSelected -> val existingFragment = getExistingFragment(position) if (existingFragment == null) { transitionToSelectedFragment(position) if (!wasSelected) playTabSelectedSound() } true } private fun playTabSelectedSound() = SoundManager.getInstance().playSound(SoundManager.TAB_BUTTON) private fun getExistingFragment(position: Int): Fragment? { val selectedFragment = navAdapter.getItem(position) as TopLevelFragment return supportFragmentManager.findFragmentByTag(selectedFragment.getFragmentTag()) } private fun transitionToSelectedFragment(position: Int) { val selectedFragment = navAdapter.getItem(position) as TopLevelFragment val transaction = supportFragmentManager.beginTransaction() transaction.replace( fragmentContainer.id, selectedFragment as Fragment, selectedFragment.getFragmentTag() ).commit() } private fun initNavBar() { val menuInflater = AHBottomNavigationAdapter(this, R.menu.navigation) menuInflater.setupWithBottomNavigation(navBar) navBar.apply { titleState = AHBottomNavigation.TitleState.ALWAYS_SHOW accentColor = getColorById(R.color.colorPrimary) setInactiveIconColor(getColorById(R.color.inactiveIconColor)) setInactiveTextColor(getColorById(R.color.inactiveTextColor)) setOnTabSelectedListener(tabListener) isSoundEffectsEnabled = false isBehaviorTranslationEnabled = false setTitleTextSizeInSp(13.0f, 12.0f) } } private fun trySelectTabFromIntent(inState: Bundle?) { val activeTab = intent.getIntExtra(EXTRA__ACTIVE_TAB, DAPP_TAB) val currentItem = inState?.getInt(CURRENT_ITEM, DAPP_TAB) if (activeTab == DAPP_TAB && currentItem != null && currentItem != DAPP_TAB) { navBar.currentItem = currentItem } else { navBar.currentItem = activeTab } intent.removeExtra(EXTRA__ACTIVE_TAB) } private fun initObservers() { viewModel.unreadMessages.observe(this, Observer { areUnreadMessages -> areUnreadMessages?.let { handleUnreadMessages(it) } }) } private fun handleUnreadMessages(areUnreadMessages: Boolean) { if (areUnreadMessages) { showUnreadBadge() } else { hideUnreadBadge() } } private fun showUnreadBadge() = navBar.setNotification(" ", 1) private fun hideUnreadBadge() = navBar.setNotification("", 1) private fun handleHasBackedUpPhrase() { if (AppPrefs.hasBackedUpPhrase()) { hideAlertBadge() } else { showAlertBadge() } } private fun hideAlertBadge() = navBar.setNotification("", ME_TAB) private fun showAlertBadge() = navBar.setNotification("!", ME_TAB) private fun showFirstRunDialog() { if (AppPrefs.hasLoadedApp()) return val builder = AlertDialog.Builder(this, R.style.AlertDialogCustom) builder.setTitle(R.string.beta_warning_title) .setMessage(R.string.init_warning_message) .setPositiveButton(R.string.ok) { dialog, _ -> dialog.dismiss() } builder.create().show() AppPrefs.setHasLoadedApp() } fun showNetworkStatusView() = networkStatusView.setNetworkVisibility(viewModel.getNetworks()) fun hideNetworkStatusView() = networkStatusView.isVisible(false) override fun onSaveInstanceState(outState: Bundle?) { outState?.putInt(CURRENT_ITEM, navBar.currentItem) super.onSaveInstanceState(outState) } override fun onBackPressed() { val dappFragment = supportFragmentManager.findFragmentByTag(DappFragment.TAG) if (dappFragment != null && dappFragment.isVisible && dappFragment is BackableTopLevelFragment) { val isHandled = dappFragment.onBackPressed() if (!isHandled) super.onBackPressed() } else super.onBackPressed() } }
gpl-3.0
b4de4223d2d8ed491b252a4aee456bf4
35.30814
105
0.695868
4.755522
false
false
false
false
pdvrieze/ProcessManager
PE-common/src/jvmMain/kotlin/nl/adaptivity/ws/WsMethodWrapper.kt
1
1948
/* * Copyright (c) 2018. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package nl.adaptivity.ws import nl.adaptivity.messaging.HttpResponseException import nl.adaptivity.messaging.MessagingException import nl.adaptivity.process.engine.MessagingFormatException import java.lang.reflect.InvocationTargetException import java.lang.reflect.Method import javax.servlet.http.HttpServletResponse /** * Created by pdvrieze on 28/11/15. */ abstract class WsMethodWrapper(protected val owner: Any, protected val method: Method) { protected lateinit var params: Array<Any?> protected open var result: Any? = null protected val paramsInitialised: Boolean get() = ::params.isInitialized open fun exec() { if (!::params.isInitialized) throw IllegalArgumentException("Argument unmarshalling has not taken place yet") val params = params try { result = method.invoke(owner, *params) } catch (e: InvocationTargetException) { val cause = e.cause throw MessagingException(cause ?: e) } catch (e: MessagingFormatException) { throw HttpResponseException(HttpServletResponse.SC_BAD_REQUEST, e) } catch (e: MessagingException) { throw e } catch (e: Exception) { throw MessagingException(e) } } }
lgpl-3.0
92b779eac7204a19c1937def51da3ee0
35.754717
117
0.714579
4.616114
false
false
false
false
shkschneider/android_Skeleton
demo/src/main/kotlin/me/shkschneider/skeleton/demo/main/MainActivity.kt
1
4771
package me.shkschneider.skeleton.demo.main import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentStatePagerAdapter import androidx.lifecycle.Observer import androidx.viewpager.widget.ViewPager import kotlinx.android.synthetic.main.activity_main.* import me.shkschneider.skeleton.SkeletonActivity import me.shkschneider.skeleton.SkeletonFragment import me.shkschneider.skeleton.demo.about.AboutActivity import me.shkschneider.skeleton.demo.R import me.shkschneider.skeleton.demo.data.ShkMod import me.shkschneider.skeleton.extensions.android.Intent import me.shkschneider.skeleton.getViewModel import me.shkschneider.skeleton.helperx.Logger import me.shkschneider.skeleton.uix.BottomSheet import me.shkschneider.skeleton.uix.Toaster class MainActivity : SkeletonActivity() { val secretKey by lazy { secretKey() } init { System.loadLibrary("secrets") } external fun secretKey(): String // region lifecycle // override fun attachBaseContext(newBase: Context?) { // super.attachBaseContext(LocaleHelper.Application.switch(newBase, LocaleHelper.Device.locale())) // } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // overridePendingTransitions(0, 0) setContentView(R.layout.activity_main) toolbar(home = false, title = getString(R.string.title), subtitle = getString(R.string.subtitle)) val pagerAdapter = MyPagerAdapter(supportFragmentManager) for (i in 0 until pagerAdapter.count) { tabLayout.addTab(tabLayout.newTab().setText(pagerAdapter.getPageTitle(i))) } tabLayout.setupWithViewPager(viewPager) viewPager.run { adapter = pagerAdapter offscreenPageLimit = pagerAdapter.count / 2 addOnPageChangeListener(object: ViewPager.OnPageChangeListener { override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { // Ignore } override fun onPageSelected(position: Int) { Logger.verbose("Page: $position") } override fun onPageScrollStateChanged(state: Int) { // Ignore } }) } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.main, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menu_about -> { startActivity(Intent(this, AboutActivity::class)) return true } } return super.onOptionsItemSelected(item) } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) when (intent.action) { ShkMod.BROADCAST_SECRET -> { val title = intent.getStringExtra("title") val message = intent.getStringExtra("message") bottomSheet(title, message) } } } // enregion // region viewmodel override fun onResume() { super.onResume() getViewModel<MainViewModel>().getModels().observe(this, Observer { models -> // update UI val breakpoint: Nothing? = null }) } // endregion private fun bottomSheet(title: String, content: String) { BottomSheet.Builder(this) .setTitle(title) .setContent(content) .setPositive(resources.getString(android.R.string.ok), null) .setNegative(resources.getString(android.R.string.cancel), null) .build() .show() } // region fragments private class MyPagerAdapter(fragmentManager: FragmentManager) : FragmentStatePagerAdapter(fragmentManager) { private val shkFragment by lazy { SkeletonFragment.newInstance(ShkFragment::class) } private val skFragment by lazy { SkeletonFragment.newInstance(SkFragment::class) } override fun getItem(position: Int): Fragment? { return when (position) { 0 -> shkFragment 1 -> skFragment else -> null } } override fun getPageTitle(position: Int): CharSequence? { return getItem(position)?.javaClass?.simpleName } override fun getCount(): Int { return 2 } } // endregion }
apache-2.0
1d0fb9565b4e3b836908f80b51216bd5
30.806667
113
0.635925
5.102674
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/provider/CategoriesProvider.kt
1
1139
package com.boardgamegeek.provider import android.net.Uri import com.boardgamegeek.provider.BggContract.Categories import com.boardgamegeek.provider.BggContract.Companion.PATH_CATEGORIES import com.boardgamegeek.provider.BggDatabase.Tables class CategoriesProvider : BasicProvider() { override fun getType(uri: Uri) = Categories.CONTENT_TYPE override val path = PATH_CATEGORIES override val table = Tables.CATEGORIES override val defaultSortOrder = Categories.DEFAULT_SORT override val insertedIdColumn = Categories.Columns.CATEGORY_ID override fun buildExpandedSelection(uri: Uri, projection: Array<String>?): SelectionBuilder { val builder = SelectionBuilder() .mapToTable(Categories.Columns.CATEGORY_ID, table) if (projection.orEmpty().contains(Categories.Columns.ITEM_COUNT)) { builder .table(Tables.CATEGORIES_JOIN_COLLECTION) .groupBy("$table.${Categories.Columns.CATEGORY_ID}") .mapAsCount(Categories.Columns.ITEM_COUNT) } else { builder.table(table) } return builder } }
gpl-3.0
d134a8b34da02d924a0553d5803ce008
33.515152
97
0.705882
4.745833
false
false
false
false
devulex/eventorage
frontend/src/com/devulex/eventorage/common/commonjs.kt
1
731
package runtime.wrappers external fun require(module: String): dynamic inline fun <T> jsObject(builder: T.() -> Unit): T { val obj: T = js("({})") return obj.apply { builder() } } inline fun js(builder: dynamic.() -> Unit): dynamic = jsObject(builder) fun Any.getOwnPropertyNames(): Array<String> { @Suppress("UNUSED_VARIABLE") val me = this return js("Object.getOwnPropertyNames(me)") } fun toPlainObjectStripNull(me: Any): dynamic { val obj = js("({})") for (p in me.getOwnPropertyNames().filterNot { it == "__proto__" || it == "constructor" }) { js("if (me[p] != null) { obj[p]=me[p] }") } return obj } fun jsstyle(builder: dynamic.() -> Unit): String = js(builder)
mit
e61ad15a60a47675e6ef680e29a8b655
25.107143
96
0.607387
3.448113
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/service/pagination/LanternPaginationBuilder.kt
1
3232
/* * 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.service.pagination import org.lanternpowered.api.text.Text import org.lanternpowered.api.text.textOf import org.lanternpowered.api.util.collections.toImmutableList import org.spongepowered.api.service.pagination.PaginationList class LanternPaginationBuilder internal constructor( private val service: LanternPaginationService ) : PaginationList.Builder { companion object { val DefaultSpacer = textOf("=") } private var paginationList: PaginationList? = null private var contents: Iterable<Text>? = null private var title: Text? = null private var header: Text? = null private var footer: Text? = null private var padding: Text = DefaultSpacer private var linesPerPage = 20 override fun contents(contents: Iterable<Text>): PaginationList.Builder = this.apply { this.contents = contents this.paginationList = null } override fun contents(vararg contents: Text): PaginationList.Builder = this.apply { this.contents = contents.toImmutableList() this.paginationList = null } override fun title(title: Text?): PaginationList.Builder = this.apply { this.title = title this.paginationList = null } override fun header(header: Text?): PaginationList.Builder = this.apply { this.header = header this.paginationList = null } override fun footer(footer: Text?): PaginationList.Builder = this.apply { this.footer = footer this.paginationList = null } override fun padding(padding: Text): PaginationList.Builder = this.apply { this.padding = padding this.paginationList = null } override fun linesPerPage(linesPerPage: Int): PaginationList.Builder = this.apply { this.linesPerPage = linesPerPage this.paginationList = null } override fun build(): PaginationList { val contents = checkNotNull(this.contents) { "The contents of the pagination list must be set!" } if (this.paginationList == null) { this.paginationList = LanternPaginationList(this.service, contents, this.title, this.header, this.footer, this.padding, this.linesPerPage) } return this.paginationList!! } override fun from(list: PaginationList): PaginationList.Builder = this.apply { this.reset() this.contents = list.contents this.title = list.title.orElse(null) this.header = list.header.orElse(null) this.footer = list.footer.orElse(null) this.padding = list.padding this.paginationList = null } override fun reset(): PaginationList.Builder = this.apply { this.contents = null this.title = null this.header = null this.footer = null this.padding = DefaultSpacer this.paginationList = null } }
mit
acd69c6458163b990237f3c317847dbf
32.319588
105
0.675433
4.43956
false
false
false
false
android/topeka
quiz/src/main/java/com/google/samples/apps/topeka/widget/quiz/AlphaPickerQuizView.kt
1
2675
/* * Copyright 2017 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 com.google.samples.apps.topeka.widget.quiz import android.annotation.SuppressLint import android.content.Context import android.os.Bundle import android.view.View import android.widget.ScrollView import android.widget.SeekBar import android.widget.TextView import com.google.samples.apps.topeka.quiz.R import com.google.samples.apps.topeka.model.Category import com.google.samples.apps.topeka.model.quiz.AlphaPickerQuiz import com.google.samples.apps.topeka.widget.SeekBarListener import java.util.Arrays @SuppressLint("ViewConstructor") class AlphaPickerQuizView( context: Context, category: Category, quiz: AlphaPickerQuiz ) : AbsQuizView<AlphaPickerQuiz>(context, category, quiz) { private val alphabet get() = Arrays.asList(*resources.getStringArray(R.array.alphabet)) private val KEY_SELECTION = "SELECTION" private var currentSelection: TextView? = null private var seekBar: SeekBar? = null override fun createQuizContentView(): View { val layout = inflate<ScrollView>(R.layout.quiz_layout_picker) currentSelection = (layout.findViewById<TextView>(R.id.seekbar_progress)).apply { text = alphabet[0] } seekBar = (layout.findViewById<SeekBar>(R.id.seekbar)).apply { max = alphabet.size - 1 setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener by SeekBarListener { override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { currentSelection?.text = alphabet[progress] allowAnswer() } }) } return layout } override val isAnswerCorrect get() = quiz .isAnswerCorrect(currentSelection?.text?.toString() ?: "") override var userInput: Bundle get() = Bundle().apply { putString(KEY_SELECTION, currentSelection?.text?.toString()) } set(savedInput) { seekBar?.progress = alphabet.indexOf(savedInput.getString(KEY_SELECTION, alphabet[0])) } }
apache-2.0
4f04c1347418bc236e39743d1b2a1bc2
35.643836
100
0.699065
4.526227
false
false
false
false
Geobert/radis
app/src/main/kotlin/fr/geobert/radis/db/DbHelper.kt
1
8795
package fr.geobert.radis.db import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import android.os.Environment import android.util.Log import fr.geobert.radis.service.RadisService import fr.geobert.radis.tools.DBPrefsManager import java.io.File import java.io.FileInputStream import java.io.FileOutputStream public class DbHelper private constructor(private val mCtx: Context) : SQLiteOpenHelper(mCtx, DbHelper.DATABASE_NAME, null, DbHelper.DATABASE_VERSION) { override fun onCreate(db: SQLiteDatabase) { AccountTable.onCreate(db) OperationTable.onCreate(db) InfoTables.onCreate(db) OperationTable.createMeta(db) PreferenceTable.onCreate(db) ScheduledOperationTable.onCreate(db) StatisticTable.onCreate(db) } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { Log.d("DbHelper", "onUpgrade $oldVersion -> $newVersion") if (oldVersion <= 1) upgradeFromV1(db, oldVersion, newVersion) if (oldVersion <= 2) upgradeFromV2(db, oldVersion, newVersion) if (oldVersion <= 3) upgradeFromV3(db, oldVersion, newVersion) if (oldVersion <= 4) upgradeFromV4(db) if (oldVersion <= 5) upgradeFromV5(db, oldVersion, newVersion) if (oldVersion <= 6) upgradeFromV6(db, oldVersion, newVersion) if (oldVersion <= 7) upgradeFromV7(db, oldVersion, newVersion) if (oldVersion <= 8) upgradeFromV8(db, oldVersion, newVersion) if (oldVersion <= 9) upgradeFromV9(db) if (oldVersion <= 10) upgradeFromV10(db) if (oldVersion <= 11) upgradeFromV11(db, oldVersion, newVersion) if (oldVersion <= 12) upgradeFromV12(db, oldVersion, newVersion) if (oldVersion <= 13) upgradeFromV13(db, oldVersion, newVersion) if (oldVersion <= 14) upgradeFromV14(db, oldVersion, newVersion) if (oldVersion <= 15) upgradeFromV15(db, oldVersion, newVersion) if (oldVersion <= 16) upgradeFromV16(db, oldVersion, newVersion) if (oldVersion <= 17) upgradeFromV17(db) if (oldVersion <= 18) upgradeFromV18(db) if (oldVersion <= 19) upgradeFromV19(db) if (oldVersion <= 20) upgradeFromV20(db, oldVersion) upgradeDefault(db) } private fun upgradeDefault(db: SQLiteDatabase) { AccountTable.upgradeDefault(db) } private fun upgradeFromV20(db: SQLiteDatabase, oldVersion: Int) { StatisticTable.upgradeFromV20(db, oldVersion) } private fun upgradeFromV19(db: SQLiteDatabase) { StatisticTable.upgradeFromV19(db) } private fun upgradeFromV18(db: SQLiteDatabase) { AccountTable.upgradeFromV18(db) PreferenceTable.upgradeFromV18(db) } private fun upgradeFromV17(db: SQLiteDatabase) { StatisticTable.upgradeFromV17(db) } private fun upgradeFromV16(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { InfoTables.upgradeFromV16(db, oldVersion, newVersion) OperationTable.upgradeFromV16(db, oldVersion, newVersion) AccountTable.upgradeFromV16(db) } private fun upgradeFromV15(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { InfoTables.upgradeFromV15(db, oldVersion, newVersion) } private fun upgradeFromV14(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { ScheduledOperationTable.upgradeFromV12(db, oldVersion, newVersion) } private fun upgradeFromV13(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { InfoTables.upgradeFromV13(db, oldVersion, newVersion) } private fun upgradeFromV12(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { ScheduledOperationTable.upgradeFromV12(db, oldVersion, newVersion) AccountTable.upgradeFromV12(db) } private fun upgradeFromV11(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { OperationTable.upgradeFromV11(db, oldVersion, newVersion) ScheduledOperationTable.upgradeFromV11(db, oldVersion, newVersion) } private fun upgradeFromV10(db: SQLiteDatabase) { PreferenceTable.upgradeFromV10(mCtx, db) } private fun upgradeFromV9(db: SQLiteDatabase) { AccountTable.upgradeFromV9(db) } private fun upgradeFromV8(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { InfoTables.upgradeFromV8(db, oldVersion, newVersion) } private fun upgradeFromV7(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { InfoTables.upgradeFromV7(db, oldVersion, newVersion) } private fun upgradeFromV6(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { AccountTable.upgradeFromV6(db) ScheduledOperationTable.upgradeFromV6(db, oldVersion, newVersion) OperationTable.upgradeFromV6(db, oldVersion, newVersion) } private fun upgradeFromV5(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { ScheduledOperationTable.upgradeFromV5(db, oldVersion, newVersion) OperationTable.upgradeFromV5(db, oldVersion, newVersion) } private fun upgradeFromV4(db: SQLiteDatabase) { AccountTable.upgradeFromV4(db) } private fun upgradeFromV3(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { OperationTable.upgradeFromV3(db, oldVersion, newVersion) } private fun upgradeFromV1(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { OperationTable.upgradeFromV1(db, oldVersion, newVersion) } private fun upgradeFromV2(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { OperationTable.upgradeFromV2(db, oldVersion, newVersion) } companion object { public val DATABASE_NAME: String = "radisDb" val DATABASE_VERSION: Int = 21 public var instance: DbHelper? = null public fun getInstance(ctx: Context): DbHelper { synchronized(this, { if (instance == null) { instance = DbHelper(ctx) } return instance!! }) } public fun trashDatabase(ctx: Context) { Log.d("Radis", "trashDatabase DbHelper") ctx.deleteDatabase(DATABASE_NAME) } public fun backupDatabase(): Boolean { try { val sd = Environment.getExternalStorageDirectory() val data = Environment.getDataDirectory() if (sd.canWrite()) { val currentDBPath = "data/fr.geobert.radis/databases/radisDb" val backupDBDir = "/radis/" val backupDBPath = "/radis/radisDb" val currentDB = File(data, currentDBPath) val backupDir = File(sd, backupDBDir) backupDir.mkdirs() val backupDB = File(sd, backupDBPath) if (currentDB.exists()) { val srcFIS = FileInputStream(currentDB) val dstFOS = FileOutputStream(backupDB) val src = srcFIS.channel val dst = dstFOS.channel dst.transferFrom(src, 0, src.size()) src.close() dst.close() srcFIS.close() dstFOS.close() } return true } return false } catch (e: Exception) { e.printStackTrace() } return false } public fun restoreDatabase(ctx: Context): Boolean { try { val sd = Environment.getExternalStorageDirectory() val backupDBPath = "/radis/radisDb" val currentDB = ctx.getDatabasePath(DATABASE_NAME) val backupDB = File(sd, backupDBPath) if (backupDB.exists()) { DbContentProvider.close() val srcFIS = FileInputStream(backupDB) val dstFOS = FileOutputStream(currentDB) val dst = dstFOS.channel val src = srcFIS.channel dst.transferFrom(src, 0, src.size()) src.close() dst.close() srcFIS.close() dstFOS.close() DbContentProvider.reinit(ctx) DBPrefsManager.getInstance(ctx).put(RadisService.CONSOLIDATE_DB, true) return true } } catch (e: Exception) { e.printStackTrace() } return false } public fun delete() { instance = null } } }
gpl-2.0
1454f0f07df68e748a04d60922206e1c
36.746781
117
0.621035
4.464467
false
false
false
false
android/android-studio-poet
aspoet/src/test/kotlin/com/google/androidstudiopoet/converters/ConfigPojoToBuildSystemConfigConverterTest.kt
1
1434
package com.google.androidstudiopoet.converters import com.google.androidstudiopoet.input.ConfigPOJO import com.google.androidstudiopoet.testutils.assertEquals import com.google.androidstudiopoet.testutils.assertOn import org.junit.Test private const val KOTLIN_VERSION = "kotlin version" private const val AGP_VERSION = "agp version" private const val GRADLE_VERSION = "gradle version" private val GRADLE_PROPERTIES = mapOf("property1" to "value1", "property2" to "value2") private const val GENERATE_BAZEL_FILES = true class ConfigPojoToBuildSystemConfigConverterTest { private val configPojo = ConfigPOJO().apply { kotlinVersion = KOTLIN_VERSION androidGradlePluginVersion = AGP_VERSION gradleVersion = GRADLE_VERSION gradleProperties = GRADLE_PROPERTIES generateBazelFiles = GENERATE_BAZEL_FILES } private val converter = ConfigPojoToBuildSystemConfigConverter() @Test fun `convert should pass gradle, AGP and kotlin versions to BuildSystemConfig`() { val buildSystemConfig = converter.convert(configPojo) assertOn(buildSystemConfig) { kotlinVersion!!.assertEquals(KOTLIN_VERSION) agpVersion!!.assertEquals(AGP_VERSION) buildSystemVersion!!.assertEquals(GRADLE_VERSION) properties!!.assertEquals(GRADLE_PROPERTIES) generateBazelFiles!!.assertEquals(GENERATE_BAZEL_FILES) } } }
apache-2.0
d2cf4c23c752336d0f3c6a3adbd68c60
37.783784
87
0.741283
4.910959
false
true
false
false
danrien/projectBlueWater
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/engine/GivenAHaltedPlaylistEngine/WhenChangingTracks.kt
1
4295
package com.lasthopesoftware.bluewater.client.playback.engine.GivenAHaltedPlaylistEngine import com.lasthopesoftware.EmptyUrl import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile import com.lasthopesoftware.bluewater.client.browsing.items.media.files.access.stringlist.FileStringListUtilities import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.KnownFileProperties import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.repository.FilePropertiesContainer import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.repository.IFilePropertiesContainerRepository import com.lasthopesoftware.bluewater.client.browsing.library.access.ILibraryStorage import com.lasthopesoftware.bluewater.client.browsing.library.access.ISpecificLibraryProvider import com.lasthopesoftware.bluewater.client.browsing.library.access.PassThroughLibraryStorage import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library import com.lasthopesoftware.bluewater.client.playback.engine.PlaybackEngine import com.lasthopesoftware.bluewater.client.playback.engine.bootstrap.PlaylistPlaybackBootstrapper import com.lasthopesoftware.bluewater.client.playback.engine.preparation.PreparedPlaybackQueueResourceManagement import com.lasthopesoftware.bluewater.client.playback.file.PositionedFile import com.lasthopesoftware.bluewater.client.playback.file.PositionedProgressedFile import com.lasthopesoftware.bluewater.client.playback.file.preparation.FakeDeferredPlayableFilePreparationSourceProvider import com.lasthopesoftware.bluewater.client.playback.file.preparation.queues.CompletingFileQueueProvider import com.lasthopesoftware.bluewater.client.playback.view.nowplaying.storage.NowPlayingRepository import com.lasthopesoftware.bluewater.client.playback.volume.PlaylistVolumeManager import com.lasthopesoftware.bluewater.shared.UrlKeyHolder import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture import com.namehillsoftware.handoff.promises.Promise import io.mockk.every import io.mockk.mockk import org.assertj.core.api.Assertions.assertThat import org.joda.time.Duration import org.junit.BeforeClass import org.junit.Test import java.util.concurrent.TimeUnit class WhenChangingTracks { companion object { private val library = Library() private var initialState: PositionedProgressedFile? = null private var nextSwitchedFile: PositionedFile? = null @BeforeClass @JvmStatic fun before() { val fakePlaybackPreparerProvider = FakeDeferredPlayableFilePreparationSourceProvider() library.setId(1) library.setSavedTracksString( FileStringListUtilities.promiseSerializedFileStringList( listOf( ServiceFile(1), ServiceFile(2), ServiceFile(3), ServiceFile(4), ServiceFile(5) ) ).toFuture().get() ) library.setNowPlayingId(0) val libraryProvider = mockk<ISpecificLibraryProvider>() every { libraryProvider.library } returns Promise(library) val libraryStorage: ILibraryStorage = PassThroughLibraryStorage() val filePropertiesContainerRepository = mockk<IFilePropertiesContainerRepository>() every { filePropertiesContainerRepository.getFilePropertiesContainer(UrlKeyHolder(EmptyUrl.url, ServiceFile(4))) } returns FilePropertiesContainer(1, mapOf(Pair(KnownFileProperties.DURATION, "100"))) val playbackEngine = PlaybackEngine( PreparedPlaybackQueueResourceManagement( fakePlaybackPreparerProvider ) { 1 }, listOf(CompletingFileQueueProvider()), NowPlayingRepository(libraryProvider, libraryStorage), PlaylistPlaybackBootstrapper(PlaylistVolumeManager(1.0f)) ) initialState = playbackEngine.restoreFromSavedState().toFuture().get() nextSwitchedFile = playbackEngine.changePosition(3, Duration.ZERO).toFuture()[1, TimeUnit.SECONDS] } } @Test fun `then the initial playlist position is correct`() { assertThat(initialState?.playlistPosition).isEqualTo(0) } @Test fun `then the next file change is the correct playlist position`() { assertThat(nextSwitchedFile!!.playlistPosition).isEqualTo(3) } @Test fun `then the saved library is at the correct playlist position`() { assertThat(library.nowPlayingId).isEqualTo(3) } }
lgpl-3.0
3c9713e28e4e42154c83fe46a86dd487
45.684783
128
0.830966
4.588675
false
false
false
false
neyb/swak
core/src/main/kotlin/swak/matcher/AndMatcher.kt
1
482
package swak.matcher import swak.http.request.UpdatableRequest class AndMatcher<B>(private val matchers: MutableList<RequestMatcher<B>>) : RequestMatcher<B> { override fun accept(request: UpdatableRequest<B>) = matchers.all { it.accept(request) } override fun and(matcher: RequestMatcher<B>): RequestMatcher<B> { matchers += matcher return this } override fun toString() = matchers.joinToString(prefix = "(", separator = " and ", postfix = ")") }
apache-2.0
d420de6f548346c60dd0a8c9b880dbe9
33.5
101
0.69917
4.22807
false
false
false
false
GeoffreyMetais/vlc-android
application/television/src/main/java/org/videolan/television/ui/MediaBrowserAnimatorDelegate.kt
1
17701
/* * ************************************************************************ * MediaBrowserTvFragment.kt * ************************************************************************* * Copyright © 2019 VLC authors and VideoLAN * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. * * ************************************************************************* */ package org.videolan.television.ui import android.util.Log import android.view.View import android.view.animation.AccelerateDecelerateInterpolator import android.widget.ProgressBar import androidx.constraintlayout.widget.ConstraintLayout import androidx.constraintlayout.widget.ConstraintSet import androidx.recyclerview.widget.RecyclerView import androidx.transition.ChangeBounds import androidx.transition.Transition import androidx.transition.TransitionManager import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ObsoleteCoroutinesApi import org.videolan.television.R import org.videolan.television.databinding.SongBrowserBinding import org.videolan.television.ui.browser.BaseBrowserTvFragment import org.videolan.vlc.BuildConfig @ObsoleteCoroutinesApi @ExperimentalCoroutinesApi internal class MediaBrowserAnimatorDelegate(val binding: SongBrowserBinding, private val cl: ConstraintLayout) : RecyclerView.OnScrollListener(), View.OnFocusChangeListener { private val scrolledUpConstraintSet = ConstraintSet() private val scrolledDownFABCollapsedConstraintSet = ConstraintSet() private val scrolledDownFABExpandedConstraintSet = ConstraintSet() private val headerVisibleConstraintSet = ConstraintSet() private val constraintSets = arrayOf(scrolledUpConstraintSet, scrolledDownFABCollapsedConstraintSet, scrolledDownFABExpandedConstraintSet, headerVisibleConstraintSet) private val transition = ChangeBounds().apply { interpolator = AccelerateDecelerateInterpolator() duration = 300 } private val fakeToolbar = binding.toolbar private val fabSettings = binding.imageButtonSettings private val fabHeader = binding.imageButtonHeader private val fabFavorite = binding.imageButtonFavorite private val fabSort = binding.imageButtonSort private val fabDisplay = binding.imageButtonDisplay private var currenstate = MediaBrowserState.SCROLLED_UP set(value) { //avoid playing the transition again if (value == field) { return } TransitionManager.beginDelayedTransition(cl, transition) when (value) { MediaBrowserState.SCROLLED_UP -> scrolledUpConstraintSet MediaBrowserState.SCROLLED_DOWN_FAB_COLLAPSED -> scrolledDownFABCollapsedConstraintSet MediaBrowserState.SCROLLED_DOWN_FAB_EXPANDED -> scrolledDownFABExpandedConstraintSet MediaBrowserState.HEADER_VISIBLE -> headerVisibleConstraintSet }.applyTo(cl) field = value } enum class MediaBrowserState { /** * Initial state : Visible fake toolbar + no fab */ SCROLLED_UP, /** * Scrolled state with collapsed FAB */ SCROLLED_DOWN_FAB_COLLAPSED, /** * Scrolled state with expanded FAB */ SCROLLED_DOWN_FAB_EXPANDED, /** * Header visible : no toolbar no FAB */ HEADER_VISIBLE } override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) currenstate = if (recyclerView.computeVerticalScrollOffset() > 0) { MediaBrowserState.SCROLLED_DOWN_FAB_COLLAPSED } else { MediaBrowserState.SCROLLED_UP } } override fun onFocusChange(v: View, hasFocus: Boolean) { //Show action labels when needed val view = when (v) { binding.displayButton -> binding.displayDescription binding.headerButton -> binding.headerDescription binding.sortButton -> binding.sortDescription binding.favoriteButton -> binding.favoriteDescription else -> null } if (BuildConfig.DEBUG) Log.d(this::class.java.simpleName, "Focusing: $hasFocus $view") view?.animate()?.cancel() view?.animate()?.alpha(if (hasFocus) 1f else 0f) // FAB has to be expanded / collapsed when its focus changes if (currenstate != MediaBrowserState.SCROLLED_UP) { if (!fabSettings.hasFocus() && !fabSort.hasFocus() && !fabDisplay.hasFocus() && !fabDisplay.hasFocus() && !fabHeader.hasFocus() && !fabFavorite.hasFocus() && currenstate != MediaBrowserState.HEADER_VISIBLE) { collapseExtendedFAB() } if (v == fabSettings && hasFocus) { expandExtendedFAB() } } } internal fun expandExtendedFAB() { currenstate = MediaBrowserState.SCROLLED_DOWN_FAB_EXPANDED } internal fun collapseExtendedFAB() { currenstate = MediaBrowserState.SCROLLED_DOWN_FAB_COLLAPSED } internal fun hideFAB() { currenstate = MediaBrowserState.HEADER_VISIBLE } internal fun showFAB() { currenstate = MediaBrowserState.SCROLLED_DOWN_FAB_COLLAPSED } //FIXME it doesn't work. WHY??? fun setVisibility(view: View, visibility: Int) { constraintSets.forEach { it.setVisibility(view.id, visibility) } view.visibility = visibility } fun isScrolled() = currenstate == MediaBrowserState.SCROLLED_DOWN_FAB_COLLAPSED init { // Scrolled up is the state already described in the XML. We clone it to be able to reuse it. scrolledUpConstraintSet.clone(cl) /* See MediaBrowserState.SCROLLED_DOWN_FAB_COLLAPSED */ scrolledDownFABCollapsedConstraintSet.clone(cl) //Reset margins scrolledDownFABCollapsedConstraintSet.setMargin(R.id.sortButton, ConstraintSet.START, 0) scrolledDownFABCollapsedConstraintSet.setMargin(R.id.sortButton, ConstraintSet.END, 0) scrolledDownFABCollapsedConstraintSet.setMargin(R.id.sortButton, ConstraintSet.TOP, 0) scrolledDownFABCollapsedConstraintSet.setMargin(R.id.sortButton, ConstraintSet.BOTTOM, 0) scrolledDownFABCollapsedConstraintSet.setMargin(R.id.displayButton, ConstraintSet.START, 0) scrolledDownFABCollapsedConstraintSet.setMargin(R.id.displayButton, ConstraintSet.END, 0) scrolledDownFABCollapsedConstraintSet.setMargin(R.id.displayButton, ConstraintSet.TOP, 0) scrolledDownFABCollapsedConstraintSet.setMargin(R.id.displayButton, ConstraintSet.BOTTOM, 0) scrolledDownFABCollapsedConstraintSet.setMargin(R.id.headerButton, ConstraintSet.START, 0) scrolledDownFABCollapsedConstraintSet.setMargin(R.id.headerButton, ConstraintSet.END, 0) scrolledDownFABCollapsedConstraintSet.setMargin(R.id.headerButton, ConstraintSet.TOP, 0) scrolledDownFABCollapsedConstraintSet.setMargin(R.id.headerButton, ConstraintSet.BOTTOM, 0) scrolledDownFABCollapsedConstraintSet.setMargin(R.id.favoriteButton, ConstraintSet.START, 0) scrolledDownFABCollapsedConstraintSet.setMargin(R.id.favoriteButton, ConstraintSet.END, 0) scrolledDownFABCollapsedConstraintSet.setMargin(R.id.favoriteButton, ConstraintSet.TOP, 0) scrolledDownFABCollapsedConstraintSet.setMargin(R.id.favoriteButton, ConstraintSet.BOTTOM, 0) //New constraints for toolbar buttons to make them move to the FAB scrolledDownFABCollapsedConstraintSet.connect(R.id.sortButton, ConstraintSet.START, R.id.imageButtonSettings, ConstraintSet.START) scrolledDownFABCollapsedConstraintSet.connect(R.id.sortButton, ConstraintSet.END, R.id.imageButtonSettings, ConstraintSet.END) scrolledDownFABCollapsedConstraintSet.connect(R.id.sortButton, ConstraintSet.TOP, R.id.imageButtonSettings, ConstraintSet.TOP) scrolledDownFABCollapsedConstraintSet.connect(R.id.sortButton, ConstraintSet.BOTTOM, R.id.imageButtonSettings, ConstraintSet.BOTTOM) scrolledDownFABCollapsedConstraintSet.connect(R.id.displayButton, ConstraintSet.START, R.id.imageButtonSettings, ConstraintSet.START) scrolledDownFABCollapsedConstraintSet.connect(R.id.displayButton, ConstraintSet.END, R.id.imageButtonSettings, ConstraintSet.END) scrolledDownFABCollapsedConstraintSet.connect(R.id.displayButton, ConstraintSet.TOP, R.id.imageButtonSettings, ConstraintSet.TOP) scrolledDownFABCollapsedConstraintSet.connect(R.id.displayButton, ConstraintSet.BOTTOM, R.id.imageButtonSettings, ConstraintSet.BOTTOM) scrolledDownFABCollapsedConstraintSet.connect(R.id.headerButton, ConstraintSet.START, R.id.imageButtonSettings, ConstraintSet.START) scrolledDownFABCollapsedConstraintSet.connect(R.id.headerButton, ConstraintSet.END, R.id.imageButtonSettings, ConstraintSet.END) scrolledDownFABCollapsedConstraintSet.connect(R.id.headerButton, ConstraintSet.TOP, R.id.imageButtonSettings, ConstraintSet.TOP) scrolledDownFABCollapsedConstraintSet.connect(R.id.headerButton, ConstraintSet.BOTTOM, R.id.imageButtonSettings, ConstraintSet.BOTTOM) scrolledDownFABCollapsedConstraintSet.connect(R.id.favoriteButton, ConstraintSet.START, R.id.imageButtonSettings, ConstraintSet.START) scrolledDownFABCollapsedConstraintSet.connect(R.id.favoriteButton, ConstraintSet.END, R.id.imageButtonSettings, ConstraintSet.END) scrolledDownFABCollapsedConstraintSet.connect(R.id.favoriteButton, ConstraintSet.TOP, R.id.imageButtonSettings, ConstraintSet.TOP) scrolledDownFABCollapsedConstraintSet.connect(R.id.favoriteButton, ConstraintSet.BOTTOM, R.id.imageButtonSettings, ConstraintSet.BOTTOM) //New constraints for the action description labels (they will be reused when expanding the FAB) scrolledDownFABCollapsedConstraintSet.clear(R.id.sortDescription, ConstraintSet.START) scrolledDownFABCollapsedConstraintSet.connect(R.id.sortDescription, ConstraintSet.END, R.id.imageButtonSort, ConstraintSet.START) scrolledDownFABCollapsedConstraintSet.connect(R.id.sortDescription, ConstraintSet.TOP, R.id.imageButtonSort, ConstraintSet.TOP) scrolledDownFABCollapsedConstraintSet.connect(R.id.sortDescription, ConstraintSet.BOTTOM, R.id.imageButtonSort, ConstraintSet.BOTTOM) scrolledDownFABCollapsedConstraintSet.clear(R.id.displayDescription, ConstraintSet.START) scrolledDownFABCollapsedConstraintSet.connect(R.id.displayDescription, ConstraintSet.END, R.id.imageButtonDisplay, ConstraintSet.START) scrolledDownFABCollapsedConstraintSet.connect(R.id.displayDescription, ConstraintSet.TOP, R.id.imageButtonDisplay, ConstraintSet.TOP) scrolledDownFABCollapsedConstraintSet.connect(R.id.displayDescription, ConstraintSet.BOTTOM, R.id.imageButtonDisplay, ConstraintSet.BOTTOM) scrolledDownFABCollapsedConstraintSet.clear(R.id.headerDescription, ConstraintSet.START) scrolledDownFABCollapsedConstraintSet.connect(R.id.headerDescription, ConstraintSet.END, R.id.imageButtonHeader, ConstraintSet.START) scrolledDownFABCollapsedConstraintSet.connect(R.id.headerDescription, ConstraintSet.TOP, R.id.imageButtonHeader, ConstraintSet.TOP) scrolledDownFABCollapsedConstraintSet.connect(R.id.headerDescription, ConstraintSet.BOTTOM, R.id.imageButtonHeader, ConstraintSet.BOTTOM) scrolledDownFABCollapsedConstraintSet.clear(R.id.favoriteDescription, ConstraintSet.START) scrolledDownFABCollapsedConstraintSet.connect(R.id.favoriteDescription, ConstraintSet.END, R.id.imageButtonFavorite, ConstraintSet.START) scrolledDownFABCollapsedConstraintSet.connect(R.id.favoriteDescription, ConstraintSet.TOP, R.id.imageButtonFavorite, ConstraintSet.TOP) scrolledDownFABCollapsedConstraintSet.connect(R.id.favoriteDescription, ConstraintSet.BOTTOM, R.id.imageButtonFavorite, ConstraintSet.BOTTOM) // Title escapes by the top of the screen scrolledDownFABCollapsedConstraintSet.constrainMaxHeight(R.id.title, ConstraintSet.TOP) scrolledDownFABCollapsedConstraintSet.constrainMaxHeight(R.id.ariane, ConstraintSet.TOP) scrolledDownFABCollapsedConstraintSet.connect(R.id.title, ConstraintSet.BOTTOM, 0, ConstraintSet.TOP) scrolledDownFABCollapsedConstraintSet.connect(R.id.ariane, ConstraintSet.BOTTOM, 0, ConstraintSet.TOP) scrolledDownFABCollapsedConstraintSet.clear(R.id.ariane, ConstraintSet.TOP) //FAB showing scrolledDownFABCollapsedConstraintSet.connect(R.id.imageButtonSettings, ConstraintSet.BOTTOM, 0, ConstraintSet.BOTTOM) scrolledDownFABCollapsedConstraintSet.clear(R.id.imageButtonSettings, ConstraintSet.TOP) /* See MediaBrowserState.SCROLLED_DOWN_FAB_EXPANDED */ //We clone the scrolledDownFABCollapsedConstraintSet as it's really close to this state scrolledDownFABExpandedConstraintSet.clone(scrolledDownFABCollapsedConstraintSet) // show the FAB children scrolledDownFABExpandedConstraintSet.clear(R.id.imageButtonHeader, ConstraintSet.TOP) scrolledDownFABExpandedConstraintSet.clear(R.id.imageButtonSort, ConstraintSet.TOP) scrolledDownFABExpandedConstraintSet.clear(R.id.imageButtonDisplay, ConstraintSet.TOP) scrolledDownFABExpandedConstraintSet.clear(R.id.imageButtonFavorite, ConstraintSet.TOP) scrolledDownFABExpandedConstraintSet.connect(R.id.imageButtonHeader, ConstraintSet.BOTTOM, R.id.imageButtonSettings, ConstraintSet.TOP) scrolledDownFABExpandedConstraintSet.connect(R.id.imageButtonSort, ConstraintSet.BOTTOM, R.id.imageButtonHeader, ConstraintSet.TOP) scrolledDownFABExpandedConstraintSet.connect(R.id.imageButtonFavorite, ConstraintSet.BOTTOM, R.id.imageButtonSort, ConstraintSet.TOP) scrolledDownFABExpandedConstraintSet.connect(R.id.imageButtonDisplay, ConstraintSet.BOTTOM, R.id.imageButtonFavorite, ConstraintSet.TOP) scrolledDownFABExpandedConstraintSet.setAlpha(R.id.displayDescription, 1f) scrolledDownFABExpandedConstraintSet.setAlpha(R.id.sortDescription, 1f) scrolledDownFABExpandedConstraintSet.setAlpha(R.id.headerDescription, 1f) scrolledDownFABExpandedConstraintSet.setAlpha(R.id.favoriteDescription, 1f) /* See MediaBrowserState.HEADER_VISIBLE */ //We clone the scrolledDownFABCollapsedConstraintSet state headerVisibleConstraintSet.clone(scrolledDownFABCollapsedConstraintSet) //Hide the list and show the header list as their visibility is embbeded in the ConstraintSets headerVisibleConstraintSet.setVisibility(R.id.headerListContainer, View.VISIBLE) headerVisibleConstraintSet.setVisibility(R.id.list, View.GONE) // Hide the FAB headerVisibleConstraintSet.clear(R.id.imageButtonSettings, ConstraintSet.BOTTOM) headerVisibleConstraintSet.connect(R.id.imageButtonSettings, ConstraintSet.TOP, R.id.headerListContainer, ConstraintSet.BOTTOM) transition.excludeTarget(ProgressBar::class.java, true) // The fake toolbar has to be View.GONE to avoid focus on its elements when it's not shown // We also want to give the focus to the header list when it's shown transition.addListener(object : Transition.TransitionListener { override fun onTransitionEnd(transition: Transition) { if (currenstate == MediaBrowserState.SCROLLED_UP) { fakeToolbar.visibility = View.VISIBLE } else { fakeToolbar.visibility = View.GONE } if (currenstate == MediaBrowserState.HEADER_VISIBLE) { binding.headerList.requestFocus() } } override fun onTransitionResume(transition: Transition) {} override fun onTransitionPause(transition: Transition) {} override fun onTransitionCancel(transition: Transition) {} override fun onTransitionStart(transition: Transition) {} }) fabSettings.setOnClickListener { expandExtendedFAB() } } } @ObsoleteCoroutinesApi @ExperimentalCoroutinesApi fun BaseBrowserTvFragment<*>.setAnimator(cl: ConstraintLayout) { animationDelegate = MediaBrowserAnimatorDelegate(binding, cl) binding.headerButton.onFocusChangeListener = animationDelegate binding.displayButton.onFocusChangeListener = animationDelegate binding.sortButton.onFocusChangeListener = animationDelegate binding.favoriteButton.onFocusChangeListener = animationDelegate binding.imageButtonSort.onFocusChangeListener = animationDelegate binding.imageButtonDisplay.onFocusChangeListener = animationDelegate binding.imageButtonHeader.onFocusChangeListener = animationDelegate binding.imageButtonSettings.onFocusChangeListener = animationDelegate binding.list.addOnScrollListener(animationDelegate) }
gpl-2.0
c4058eb5f717ee878613ed114211c8ec
54.835962
220
0.74774
4.866648
false
false
false
false
songzhw/AndroidArchitecture
deprecated/CoroutineFlowLiveData/app/src/main/java/ca/six/archi/cfl/biz/DetailActivity.kt
1
1497
package ca.six.archi.cfl.biz import android.content.Intent import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModelProvider import ca.six.archi.cfl.R import ca.six.archi.cfl.core.App import ca.six.archi.cfl.data.Plant import com.bumptech.glide.Glide import kotlinx.android.synthetic.main.activity_detail.* class DetailActivity : AppCompatActivity(R.layout.activity_detail) { lateinit var vm: DetailViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val plant = intent.getParcelableExtra<Plant>("plant") Glide.with(this).load(plant?.imageUrl).into(ivDetail) tvDetailTitle.text = plant?.name tvDetailDesp.text = plant?.description tvDetailId.text = plant?.plantId vm = ViewModelProvider(this).get(DetailViewModel::class.java) vm.injector = App.injector vm.previousPlantLiveData.observe(this) { prevPlant -> println("szw prevPlant = ${prevPlant.plant}") ivPrevPlant.visibility = if (prevPlant == null) View.GONE else View.VISIBLE ivPrevPlant.setOnClickListener { val intent = Intent(this, DetailActivity::class.java) .putExtra("plant", prevPlant.plant) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) startActivity(intent) } } vm.getPrevPlant(plant) } }
apache-2.0
8ae44a36bc83e7d9045e95448b890cec
33.813953
87
0.684703
4.277143
false
false
false
false
cout970/ComputerMod
src/main/kotlin/com/cout970/computer/item/ItemROM.kt
1
1021
package com.cout970.computer.item import com.cout970.computer.api.IComponentROM import com.cout970.computer.api.IComputer import com.cout970.computer.api.IModuleROM import com.cout970.computer.emulator.ModuleROM import net.minecraft.item.ItemStack import net.minecraft.nbt.NBTTagCompound import net.minecraft.util.EnumFacing import net.minecraftforge.common.capabilities.Capability import net.minecraftforge.common.capabilities.ICapabilityProvider /** * Created by cout970 on 01/06/2016. */ object ItemROM : ItemBase("rom"), IComponentROM, ICapabilityProvider { override fun createModule(item: ItemStack?, computer: IComputer?): IModuleROM? = ModuleROM() override fun loadModule(item: ItemStack?, computer: IComputer?, nbt: NBTTagCompound?): IModuleROM? = ModuleROM() override fun <T : Any?> getCapability(capability: Capability<T>?, facing: EnumFacing?): T = this as T override fun hasCapability(capability: Capability<*>?, facing: EnumFacing?): Boolean = capability == IComponentROM.CAPABILITY }
gpl-3.0
2154ac901d8f13b3e066e6b1e548cab7
39.88
129
0.789422
4.219008
false
false
false
false
MarKco/Catchit
catchit/src/main/java/com/ilsecondodasinistra/catchit/NavigationAdapter.kt
1
6310
package com.ilsecondodasinistra.catchit /** * Created by marco on 29/01/17. */ import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import android.widget.Toast /** * Created by hp1 on 28-12-2014. */ class NavigationAdapter internal constructor(private val mNavTitles: Array<String> // String Array to store the passed titles Value from MainActivity.java , private val mIcons: IntArray // Int Array to store the passed icons resource value from MainActivity.java , private val name: String //String Resource for header View Name , private val email: String //String Resource for header view email , private val profile: Int //int Resource for header view profile picture )// NavigationAdapter Constructor with titles and icons parameter // titles, icons, name, email, profile pic are passed from the main activity as we //have seen earlier //here we assign those passed values to the values we declared here //in adapter : RecyclerView.Adapter<NavigationAdapter.ViewHolder>() { // Creating a ViewHolder which extends the RecyclerView View Holder // ViewHolder are used to to store the inflated views in order to recycle them class ViewHolder(itemView: View, ViewType: Int) : RecyclerView.ViewHolder(itemView) { internal var Holderid: Int = 0 internal lateinit var textView: TextView internal lateinit var imageView: ImageView internal lateinit var profile: ImageView internal lateinit var Name: TextView internal lateinit var email: TextView init { // Creating ViewHolder Constructor with View and viewType As a parameter // Here we set the appropriate view in accordance with the the view type as passed when the holder object is created if (ViewType == TYPE_ITEM) { textView = itemView.findViewById<View>(R.id.rowText) as TextView // Creating TextView object with the id of textView from item_row.xml imageView = itemView.findViewById<View>(R.id.rowIcon) as ImageView// Creating ImageView object with the id of ImageView from item_row.xml Holderid = 1 // setting holder id as 1 as the object being populated are of type item row } else { Name = itemView.findViewById<View>(R.id.name) as TextView // Creating Text View object from header.xml for name email = itemView.findViewById<View>(R.id.email) as TextView // Creating Text View object from header.xml for email profile = itemView.findViewById<View>(R.id.circleView) as ImageView// Creating Image view object from header.xml for profile pic Holderid = 0 // Setting holder id = 0 as the object being populated are of type header view } } } //Below first we ovverride the method onCreateViewHolder which is called when the ViewHolder is //Created, In this method we inflate the item_row.xml layout if the viewType is Type_ITEM or else we inflate header.xml // if the viewType is TYPE_HEADER // and pass it to the view holder override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NavigationAdapter.ViewHolder? { if (viewType == TYPE_ITEM) { val v = LayoutInflater.from(parent.context).inflate(R.layout.navigation_drawer_item_row, parent, false) //Inflating the layout val vhItem = ViewHolder(v, viewType) //Creating ViewHolder and passing the object of type view return vhItem // Returning the created object //inflate your layout and pass it to view holder } else if (viewType == TYPE_HEADER) { val v = LayoutInflater.from(parent.context).inflate(R.layout.navigation_drawer_header, parent, false) //Inflating the layout val vhHeader = ViewHolder(v, viewType) //Creating ViewHolder and passing the object of type view return vhHeader //returning the object created } return null } //Next we override a method which is called when the item in a row is needed to be displayed, here the int position // Tells us item at which position is being constructed to be displayed and the holder id of the holder object tell us // which view type is being created 1 for item row override fun onBindViewHolder(holder: NavigationAdapter.ViewHolder, position: Int) { if (holder.Holderid == 1) { // as the list view is going to be called after the header view so we decrement the // position by 1 and pass it to the holder while setting the text and image holder.textView.text = mNavTitles[position - 1] // Setting the Text with the array of our Titles holder.imageView.setImageResource(mIcons[position - 1])// Settimg the image with array of our icons } else { holder.profile.setImageResource(profile) // Similarly we set the resources for header view holder.Name.text = name holder.email.text = email } } // This method returns the number of items present in the list override fun getItemCount(): Int { return mNavTitles.size + 1 // the number of items in the list will be +1 the titles including the header view. } // Witht the following method we check what type of view is being passed override fun getItemViewType(position: Int): Int { if (isPositionHeader(position)) return TYPE_HEADER return TYPE_ITEM } private fun isPositionHeader(position: Int): Boolean { return position == 0 } companion object { private val TYPE_HEADER = 0 // Declaring Variable to Understand which View is being worked on // IF the view under inflation and population is header or Item private val TYPE_ITEM = 1 } }
gpl-3.0
ca016336d006d26ebe2005f7bb2e618d
45.065693
158
0.657052
5.015898
false
false
false
false
nemerosa/ontrack
ontrack-extension-github/src/test/java/net/nemerosa/ontrack/extension/github/ingestion/processing/config/DefaultConfigLoaderServiceTest.kt
1
2829
package net.nemerosa.ontrack.extension.github.ingestion.processing.config import io.mockk.every import io.mockk.mockk import net.nemerosa.ontrack.extension.github.ingestion.FileLoaderService import net.nemerosa.ontrack.extension.github.ingestion.config.parser.ConfigParsingException import net.nemerosa.ontrack.model.structure.Branch import net.nemerosa.ontrack.model.structure.NameDescription import net.nemerosa.ontrack.model.structure.Project import net.nemerosa.ontrack.test.TestUtils import org.junit.Test import kotlin.test.assertFailsWith import kotlin.test.assertNotNull import kotlin.test.assertNull class DefaultConfigLoaderServiceTest { @Test fun `Project not configured returns null`() { test( projectConfigured = false, expectedConfig = false, ) } @Test fun `Branch not configured returns null`() { test( branchConfigured = false, expectedConfig = false, ) } @Test fun `Path not found returns null`() { test( pathFound = false, expectedConfig = false, ) } @Test fun `Loading the configuration`() { test() } @Test fun `Configuration parsing error returns an error`() { assertFailsWith<ConfigParsingException> { test( incorrectConfig = true, expectedConfig = false, ) } } private fun test( projectConfigured: Boolean = true, branchConfigured: Boolean = true, pathFound: Boolean = true, incorrectConfig: Boolean = false, expectedConfig: Boolean = true, ) { val project = Project.of(NameDescription.nd("test", "")) val branch = Branch.of(project, NameDescription.nd("main", "")) val fileLoaderService = mockk<FileLoaderService>() if (pathFound && branchConfigured && projectConfigured) { val path = if (incorrectConfig) { "/ingestion/config-incorrect.yml" } else { "/ingestion/config.yml" } every { fileLoaderService.loadFile(branch, INGESTION_CONFIG_FILE_PATH) } returns TestUtils.resourceString(path) } else { every { fileLoaderService.loadFile(branch, INGESTION_CONFIG_FILE_PATH) } returns null } val configLoaderService = DefaultConfigLoaderService( fileLoaderService = fileLoaderService, ) val config = configLoaderService.loadConfig(branch, INGESTION_CONFIG_FILE_PATH) if (expectedConfig) { assertNotNull(config, "Configuration was loaded") } else { assertNull(config, "Configuration could not be found") } } }
mit
66b0812aa56de6dfb3eba3b0e0c38076
28.789474
91
0.622835
4.860825
false
true
false
false
openHPI/android-app
app/src/main/java/de/xikolo/controllers/base/BaseActivity.kt
1
9196
package de.xikolo.controllers.base import android.content.Intent import android.content.pm.PackageManager import android.os.Bundle import android.os.Handler import android.view.KeyEvent import android.view.Menu import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.annotation.LayoutRes import androidx.appcompat.app.ActionBar import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.content.ContextCompat import androidx.drawerlayout.widget.DrawerLayout import butterknife.ButterKnife import com.google.android.gms.cast.framework.CastButtonFactory import com.google.android.gms.cast.framework.CastContext import com.google.android.gms.cast.framework.CastState import com.google.android.gms.cast.framework.CastStateListener import com.google.android.gms.cast.framework.IntroductoryOverlay import com.google.android.material.appbar.AppBarLayout import com.google.android.material.appbar.AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS import com.google.android.material.appbar.AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL import com.google.android.material.appbar.AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP import com.google.firebase.crashlytics.FirebaseCrashlytics import com.yatatsu.autobundle.AutoBundle import de.xikolo.App import de.xikolo.R import de.xikolo.extensions.observe import de.xikolo.utils.NotificationUtil import de.xikolo.utils.extensions.hasPlayServices abstract class BaseActivity : AppCompatActivity(), CastStateListener { protected var actionBar: ActionBar? = null protected var toolbar: Toolbar? = null protected var appBar: AppBarLayout? = null private var castContext: CastContext? = null private var drawerLayout: DrawerLayout? = null private var contentLayout: CoordinatorLayout? = null private var mediaRouteMenuItem: MenuItem? = null private var offlineModeToolbar: Boolean = false private var overlay: IntroductoryOverlay? = null private var translucentActionbar = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState != null) { // restore AutoBundle.bind(this, savedInstanceState) } else { AutoBundle.bind(this) } offlineModeToolbar = true try { if (this.hasPlayServices) { castContext = CastContext.getSharedInstance(this) } } catch (e: Exception) { FirebaseCrashlytics.getInstance().recordException(e) } if (overlay == null) { showOverlay() } handleIntent(intent) App.instance.state.connectivity.observe(this) { this.onConnectivityChange(it) } } override fun setContentView(@LayoutRes layoutResID: Int) { super.setContentView(layoutResID) ButterKnife.bind(this, findViewById<View>(android.R.id.content)) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { super.onCreateOptionsMenu(menu) try { if (this.hasPlayServices) { castContext = CastContext.getSharedInstance(this) menuInflater.inflate(R.menu.cast, menu) mediaRouteMenuItem = CastButtonFactory.setUpMediaRouteButton( applicationContext, menu, R.id.media_route_menu_item) } } catch (e: Exception) { FirebaseCrashlytics.getInstance().recordException(e) } return true } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) setIntent(intent) AutoBundle.bind(this) handleIntent(intent) } override fun onStart() { super.onStart() if (castContext != null) { castContext?.addCastStateListener(this) setupCastMiniController() } } override fun onPause() { super.onPause() App.instance.syncCookieSyncManager() } override fun onStop() { super.onStop() castContext?.removeCastStateListener(this) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) AutoBundle.pack(this, outState) } private fun showOverlay() { overlay?.remove() if (mediaRouteMenuItem?.isVisible == true) { Handler().postDelayed({ if (mediaRouteMenuItem != null && mediaRouteMenuItem?.isVisible == true) { overlay = IntroductoryOverlay.Builder(this@BaseActivity, mediaRouteMenuItem) .setTitleText(R.string.intro_overlay_text) .setSingleTime() .setOnOverlayDismissedListener { overlay = null } .build() overlay?.show() } }, 1000) } } override fun onCastStateChanged(newState: Int) { if (newState != CastState.NO_DEVICES_AVAILABLE) { showOverlay() } } @JvmOverloads protected fun setupActionBar(translucentActionbar: Boolean = false) { this.translucentActionbar = translucentActionbar val tb = findViewById<Toolbar>(R.id.toolbar) if (tb != null) { setSupportActionBar(tb) } toolbar = tb actionBar = supportActionBar actionBar?.setDisplayHomeAsUpEnabled(true) actionBar?.setHomeButtonEnabled(true) drawerLayout = findViewById(R.id.drawer_layout) contentLayout = findViewById(R.id.contentLayout) appBar = findViewById(R.id.appbar) setColorScheme(R.color.toolbar, R.color.statusbar) } private fun setupCastMiniController(): Boolean { return if (this.hasPlayServices && findViewById<View>(R.id.miniControllerContainer) != null) { var container = findViewById<View>(R.id.miniControllerContainer) val parent = container.parent as ViewGroup val index = parent.indexOfChild(container) parent.removeView(container) container = layoutInflater.inflate(R.layout.container_mini_controller, parent, false) parent.addView(container, index) true } else { false } } protected fun setActionBarElevation(elevation: Float) { actionBar?.elevation = elevation } protected fun setAppBarExpanded(expanded: Boolean) { appBar?.setExpanded(expanded, false) } fun setScrollingBehavior(hide: Boolean) { toolbar?.layoutParams = (toolbar?.layoutParams as? AppBarLayout.LayoutParams)?.apply { scrollFlags = SCROLL_FLAG_ENTER_ALWAYS or SCROLL_FLAG_SNAP or if (hide) SCROLL_FLAG_SCROLL else 0 } } protected fun enableOfflineModeToolbar(enable: Boolean) { this.offlineModeToolbar = enable } protected fun setColorScheme(toolbarColor: Int, statusbarColor: Int) { if (!translucentActionbar) { toolbar?.let { toolbar -> toolbar.setBackgroundColor(ContextCompat.getColor(this, toolbarColor)) drawerLayout?.setStatusBarBackgroundColor(ContextCompat.getColor(this, toolbarColor)) if (drawerLayout == null) { window.statusBarColor = ContextCompat.getColor(this, statusbarColor) } contentLayout?.setBackgroundColor(ContextCompat.getColor(this, toolbarColor)) } } } open fun onConnectivityChange(isOnline: Boolean) { if (offlineModeToolbar) { toolbar?.let { if (isOnline) { it.subtitle = "" setColorScheme(R.color.toolbar, R.color.statusbar) } else { it.subtitle = getString(R.string.offline_mode) setColorScheme(R.color.toolbar_offline, R.color.statusbar_offline) } } } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { App.instance.state.permission.of(requestCode).granted() } else { App.instance.state.permission.of(requestCode).denied() } } protected fun enableCastMediaRouterButton(enable: Boolean) { mediaRouteMenuItem?.isVisible = enable invalidateOptionsMenu() } private fun handleIntent(intent: Intent?) { if (intent != null) { NotificationUtil.deleteDownloadNotificationsFromIntent(intent) } } override fun dispatchKeyEvent(event: KeyEvent): Boolean { return if (this.hasPlayServices && castContext != null) { castContext?.onDispatchVolumeKeyEventBeforeJellyBean(event) == true || super.dispatchKeyEvent(event) } else { super.dispatchKeyEvent(event) } } }
bsd-3-clause
3c8c75a6597ac2b36bfa35f845ccc92f
31.842857
119
0.65224
4.986985
false
false
false
false
ojacquemart/spring-kotlin-euro-bets
src/main/kotlin/org/ojacquemart/eurobets/firebase/management/league/ImageModerator.kt
2
2090
package org.ojacquemart.eurobets.firebase.management.league import org.ojacquemart.eurobets.firebase.Collections import org.ojacquemart.eurobets.firebase.config.FirebaseRef import org.ojacquemart.eurobets.firebase.config.FirebaseSettings import org.ojacquemart.eurobets.firebase.rx.RxFirebase import org.ojacquemart.eurobets.lang.loggerFor import org.springframework.stereotype.Component import rx.Observable import javax.annotation.PostConstruct @Component class ImageModerator(val ref: FirebaseRef, val mailSender: MailSender<League>) { private val log = loggerFor<ImageModerator>() @PostConstruct fun init() { moderate() } private fun moderate() { log.info("Leagues images moderation") RxFirebase.observeList(this.ref.firebase.child(Collections.leagues), League::class.java) .flatMapIterable { it -> it } .filter { it -> it.needsModeration() } .flatMap { it -> copyWithImageAsDataUrl(it) } .map { it -> getMessage(ref.settings, it) } .subscribe { it -> log.info("Send mail for ${it.item.name}") mailSender.sendMail(it) } } fun copyWithImageAsDataUrl(league: League): Observable<League> { return RxFirebase.observe(this.ref.firebase.child(Collections.leaguesImages).child("${league.image}")) .filter { ds -> ds.value != null } .map { ds -> ds.value.toString() } .map { value -> league.copy(image = value) } } fun getMessage(firebaseSettings: FirebaseSettings, league: League): Mail<League> { return Mail(subject = "[euro-bets] ${league.slug} moderation", content = """ This team needs a moderation operation. <br /> <a href="https://${firebaseSettings.app}.firebaseio.com/leagues/${league.slug}/imageModerated">Moderate</a> """, item = league, imageBase64 = ImageBase64.create(league.image, "/tmp/", league.slug)) } }
unlicense
d986825e1bf7175a3dcf8dcd5347a7cf
37.703704
123
0.631579
4.418605
false
false
false
false
HedvigInsurance/bot-service
src/main/java/com/hedvig/botService/dataTypes/HouseExtraBuildings.kt
1
1452
package com.hedvig.botService.dataTypes class HouseExtraBuildings : HedvigDataType() { private var extraBuildings: Int? = null override fun validate(input: String): Boolean { try { val extraBuildings = Integer.parseInt(input) if (extraBuildings < MIN_NUMBER_OF_EXTRA_BUILDINGS) { this.errorMessage = "{INPUT} extra byggnader låter väldigt få. Prova igen tack!" return false } if (extraBuildings > MAX_NUMBER_OF_EXTRA_BUILDINGS) { this.errorMessage = "{INPUT} extra byggnader?! Låter som väldigt många! Hmm... Prova igen tack!" return false } this.extraBuildings = extraBuildings } catch (e: NumberFormatException) { extraBuildings = null this.errorMessage = "{INPUT} verkar vara ett konstigt antal extra byggnader. Prova igen tack" return false } return true } override fun getErrorMessageId(): String? { return extraBuildings?.let { extraBuildings -> if (extraBuildings < MIN_NUMBER_OF_EXTRA_BUILDINGS) { return "hedvig.data.type.house.extra.buildings.to.few" } if (extraBuildings > MAX_NUMBER_OF_EXTRA_BUILDINGS) { "hedvig.data.type.house.extra.buildings.to.many" } else null } ?: "hedvig.data.type.house.extra.buildings.not.a.number" } companion object { private const val MIN_NUMBER_OF_EXTRA_BUILDINGS = 0 private const val MAX_NUMBER_OF_EXTRA_BUILDINGS = 20 } }
agpl-3.0
553d7f13b94a2c943c0d3b94868b332f
31.863636
104
0.674274
3.717224
false
false
false
false
donald-w/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/multimediacard/AudioRecorder.kt
1
3554
/* * 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]> * Copyright (c) 2021 David Allison <[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 import android.content.Context import android.media.MediaRecorder import com.ichi2.compat.CompatHelper import com.ichi2.utils.KotlinCleanup import timber.log.Timber import java.io.IOException import java.lang.Exception import kotlin.Throws class AudioRecorder { @KotlinCleanup("lateinit mRecorder") private var mRecorder: MediaRecorder? = null private var mOnRecordingInitialized: Runnable? = null private fun initMediaRecorder(context: Context, audioPath: String): MediaRecorder { val mr = CompatHelper.getCompat().getMediaRecorder(context) mr.setAudioSource(MediaRecorder.AudioSource.MIC) mr.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP) onRecordingInitialized() mr.setOutputFile(audioPath) // audioPath could change return mr } private fun onRecordingInitialized() { if (mOnRecordingInitialized != null) { mOnRecordingInitialized!!.run() } } @Throws(IOException::class) fun startRecording(context: Context, audioPath: String) { var highSampling = false try { // try high quality AAC @ 44.1kHz / 192kbps first // can throw IllegalArgumentException if codec isn't supported mRecorder = initMediaRecorder(context, audioPath) mRecorder!!.setAudioEncoder(MediaRecorder.AudioEncoder.AAC) mRecorder!!.setAudioChannels(2) mRecorder!!.setAudioSamplingRate(44100) mRecorder!!.setAudioEncodingBitRate(192000) // this can also throw IOException if output path is invalid mRecorder!!.prepare() mRecorder!!.start() highSampling = true } catch (e: Exception) { Timber.w(e) // in all cases, fall back to low sampling } if (!highSampling) { // if we are here, either the codec didn't work or output file was invalid // fall back on default mRecorder = initMediaRecorder(context, audioPath) mRecorder!!.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB) mRecorder!!.prepare() mRecorder!!.start() } } fun stopRecording() { if (mRecorder != null) { mRecorder!!.stop() } } fun setOnRecordingInitializedHandler(onRecordingInitialized: Runnable?) { mOnRecordingInitialized = onRecordingInitialized } fun release() { if (mRecorder != null) { mRecorder!!.release() } } }
gpl-3.0
f698f04f6739a04ebc9fbb25f39e8d7c
36.410526
87
0.670231
4.376847
false
false
false
false
Ztiany/Repository
Kotlin/Kotlin-github/retroapollo-android/src/main/java/com/bennyhuo/retroapollo/coroutine/CoroutineCallAdapterFactory.kt
2
3484
package com.bennyhuo.retroapollo.coroutine import com.apollographql.apollo.ApolloCall import com.apollographql.apollo.ApolloCall.Callback import com.apollographql.apollo.api.Response import com.apollographql.apollo.exception.ApolloException import com.bennyhuo.retroapollo.CallAdapter import kotlinx.coroutines.experimental.CompletableDeferred import kotlinx.coroutines.experimental.Deferred import java.lang.reflect.ParameterizedType import java.lang.reflect.Type class CoroutineCallAdapterFactory private constructor() : CallAdapter.Factory() { companion object { @JvmStatic @JvmName("create") operator fun invoke() = CoroutineCallAdapterFactory() } override fun get(returnType: Type): CallAdapter<*, *>? { if (Deferred::class.java != getRawType(returnType)) { return null } if (returnType !is ParameterizedType) { throw IllegalStateException( "Deferred return type must be parameterized as Deferred<Foo> or Deferred<out Foo>") } val responseType = getParameterUpperBound(0, returnType) val rawDeferredType = getRawType(responseType) return if (rawDeferredType == Response::class.java) { if (responseType !is ParameterizedType) { throw IllegalStateException( "Response must be parameterized as Response<Foo> or Response<out Foo>") } ResponseCallAdapter<Any>(getParameterUpperBound(0, responseType)) } else { BodyCallAdapter<Any>(responseType) } } private class BodyCallAdapter<T>( private val responseType: Type ) : CallAdapter<T, Deferred<T>> { override fun responseType() = responseType override fun adapt(call: ApolloCall<T>): Deferred<T> { val deferred = CompletableDeferred<T>() deferred.invokeOnCompletion { if (deferred.isCancelled) { call.cancel() } } call.enqueue(object : Callback<T>() { override fun onFailure(e: ApolloException) { deferred.completeExceptionally(e) } override fun onResponse(response: Response<T>) { if (response.data() == null) { deferred.completeExceptionally(ApolloException(response.errors().toString())) } else { deferred.complete(response.data()!!) } } }) return deferred } } private class ResponseCallAdapter<T>( private val responseType: Type ) : CallAdapter<T, Deferred<Response<T>>> { override fun responseType() = responseType override fun adapt(call: ApolloCall<T>): Deferred<Response<T>> { val deferred = CompletableDeferred<Response<T>>() deferred.invokeOnCompletion { if (deferred.isCancelled) { call.cancel() } } call.enqueue(object : Callback<T>() { override fun onFailure(t: ApolloException) { deferred.completeExceptionally(t) } override fun onResponse(response: Response<T>) { deferred.complete(response) } }) return deferred } } }
apache-2.0
eedc0b61e19c58dd925be4298e6e32f6
32.825243
103
0.58496
5.565495
false
false
false
false
varpeti/Suli
Android/work/varpe8/homeworks/06/HF06/app/src/main/java/ml/varpeti/hf06/MainActivity.kt
1
2881
package ml.varpeti.hf06 import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button import android.widget.TextView class MainActivity : AppCompatActivity() { val bincalc = BinaryCalc() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } fun b2tw(tw: TextView, s: CharSequence) { when (s) { "0" -> if (tw.text.length<31) tw.text = "${tw.text}0" "1" -> if (tw.text.length<31) tw.text = "${tw.text}1" "\u232b" -> if (tw.text.isNotEmpty()) tw.text = tw.text.substring(0, tw.text.length - 1) "DEL" -> tw.text = "" } } fun onClickB0(view : View) { val v = view as Button val tw = findViewById<TextView>(R.id.b0) b2tw(tw,v.text) } fun onClickB1(view : View) { val v = view as Button val tw = findViewById<TextView>(R.id.b1) b2tw(tw,v.text) } fun onClickB2(view : View) { val v = view as Button val b0 = findViewById<TextView>(R.id.b0) val b1 = findViewById<TextView>(R.id.b1) val b2 = findViewById<TextView>(R.id.b2) val b0t = when { b0.text.isEmpty() -> "0" b0.text=="-" -> "0" else -> b0.text } val b1t = when { b1.text.isEmpty() -> "0" b1.text=="-" -> "0" else -> b1.text } when (v.text) { "+" -> b2.text = bincalc.add(b0t,b1t) "-" -> b2.text = bincalc.sub(b0t,b1t) "\u2b09" -> b0.text = b2.text "\u2b08" -> b1.text = b2.text } } public override fun onSaveInstanceState(savedInstanceState: Bundle) { super.onSaveInstanceState(savedInstanceState) val b0 = findViewById<TextView>(R.id.b0) val b1 = findViewById<TextView>(R.id.b1) val b2 = findViewById<TextView>(R.id.b2) savedInstanceState.putString("b0", b0.text.toString()) savedInstanceState.putString("b1", b1.text.toString()) savedInstanceState.putString("b2", b2.text.toString()) } public override fun onRestoreInstanceState(savedInstanceState: Bundle?) { super.onRestoreInstanceState(savedInstanceState) val b0 = findViewById<TextView>(R.id.b0) val b1 = findViewById<TextView>(R.id.b1) val b2 = findViewById<TextView>(R.id.b2) if (savedInstanceState != null) { b0.text = savedInstanceState.getString("b0") ?: "" b1.text = savedInstanceState.getString("b1") ?: "" b2.text = savedInstanceState.getString("b2") ?: "" } } }
unlicense
675b111459f7322b467a02763db7c28c
28.701031
100
0.547032
3.587796
false
false
false
false
beamishjabberwock/kedux-recorder
src/test/kotlin/com/angusmorton/kedux/recorder/Actions.kt
1
989
package com.angusmorton.kedux.recorder import com.angusmorton.kedux.Action import com.angusmorton.kedux.State import com.angusmorton.kedux.createReducer internal val PLUS_ACTION = "com.angusmorton.kedux.recorder.getPLUS_ACTION" internal val MINUS_ACTION = "com.angusmorton.kedux.recorder.getMINUS_ACTION" internal val RESET_ACTION = "com.angusmorton.kedux.recorder.getRESET_ACTION" internal val INIT_ACTION = "com.angusmorton.kedux.recorder.getINIT_ACTION" internal data class TestState(val value: Int) : State internal data class TestAction(val type: String, val by: Int = 0) : Action internal val counterReducer = createReducer<TestState> { state, action -> if (action is TestAction) { when (action.type) { PLUS_ACTION -> state.copy(value = state.value + action.by) MINUS_ACTION -> state.copy(value = state.value - action.by) RESET_ACTION -> state.copy(value = 0) else -> state } } else { state } }
apache-2.0
c09ee8472b02f7f7b59c8dd57cbda328
35.666667
76
0.706775
3.422145
false
true
false
false
stripe/stripe-android
stripe-core/src/main/java/com/stripe/android/core/networking/NetworkConstants.kt
1
1563
package com.stripe.android.core.networking import androidx.annotation.RestrictTo /** * If the SDK receives a "Too Many Requests" (429) status code from Stripe, * it will automatically retry the request using exponential backoff. * * See https://stripe.com/docs/rate-limits for more information. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) const val HTTP_TOO_MANY_REQUESTS = 429 @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) val DEFAULT_RETRY_CODES: Iterable<Int> = HTTP_TOO_MANY_REQUESTS..HTTP_TOO_MANY_REQUESTS @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) const val HEADER_USER_AGENT = "User-Agent" @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) const val HEADER_ACCEPT_CHARSET = "Accept-Charset" @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) const val HEADER_ACCEPT_LANGUAGE = "Accept-Language" @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) const val HEADER_CONTENT_TYPE = "Content-Type" @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) const val HEADER_ACCEPT = "Accept" @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) const val HEADER_STRIPE_VERSION = "Stripe-Version" @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) const val HEADER_STRIPE_ACCOUNT = "Stripe-Account" @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) const val HEADER_STRIPE_LIVEMODE = "Stripe-Livemode" @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) const val HEADER_AUTHORIZATION = "Authorization" @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) const val HEADER_IDEMPOTENCY_KEY = "Idempotency-Key" @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) const val HEADER_X_STRIPE_USER_AGENT = "X-Stripe-User-Agent"
mit
b9d35e59d0f1d791ce820463ac930584
31.5625
87
0.792067
3.496644
false
false
false
false
jak78/extreme-carpaccio
clients/kotlin/src/test/kotlin/xcarpaccio/MyServerTest.kt
1
3932
package xcarpaccio import io.kotlintest.Spec import io.kotlintest.matchers.shouldBe import io.kotlintest.mock.mock import io.kotlintest.specs.StringSpec import org.apache.http.Header import org.apache.http.client.methods.HttpEntityEnclosingRequestBase import org.apache.http.client.methods.HttpGet import org.apache.http.client.methods.HttpPost import org.apache.http.client.methods.HttpRequestBase import org.apache.http.entity.StringEntity import org.apache.http.impl.client.HttpClientBuilder import org.apache.http.util.EntityUtils import org.mockito.BDDMockito.then import java.util.* class MyServerTest : StringSpec() { val TEST_PORT = 8001 val logger: Logger = mock() val myServer: MyServer = MyServer(TEST_PORT, logger) override val oneInstancePerTest = false override fun interceptSpec(context: Spec, spec: () -> Unit) { myServer.start(false) spec() myServer.shutdown() } init { "MyServer should respond 'pong' when 'ping' is received" { val response = sendSimpleRequest("/ping", "GET") response.statusCode shouldBe 200 response.body shouldBe "pong" } "MyServer should log feedback message received via POST" { sendJson("/feedback", "POST", """{"type":"ERROR", "content":"The field \"total\" in the response is missing."}""") then(logger).should().log("""ERROR: The field "total" in the response is missing.""") } "MyServer should respond to order" { val response = sendJson("/order", "POST", """{"prices":[3.5], "quantities":[2], "country":"FR", "reduction":"STANDARD"}""") then(logger).should().log("POST /order {quantities=[2], country=FR, prices=[3.5], reduction=STANDARD}") then(logger).should().log("Order(prices=[3.5], quantities=[2], country=FR, reduction=STANDARD)") response.statusCode shouldBe 200 response.body shouldBe "" } } private fun sendSimpleRequest(url: String, method: String, headers: HashMap<String, String> = hashMapOf()): HttpResponse { val request = createHttpRequestInstance(url, method) return executeRequest(headers, request) } private fun sendJson(url: String, method: String, json: String, headers: HashMap<String, String> = hashMapOf()): HttpResponse { val httpRequest = createHttpRequestInstance(url, method) if (httpRequest is HttpEntityEnclosingRequestBase) { httpRequest.setHeader("Content-Type", "application/json") httpRequest.entity = StringEntity(json) } else { throw Exception("Cannot send JSON with this HTTP method ($method).") } return executeRequest(headers, httpRequest) } private fun createHttpRequestInstance(url: String, method: String): HttpRequestBase { val fullUrl = "http://localhost:" + TEST_PORT + url return when (method) { "GET" -> { HttpGet(fullUrl) } "POST" -> { HttpPost(fullUrl) } else -> { throw Exception("Invalid method") } } } private fun executeRequest(headers: HashMap<String, String>, request: HttpRequestBase): HttpResponse { val httpClient = HttpClientBuilder.create().build() for ((key, value) in headers) { request.setHeader(key, value) } request.setHeader("Connection", "Close") val response = httpClient.execute(request)!! val body = if (response.entity != null) { EntityUtils.toString(response.entity) } else { null } val responseHeaders = response.allHeaders!! return HttpResponse(responseHeaders, body, response.statusLine?.statusCode!!, response.statusLine?.reasonPhrase ?: "") } data class HttpResponse(val headers: Array<Header>, val body: String?, val statusCode: Int, val statusDescription: String) }
bsd-3-clause
665e1ee8197ee1e977bc68a431efc57b
38.32
135
0.656409
4.453001
false
true
false
false
Undin/intellij-rust
src/test/kotlin/org/rust/ide/inspections/lints/naming/RsModuleNamingInspectionTest.kt
2
2528
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.inspections.lints.naming import org.rust.ide.inspections.RsInspectionsTestBase import org.rust.ide.inspections.lints.RsModuleNamingInspection class RsModuleNamingInspectionTest : RsInspectionsTestBase(RsModuleNamingInspection::class) { fun `test modules`() = checkByText(""" mod module_ok {} mod <warning descr="Module `moduleA` should have a snake case name such as `module_a`">moduleA</warning> {} """) fun `test modules suppression`() = checkByText(""" #[allow(non_snake_case)] mod moduleA {} """) fun `test modules suppression bad style 1`() = checkByText(""" #[allow(bad_style)] mod moduleA {} """) fun `test modules suppression bad style 2`() = checkByFileTree(""" //- main.rs #![allow(bad_style)] mod x; //- x.rs mod moduleA/*caret*/ {} """) fun `test modules suppression nonstandard style`() = checkByText(""" #[allow(nonstandard_style)] mod moduleA {} """) fun `test modules fix`() = checkFixByText("Rename to `mod_foo`", """ mod <warning descr="Module `modFoo` should have a snake case name such as `mod_foo`">modF<caret>oo</warning> { pub const ONE: u32 = 1; } fn use_mod() { let a = modFoo::ONE; } """, """ mod mod_foo { pub const ONE: u32 = 1; } fn use_mod() { let a = mod_foo::ONE; } """, preview = null) fun `test module not support case`() = checkByText(""" mod 模块名 {} """) fun `test mod decl 1`() = checkFixByFileTreeWithoutHighlighting("Rename to `foo`", """ //- main.rs fn main() { Foo::func(); } mod Foo/*caret*/; //- Foo.rs pub fn func() {} """, """ //- main.rs fn main() { foo::func(); } mod foo/*caret*/; //- foo.rs pub fn func() {} """, preview = null) fun `test mod decl 2`() = checkFixByFileTreeWithoutHighlighting("Rename to `foo`", """ //- main.rs fn main() { Foo::func(); } mod Foo/*caret*/; //- Foo/mod.rs pub fn func() {} """, """ //- main.rs fn main() { foo::func(); } mod foo/*caret*/; //- foo/mod.rs pub fn func() {} """, preview = null) }
mit
c1e16ef686acb6a362c9235e837c720c
25.270833
118
0.519826
4.161716
false
true
false
false
JustinMockler/pi-recipe-viewer
src/main/kotlin/com/justinmockler/pirecipeviewer/SettingsWindow.kt
1
4930
package com.justinmockler.pirecipeviewer import java.awt.* import java.util.prefs.Preferences import javax.swing.* // The class for the settings window, which allows a user to adjust how the application looks and functions internal class SettingsWindow(recipeViewer: RecipeViewer) { // Initialize the companion object for the settings text, so we can reference it from other classes companion object { const val recipeFolderText = "Recipe Folder Location:" const val googleDrive = "Google Drive" const val local = "Local" const val shutdownOptionsText = "On Window Close:" const val exitApplication = "Exit Application" const val shutdownDevice = "Shutdown Device" const val orientationText = "Viewer Orientation:" const val landscape = "Landscape" const val portrait = "Portrait" } // Initialize the global variables used in the class private val preferences: Preferences = Preferences.userNodeForPackage(javaClass) private val settingsDialog: JDialog private val recipeFolderOptions = arrayOf(googleDrive, local) private val recipeFolderDropdown: JComboBox<String> private val shutdownOptions = arrayOf(exitApplication, shutdownDevice) private val shutdownDropdown: JComboBox<String> private val orientations = arrayOf(landscape, portrait) private val orientationDropdown: JComboBox<String> private val preferencesPanel = JPanel(GridLayout(3, 2, 4, 4)) // The constructor for the settings window, which takes in the recipe viewer as a variable init { // Put a empty border around the preferences panel for padding preferencesPanel.border = BorderFactory.createEmptyBorder(20, 20, 20, 20) // Initialize the settings dropdown menus recipeFolderDropdown = createSettingsDropdown(recipeFolderText, recipeFolderOptions) shutdownDropdown = createSettingsDropdown(shutdownOptionsText, shutdownOptions) orientationDropdown = createSettingsDropdown(orientationText, orientations) // Add the save button to a panel at the bottom of the window val buttonPanel = JPanel() buttonPanel.border = BorderFactory.createEmptyBorder(0, 0, 20, 0) buttonPanel.layout = BoxLayout(buttonPanel, BoxLayout.X_AXIS) val saveButton = JButton("Save") saveButton.addActionListener { saveSettings(recipeViewer) } saveButton.margin = Insets(10, 10, 10, 10) buttonPanel.add(Box.createHorizontalGlue()) buttonPanel.add(saveButton) buttonPanel.add(Box.createHorizontalGlue()) // Create the main panel that will hold the two panels above val mainPanel = JPanel(BorderLayout()) mainPanel.add(preferencesPanel, BorderLayout.CENTER) mainPanel.add(buttonPanel, BorderLayout.PAGE_END) // Initialize the settings dialog and customize its properties settingsDialog = JDialog() settingsDialog.title = "Settings (" + javaClass.`package`.implementationVersion + ")" settingsDialog.setIconImage(ImageIcon(javaClass.getResource("/images/system/icon.png")).image) settingsDialog.isResizable = false settingsDialog.modalityType = Dialog.ModalityType.APPLICATION_MODAL // Add the main panel to the dialog and then show it to the user at the center of the screen settingsDialog.add(mainPanel) settingsDialog.pack() settingsDialog.setLocationRelativeTo(null) settingsDialog.isVisible = true } // For creating the label and dropdown pairs used on the settings menu private fun createSettingsDropdown(settingsLabelText: String, dropdownOptions: Array<String>): JComboBox<String> { val settingsLabel = JLabel(settingsLabelText) settingsLabel.horizontalAlignment = JLabel.RIGHT preferencesPanel.add(settingsLabel) val settingsDropdown = JComboBox(dropdownOptions) settingsDropdown.selectedItem = preferences.get(settingsLabelText, dropdownOptions[0]) settingsDropdown.preferredSize = Dimension(150, 40) preferencesPanel.add(settingsDropdown) return settingsDropdown } // For saving the settings and calling the recipe viewer to apply the settings private fun saveSettings(recipeViewer: RecipeViewer) { // Save the setting values from the dropdowns to the preferences file preferences.put(recipeFolderText, recipeFolderOptions[recipeFolderDropdown.selectedIndex]) preferences.put(shutdownOptionsText, shutdownOptions[shutdownDropdown.selectedIndex]) preferences.put(orientationText, orientations[orientationDropdown.selectedIndex]) // Hide the settings dialog and then dispose of it settingsDialog.isVisible = false settingsDialog.dispose() // Apply the preferences to the recipe viewer recipeViewer.applyUserPreferences() } }
mit
88139d1b71d0da626cd83d756e849ae2
47.333333
118
0.73002
5.173137
false
false
false
false
arcuri82/testing_security_development_enterprise_systems
advanced/exercise-solutions/card-game/part-10/user-collections/src/main/kotlin/org/tsdes/advanced/exercises/cardgame/usercollections/db/UserService.kt
8
3884
package org.tsdes.advanced.exercises.cardgame.usercollections.db import org.springframework.data.jpa.repository.Lock import org.springframework.data.jpa.repository.Query import org.springframework.data.repository.CrudRepository import org.springframework.data.repository.query.Param import org.springframework.stereotype.Repository import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import org.tsdes.advanced.exercises.cardgame.usercollections.CardService import javax.persistence.LockModeType @Repository interface UserRepository : CrudRepository<User, String>{ @Lock(LockModeType.PESSIMISTIC_WRITE) @Query("select u from User u where u.userId = :id") fun lockedFind(@Param("id") userId: String) : User? } @Service @Transactional class UserService( private val userRepository: UserRepository, private val cardService: CardService ) { companion object{ const val CARDS_PER_PACK = 5 } fun findByIdEager(userId: String) : User?{ val user = userRepository.findById(userId).orElse(null) if(user != null){ user.ownedCards.size } return user } fun registerNewUser(userId: String) : Boolean{ if(userRepository.existsById(userId)){ return false } val user = User() user.userId = userId user.cardPacks = 3 user.coins = 100 userRepository.save(user) return true } private fun validateCard(cardId: String) { if (!cardService.isInitialized()) { throw IllegalStateException("Card service is not initialized") } if (!cardService.cardCollection.any { it.cardId == cardId }) { throw IllegalArgumentException("Invalid cardId: $cardId") } } private fun validateUser(userId: String) { if (!userRepository.existsById(userId)) { throw IllegalArgumentException("User $userId does not exist") } } private fun validate(userId: String, cardId: String) { validateUser(userId) validateCard(cardId) } fun buyCard(userId: String, cardId: String) { validate(userId, cardId) val price = cardService.price(cardId) val user = userRepository.lockedFind(userId)!! if (user.coins < price) { throw IllegalArgumentException("Not enough coins") } user.coins -= price addCard(user, cardId) } private fun addCard(user: User, cardId: String) { user.ownedCards.find { it.cardId == cardId } ?.apply { numberOfCopies++ } ?: CardCopy().apply { this.cardId = cardId this.user = user this.numberOfCopies = 1 }.also { user.ownedCards.add(it) } } fun millCard(userId: String, cardId: String) { validate(userId, cardId) val user = userRepository.lockedFind(userId)!! val copy = user.ownedCards.find { it.cardId == cardId } if(copy == null || copy.numberOfCopies == 0){ throw IllegalArgumentException("User $userId does not own a copy of $cardId") } copy.numberOfCopies-- val millValue = cardService.millValue(cardId) user.coins += millValue } fun openPack(userId: String) : List<String> { validateUser(userId) val user = userRepository.lockedFind(userId)!! if(user.cardPacks < 1){ throw IllegalArgumentException("No pack to open") } user.cardPacks-- val selection = cardService.getRandomSelection(CARDS_PER_PACK) val ids = mutableListOf<String>() selection.forEach { addCard(user, it.cardId) ids.add(it.cardId) } return ids } }
lgpl-3.0
31f3bf372c8b46ed66a466b31340f278
26.167832
89
0.629248
4.548009
false
false
false
false
androidx/androidx
benchmark/benchmark-common/src/main/java/androidx/benchmark/perfetto/PerfettoCaptureWrapper.kt
3
4555
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.benchmark.perfetto import android.os.Build import android.util.Log import androidx.annotation.RequiresApi import androidx.annotation.RestrictTo import androidx.benchmark.Outputs import androidx.benchmark.Outputs.dateToFileName import androidx.benchmark.PropOverride import androidx.benchmark.perfetto.PerfettoHelper.Companion.isAbiSupported /** * Wrapper for [PerfettoCapture] which does nothing below L. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) class PerfettoCaptureWrapper { private var capture: PerfettoCapture? = null private val TRACE_ENABLE_PROP = "persist.traced.enable" init { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { capture = PerfettoCapture() } } companion object { val inUseLock = Object() /** * Prevents re-entrance of perfetto trace capture, as it doesn't handle this correctly * * (Single file output location, process cleanup, etc.) */ var inUse = false } @RequiresApi(Build.VERSION_CODES.LOLLIPOP) private fun start( appTagPackages: List<String>, userspaceTracingPackage: String? ): Boolean { capture?.apply { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Log.d(PerfettoHelper.LOG_TAG, "Recording perfetto trace") if (userspaceTracingPackage != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R ) { enableAndroidxTracingPerfetto( targetPackage = userspaceTracingPackage, provideBinariesIfMissing = true ) } start(appTagPackages) } } return true } @RequiresApi(Build.VERSION_CODES.LOLLIPOP) private fun stop(traceLabel: String): String { return Outputs.writeFile( fileName = "${traceLabel}_${dateToFileName()}.perfetto-trace", reportKey = "perfetto_trace_$traceLabel" ) { capture!!.stop(it.absolutePath) } } fun record( fileLabel: String, appTagPackages: List<String>, userspaceTracingPackage: String?, traceCallback: ((String) -> Unit)? = null, block: () -> Unit ): String? { // skip if Perfetto not supported, or on Cuttlefish (where tracing doesn't work) if (Build.VERSION.SDK_INT < 21 || !isAbiSupported()) { block() return null } synchronized(inUseLock) { if (inUse) { throw IllegalStateException( "Reentrant Perfetto Tracing is not supported." + " This means you cannot use more than one of" + " BenchmarkRule/MacrobenchmarkRule/PerfettoTraceRule/PerfettoTrace.record" + " together." ) } inUse = true } // Prior to Android 11 (R), a shell property must be set to enable perfetto tracing, see // https://perfetto.dev/docs/quickstart/android-tracing#starting-the-tracing-services val propOverride = if (Build.VERSION.SDK_INT == Build.VERSION_CODES.Q) { PropOverride(TRACE_ENABLE_PROP, "1") } else null val path: String try { propOverride?.forceValue() start(appTagPackages, userspaceTracingPackage) try { block() } finally { // finally here to ensure trace is fully recorded if block throws path = stop(fileLabel) traceCallback?.invoke(path) } return path } finally { propOverride?.resetIfOverridden() synchronized(inUseLock) { inUse = false } } } }
apache-2.0
d82339324027a7f3f5a47d9d7bbdbd5a
32.740741
100
0.597146
4.73001
false
false
false
false
kotlinx/kotlinx.html
buildSrc/src/main/kotlin/kotlinx/html/generate/tag-builders.kt
1
1460
package kotlinx.html.generate val emptyTags = """area base basefont bgsound br col command device embed frame hr img input keygen link menuitem meta param source track wbr""".lines().toSet() fun Appendable.htmlTagBuilders(receiver : String, tag : TagInfo) { val contentlessTag = tag.name.toLowerCase() in contentlessTags val probablyContentOnly = tag.possibleChildren.isEmpty() && tag.name.toLowerCase() !in emptyTags && !contentlessTag htmlTagBuilderMethod(receiver, tag, true) if (probablyContentOnly) { htmlTagBuilderMethod(receiver, tag, false) } else if (contentlessTag) { deprecated("This tag doesn't support content or requires unsafe (try unsafe {})") suppress("DEPRECATION") htmlTagBuilderMethod(receiver, tag, false) } val someEnumAttribute = tag.attributes.filter { it.type == AttributeType.ENUM }.maxBy { it.enumValues.size } // ?? if (someEnumAttribute != null && someEnumAttribute.enumValues.size < 25) { htmlTagEnumBuilderMethod(receiver, tag, true, someEnumAttribute, 0) if (probablyContentOnly) { htmlTagEnumBuilderMethod(receiver, tag, false, someEnumAttribute, 0) } else if (contentlessTag) { deprecated("This tag doesn't support content or requires unsafe (try unsafe {})") suppress("DEPRECATION") htmlTagEnumBuilderMethod(receiver, tag, false, someEnumAttribute, 0) } } emptyLine() }
apache-2.0
a657b6b29040d66c23a5dc457dcdc807
28.22
119
0.696575
4.078212
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/nbt/editor/NbtToolbar.kt
1
1367
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.nbt.editor import com.demonwav.mcdev.nbt.NbtVirtualFile import com.demonwav.mcdev.util.runWriteTaskLater import javax.swing.JButton import javax.swing.JComboBox import javax.swing.JPanel class NbtToolbar(nbtFile: NbtVirtualFile) { lateinit var panel: JPanel private lateinit var compressionBox: JComboBox<CompressionSelection> lateinit var saveButton: JButton private var lastSelection: CompressionSelection init { compressionBox.addItem(CompressionSelection.GZIP) compressionBox.addItem(CompressionSelection.UNCOMPRESSED) compressionBox.selectedItem = if (nbtFile.isCompressed) CompressionSelection.GZIP else CompressionSelection.UNCOMPRESSED lastSelection = selection if (!nbtFile.isWritable || !nbtFile.parseSuccessful) { compressionBox.isEnabled = false } if (!nbtFile.parseSuccessful) { panel.isVisible = false } saveButton.addActionListener { lastSelection = selection runWriteTaskLater { nbtFile.writeFile(this) } } } val selection get() = compressionBox.selectedItem as CompressionSelection }
mit
e7fdb3535dc7c1b2cec8c759ebba1eca
25.288462
102
0.691295
4.847518
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/ui/onboarding/OnboardingExtrasFragment.kt
1
7500
package de.tum.`in`.tumcampusapp.component.ui.onboarding import android.content.Context import android.content.SharedPreferences import android.os.Bundle import android.view.View import androidx.core.content.edit import com.google.gson.Gson import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.api.app.AuthenticationManager import de.tum.`in`.tumcampusapp.api.app.TUMCabeClient import de.tum.`in`.tumcampusapp.api.app.model.TUMCabeVerification import de.tum.`in`.tumcampusapp.api.app.model.UploadStatus import de.tum.`in`.tumcampusapp.api.tumonline.AccessTokenManager import de.tum.`in`.tumcampusapp.component.other.generic.fragment.FragmentForLoadingInBackground import de.tum.`in`.tumcampusapp.component.ui.chat.ChatRoomController import de.tum.`in`.tumcampusapp.component.ui.chat.model.ChatMember import de.tum.`in`.tumcampusapp.component.ui.onboarding.di.OnboardingComponent import de.tum.`in`.tumcampusapp.component.ui.onboarding.di.OnboardingComponentProvider import de.tum.`in`.tumcampusapp.service.SilenceService import de.tum.`in`.tumcampusapp.utils.CacheManager import de.tum.`in`.tumcampusapp.utils.Const import de.tum.`in`.tumcampusapp.utils.NetUtils import de.tum.`in`.tumcampusapp.utils.Utils import kotlinx.android.synthetic.main.fragment_onboarding_extras.bugReportsCheckBox import kotlinx.android.synthetic.main.fragment_onboarding_extras.finishButton import kotlinx.android.synthetic.main.fragment_onboarding_extras.groupChatCheckBox import kotlinx.android.synthetic.main.fragment_onboarding_extras.privacyPolicyButton import kotlinx.android.synthetic.main.fragment_onboarding_extras.silentModeCheckBox import org.jetbrains.anko.defaultSharedPreferences import org.jetbrains.anko.support.v4.browse import java.io.IOException import javax.inject.Inject class OnboardingExtrasFragment : FragmentForLoadingInBackground<ChatMember>( R.layout.fragment_onboarding_extras, R.string.connect_to_tum_online ) { private val onboardingComponent: OnboardingComponent by lazy { (requireActivity() as OnboardingComponentProvider).onboardingComponent() } @Inject lateinit var cacheManager: CacheManager @Inject lateinit var tumCabeClient: TUMCabeClient @Inject lateinit var chatRoomController: ChatRoomController @Inject lateinit var authManager: AuthenticationManager @Inject lateinit var navigator: OnboardingNavigator override fun onAttach(context: Context) { super.onAttach(context) onboardingComponent.inject(this) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) bugReportsCheckBox.isChecked = Utils.getSettingBool(requireContext(), Const.BUG_REPORTS, true) if (AccessTokenManager.hasValidAccessToken(requireContext())) { silentModeCheckBox.isChecked = Utils.getSettingBool(requireContext(), Const.SILENCE_SERVICE, false) silentModeCheckBox.setOnCheckedChangeListener { _, isChecked -> if (isChecked && !SilenceService.hasPermissions(requireContext())) { SilenceService.requestPermissions(requireContext()) silentModeCheckBox.isChecked = false } } } else { silentModeCheckBox.isChecked = false silentModeCheckBox.isEnabled = false } if (AccessTokenManager.hasValidAccessToken(requireContext())) { groupChatCheckBox.isChecked = Utils.getSettingBool(requireContext(), Const.GROUP_CHAT_ENABLED, true) } else { groupChatCheckBox.isChecked = false groupChatCheckBox.isEnabled = false } if (AccessTokenManager.hasValidAccessToken(requireContext())) { cacheManager.fillCache() } privacyPolicyButton.setOnClickListener { browse(getString(R.string.url_privacy_policy)) } finishButton.setOnClickListener { startLoading() } } override fun onLoadInBackground(): ChatMember? { if (!NetUtils.isConnected(requireContext())) { showNoInternetLayout() return null } // By now, we should have generated the RSA key and uploaded it to our server and TUMonline val lrzId = Utils.getSetting(requireContext(), Const.LRZ_ID, "") val name = Utils.getSetting(requireContext(), Const.CHAT_ROOM_DISPLAY_NAME, getString(R.string.not_connected_to_tumonline)) val currentChatMember = ChatMember(lrzId) currentChatMember.displayName = name if (currentChatMember.lrzId.isNullOrEmpty()) { return currentChatMember } // Tell the server the new member val member: ChatMember? try { // After the user has entered their display name, create the new member on the server member = tumCabeClient.createMember(currentChatMember) } catch (e: IOException) { Utils.log(e) Utils.showToastOnUIThread(requireActivity(), R.string.error_setup_chat_member) return null } // Catch a possible error, when we didn't get something returned if (member?.lrzId == null) { Utils.showToastOnUIThread(requireActivity(), R.string.error_setup_chat_member) return null } val status = tumCabeClient.verifyKey() if (status?.status != UploadStatus.VERIFIED) { Utils.showToastOnUIThread(requireActivity(), getString(R.string.error_pk_verification)) return null } // Try to restore already joined chat rooms from server return try { val verification = TUMCabeVerification.create(requireContext(), null) val rooms = tumCabeClient.getMemberRooms(member.id, verification) chatRoomController.replaceIntoRooms(rooms) // upload obfuscated ids now that we have a member val uploadStatus = tumCabeClient.getUploadStatus(lrzId) if (uploadStatus != null) { authManager.uploadObfuscatedIds(uploadStatus) } member } catch (e: IOException) { Utils.log(e) null } } override fun onLoadFinished(result: ChatMember?) { if (result == null) { showLoadingEnded() return } // Gets the editor for editing preferences and updates the preference values with the // chosen state requireContext() .defaultSharedPreferences .edit { putBoolean(Const.SILENCE_SERVICE, silentModeCheckBox.isChecked) putBoolean(Const.BACKGROUND_MODE, true) // Enable by default putBoolean(Const.BUG_REPORTS, bugReportsCheckBox.isChecked) if (!result.lrzId.isNullOrEmpty()) { putBoolean(Const.GROUP_CHAT_ENABLED, groupChatCheckBox.isChecked) putBoolean(Const.AUTO_JOIN_NEW_ROOMS, groupChatCheckBox.isChecked) put(Const.CHAT_MEMBER, result) } } finishOnboarding() } private fun finishOnboarding() { navigator.finish() } private fun SharedPreferences.Editor.put(key: String, value: Any) { putString(key, Gson().toJson(value)) } companion object { fun newInstance() = OnboardingExtrasFragment() } }
gpl-3.0
5c7f44efd89f490c5f0a6c202eb1c514
37.461538
102
0.684133
4.841833
false
false
false
false
InsertKoinIO/koin
android/koin-android/src/main/java/org/koin/androidx/viewmodel/ext/android/ViewModelLazy.kt
1
2945
@file:Suppress("DEPRECATION") package org.koin.androidx.viewmodel.ext.android import androidx.activity.ComponentActivity import androidx.annotation.MainThread import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelStoreOwner import androidx.lifecycle.viewmodel.CreationExtras import org.koin.android.ext.android.getKoinScope import org.koin.androidx.viewmodel.resolveViewModel import org.koin.androidx.viewmodel.scope.BundleDefinition import org.koin.core.annotation.KoinInternalApi import org.koin.core.context.GlobalContext import org.koin.core.parameter.ParametersDefinition import org.koin.core.qualifier.Qualifier import org.koin.core.scope.Scope import kotlin.reflect.KClass @OptIn(KoinInternalApi::class) @MainThread fun <T : ViewModel> ComponentActivity.viewModelForClass( clazz: KClass<T>, qualifier: Qualifier? = null, owner: ViewModelStoreOwner = this, state: BundleDefinition? = null, key: String? = null, parameters: ParametersDefinition? = null, ): Lazy<T> { val viewModelStore = owner.viewModelStore return lazy(LazyThreadSafetyMode.NONE) { resolveViewModel( clazz, viewModelStore, extras = state?.invoke()?.toExtras(owner) ?: CreationExtras.Empty, qualifier = qualifier, parameters = parameters, key = key, scope = getKoinScope() ) } } @OptIn(KoinInternalApi::class) @MainThread fun <T : ViewModel> Fragment.viewModelForClass( clazz: KClass<T>, qualifier: Qualifier? = null, owner: () -> ViewModelStoreOwner = { this }, state: BundleDefinition? = null, key: String? = null, parameters: ParametersDefinition? = null, ): Lazy<T> { return lazy(LazyThreadSafetyMode.NONE) { val ownerEager = owner() val viewModelStore = ownerEager.viewModelStore resolveViewModel( clazz, viewModelStore, extras = state?.invoke()?.toExtras(ownerEager) ?: CreationExtras.Empty, qualifier = qualifier, parameters = parameters, key = key, scope = getKoinScope() ) } } @OptIn(KoinInternalApi::class) @MainThread fun <T : ViewModel> getLazyViewModelForClass( clazz: KClass<T>, owner: ViewModelStoreOwner, scope: Scope = GlobalContext.get().scopeRegistry.rootScope, qualifier: Qualifier? = null, state: BundleDefinition? = null, key: String? = null, parameters: ParametersDefinition? = null, ): Lazy<T> { val viewModelStore = owner.viewModelStore return lazy(LazyThreadSafetyMode.NONE) { resolveViewModel( clazz, viewModelStore, extras = state?.invoke()?.toExtras(owner) ?: CreationExtras.Empty, qualifier = qualifier, parameters = parameters, key = key, scope = scope ) } }
apache-2.0
6dd953385ea080f085ff57f38dbf4c13
30.677419
83
0.677419
4.623234
false
false
false
false
Archinamon/GradleAspectJ-Android
android-gradle-aspectj/src/main/kotlin/com/archinamon/api/transform/AspectJTransform.kt
1
9889
package com.archinamon.api.transform import com.android.build.api.transform.* import com.android.build.api.variant.impl.VariantPropertiesImpl import com.android.build.gradle.internal.pipeline.TransformInvocationBuilder import com.android.build.gradle.internal.pipeline.TransformManager import com.android.build.gradle.internal.variant.BaseVariantData import com.android.utils.FileUtils import com.archinamon.AndroidConfig import com.archinamon.api.jars.AspectJMergeJars import com.archinamon.api.AspectJWeaver import com.archinamon.plugin.ConfigScope import com.archinamon.utils.* import com.archinamon.utils.DependencyFilter.isExcludeFilterMatched import com.archinamon.utils.DependencyFilter.isIncludeFilterMatched import com.google.common.collect.Sets import org.aspectj.util.FileUtil import org.gradle.api.Project import java.io.File import java.nio.file.Files import java.nio.file.Path internal abstract class AspectJTransform(val project: Project, private val policy: BuildPolicy): Transform() { private lateinit var config: AndroidConfig private val aspectJWeaver: AspectJWeaver = AspectJWeaver(project) private val aspectJMerger: AspectJMergeJars = AspectJMergeJars() fun withConfig(config: AndroidConfig): AspectJTransform { this.config = config return this } open fun prepareProject(): AspectJTransform { project.afterEvaluate { getVariantDataList(config.plugin).forEach(::setupVariant) with(config.aspectj()) { aspectJWeaver.weaveInfo = weaveInfo aspectJWeaver.debugInfo = debugInfo aspectJWeaver.addSerialVUID = addSerialVersionUID aspectJWeaver.noInlineAround = noInlineAround aspectJWeaver.ignoreErrors = ignoreErrors aspectJWeaver.transformLogFile = transformLogFile aspectJWeaver.breakOnError = breakOnError aspectJWeaver.experimental = experimental aspectJWeaver.ajcArgs from ajcArgs } } return this } private fun <T: BaseVariantData> setupVariant(variantData: Pair<T, VariantPropertiesImpl>) { val javaTask = getJavaTask(variantData.first) getAjSourceAndExcludeFromJavac(project, variantData) aspectJWeaver.encoding = javaTask.options.encoding aspectJWeaver.sourceCompatibility = config.aspectj().java.toString() aspectJWeaver.targetCompatibility = config.aspectj().java.toString() } /* External API */ override fun getName(): String { return TRANSFORM_NAME } override fun getInputTypes(): Set<QualifiedContent.ContentType> { return Sets.immutableEnumSet(QualifiedContent.DefaultContentType.CLASSES) } override fun getOutputTypes(): Set<QualifiedContent.ContentType> { return TransformManager.CONTENT_CLASS } override fun getScopes(): MutableSet<in QualifiedContent.Scope> { return if (modeComplex()) TransformManager.SCOPE_FULL_PROJECT else Sets.immutableEnumSet(QualifiedContent.Scope.PROJECT) } override fun getReferencedScopes(): MutableSet<in QualifiedContent.Scope> { return if (modeComplex()) super.getReferencedScopes() else TransformManager.SCOPE_FULL_PROJECT } override fun isIncremental(): Boolean { return false } @Suppress("OverridingDeprecatedMember") override fun transform(context: Context, inputs: Collection<TransformInput>, referencedInputs: Collection<TransformInput>, outputProvider: TransformOutputProvider, isIncremental: Boolean) { transform(TransformInvocationBuilder(context) .addInputs(inputs) .addReferencedInputs(referencedInputs) .addOutputProvider(outputProvider) .setIncrementalMode(isIncremental).build()) } override fun transform(transformInvocation: TransformInvocation) { // bypassing transformer for non-test variant data in ConfigScope.JUNIT if (!verifyBypassInTestScope(transformInvocation.context)) { logBypassTransformation() return } val outputProvider = transformInvocation.outputProvider val includeJars = config.aspectj().includeJar val excludeJars = config.aspectj().excludeJar val includeAspects = config.aspectj().includeAspectsFromJar if (!transformInvocation.isIncremental) { outputProvider.deleteAll() } val outputDir = outputProvider.getContentLocation(TRANSFORM_NAME, outputTypes, scopes, Format.DIRECTORY) if (outputDir.isDirectory) FileUtils.deleteDirectoryContents(outputDir) FileUtils.mkdirs(outputDir) aspectJWeaver.destinationDir = outputDir.absolutePath aspectJWeaver.bootClasspath = config.getBootClasspath().joinToString(separator = File.pathSeparator) // clear weaver input, so each transformation can have its own configuration // (e.g. different build types / variants) // thanks to @philippkumar aspectJWeaver.inPath.clear() aspectJWeaver.aspectPath.clear() logAugmentationStart() // attaching source classes compiled by compile${variantName}AspectJ task includeCompiledAspects(transformInvocation, outputDir) val inputs = if (modeComplex()) transformInvocation.inputs else transformInvocation.referencedInputs inputs.forEach proceedInputs@ { input -> if (input.directoryInputs.isEmpty() && input.jarInputs.isEmpty()) return@proceedInputs //if no inputs so nothing to proceed input.directoryInputs.forEach { dir -> aspectJWeaver.inPath shl dir.file aspectJWeaver.classPath shl dir.file } input.jarInputs.forEach { jar -> aspectJWeaver.classPath shl jar.file if (modeComplex()) { val includeAllJars = config.aspectj().includeAllJars val includeFilterMatched = includeJars.isNotEmpty() && isIncludeFilterMatched(jar, includeJars) val excludeFilterMatched = excludeJars.isNotEmpty() && isExcludeFilterMatched(jar, excludeJars) if (excludeFilterMatched) { logJarInpathRemoved(jar) } if (!excludeFilterMatched && (includeAllJars || includeFilterMatched)) { logJarInpathAdded(jar) aspectJWeaver.inPath shl jar.file } else { copyJar(outputProvider, jar) } } else { if (includeJars.isNotEmpty() || excludeJars.isNotEmpty()) logIgnoreInpathJars() } val includeAspectsFilterMatched = includeAspects.isNotEmpty() && isIncludeFilterMatched(jar, includeAspects) if (includeAspectsFilterMatched) { logJarAspectAdded(jar) aspectJWeaver.aspectPath shl jar.file } } } val classpathFiles = aspectJWeaver.classPath.filter { it.isDirectory && !it.list().isNullOrEmpty() } val inpathFiles = aspectJWeaver.inPath.filter { it.isDirectory && !it.list().isNullOrEmpty() } if (inpathFiles.isEmpty() || classpathFiles.isEmpty()) { logNoAugmentation() return } aspectJWeaver.inPath shl outputDir logWeaverBuildPolicy(policy) aspectJWeaver.doWeave() if (modeComplex()) { aspectJMerger.doMerge(this, transformInvocation, outputDir) } copyUnprocessedFiles(inputs, outputDir) logAugmentationFinish() } private fun copyUnprocessedFiles(inputs: Collection<TransformInput>, outputDir: File) { inputs.forEach { input -> input.directoryInputs.forEach { dir -> copyUnprocessedFiles(dir.file.toPath(), outputDir.toPath()) } } } private fun copyUnprocessedFiles(inDir: Path, outDir: Path) { if (modeComplex()) { return } Files.walk(inDir).forEach traverse@ { inFile -> val outFile = outDir.resolve(inDir.relativize(inFile)) if (Files.exists(outFile)) return@traverse if (Files.isDirectory(outFile)) { Files.createDirectory(outFile) } else { Files.copy(inFile, outFile) } } } private fun modeComplex(): Boolean { return policy == BuildPolicy.COMPLEX } /* Internal */ private fun verifyBypassInTestScope(ctx: Context): Boolean { val variant = ctx.variantName return when (config.scope) { ConfigScope.JUNIT -> variant.contains("androidtest", true) else -> true } } private fun includeCompiledAspects(transformInvocation: TransformInvocation, outputDir: File) { val compiledAj = project.file("${project.buildDir}/$LANG_AJ/${transformInvocation.context.variantName}") if (compiledAj.exists()) { aspectJWeaver.aspectPath shl compiledAj //copy compiled .class files to output directory FileUtil.copyDir(compiledAj, outputDir) } } private fun copyJar(outputProvider: TransformOutputProvider, jarInput: JarInput?): Boolean { if (jarInput === null) { return false } var jarName = jarInput.name if (jarName.endsWith(".jar")) { jarName = jarName.substring(0, jarName.length - 4) } val dest: File = outputProvider.getContentLocation(jarName, jarInput.contentTypes, jarInput.scopes, Format.JAR) FileUtil.copyFile(jarInput.file, dest) return true } }
apache-2.0
3560c2a07414e6e5671894bd2705ddb2
36.888889
193
0.659521
4.805151
false
true
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepic/droid/ui/fragments/HomeFragment.kt
1
6043
package org.stepic.droid.ui.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import com.google.firebase.remoteconfig.FirebaseRemoteConfig import kotlinx.android.synthetic.main.fragment_home.* import kotlinx.android.synthetic.main.home_streak_view.* import kotlinx.android.synthetic.main.view_centered_toolbar.* import org.stepic.droid.R import org.stepic.droid.analytic.AmplitudeAnalytic import org.stepic.droid.base.App import org.stepic.droid.base.FragmentBase import org.stepic.droid.configuration.RemoteConfig import org.stepic.droid.core.presenters.HomeStreakPresenter import org.stepic.droid.core.presenters.contracts.HomeStreakView import org.stepic.droid.util.commitNow import org.stepik.android.domain.home.interactor.HomeInteractor import org.stepik.android.view.course_list.ui.fragment.CourseListPopularFragment import org.stepik.android.view.course_list.ui.fragment.CourseListUserHorizontalFragment import org.stepik.android.view.course_list.ui.fragment.CourseListVisitedHorizontalFragment import org.stepik.android.view.fast_continue.ui.fragment.FastContinueFragment import org.stepik.android.view.fast_continue.ui.fragment.FastContinueNewHomeFragment import org.stepik.android.view.learning_actions.ui.fragment.LearningActionsFragment import org.stepik.android.view.stories.ui.fragment.StoriesFragment import ru.nobird.android.stories.transition.SharedTransitionsManager import ru.nobird.android.stories.ui.delegate.SharedTransitionContainerDelegate import javax.inject.Inject class HomeFragment : FragmentBase(), HomeStreakView, FastContinueNewHomeFragment.Callback { companion object { const val TAG = "HomeFragment" const val HOME_DEEPLINK_STORY_KEY = "home_deeplink_story_key" fun newInstance(): HomeFragment = HomeFragment() private const val fastContinueTag = "fastContinueTag" } @Inject lateinit var homeStreakPresenter: HomeStreakPresenter @Inject lateinit var homeInteractor: HomeInteractor @Inject lateinit var remoteConfig: FirebaseRemoteConfig override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) analytic.reportAmplitudeEvent(AmplitudeAnalytic.Home.HOME_SCREEN_OPENED) } override fun injectComponent() { App.component() .homeComponentBuilder() .build() .inject(this) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_home, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { nullifyActivityBackground() super.onViewCreated(view, savedInstanceState) centeredToolbarTitle.setText(R.string.home_title) if (savedInstanceState == null) { setupFragments(remoteConfig.getBoolean(RemoteConfig.IS_NEW_HOME_SCREEN_ENABLED)) } appBarLayout.isVisible = !remoteConfig.getBoolean(RemoteConfig.IS_NEW_HOME_SCREEN_ENABLED) homeStreakPresenter.attachView(this) homeStreakPresenter.onNeedShowStreak() } override fun onStart() { super.onStart() if (remoteConfig.getBoolean(RemoteConfig.IS_NEW_HOME_SCREEN_ENABLED)) { SharedTransitionsManager.registerTransitionDelegate(HOME_DEEPLINK_STORY_KEY, object : SharedTransitionContainerDelegate { override fun getSharedView(position: Int): View? = storyDeepLinkMockView override fun onPositionChanged(position: Int) {} }) } } override fun onStop() { if (remoteConfig.getBoolean(RemoteConfig.IS_NEW_HOME_SCREEN_ENABLED)) { SharedTransitionsManager.unregisterTransitionDelegate(HOME_DEEPLINK_STORY_KEY) } super.onStop() } override fun onDestroyView() { homeStreakPresenter.detachView(this) super.onDestroyView() } override fun showStreak(streak: Int) { streakCounter.text = streak.toString() val daysPlural = resources.getQuantityString(R.plurals.day_number, streak) val days = "$streak $daysPlural" streakText.text = textResolver.fromHtml(getString(R.string.home_streak_counter_text, days)) homeStreak.isVisible = true } override fun onEmptyStreak() { homeStreak.isVisible = false } private fun setupFragments(isNewHomeScreenEnabled: Boolean) { if (isNewHomeScreenEnabled) { childFragmentManager.commitNow { add(R.id.homeMainContainer, StoriesFragment.newInstance()) add(R.id.homeMainContainer, CourseListUserHorizontalFragment.newInstance()) add(R.id.homeMainContainer, CourseListVisitedHorizontalFragment.newInstance()) add(R.id.homeMainContainer, CourseListPopularFragment.newInstance()) add(R.id.fastContinueContainer, FastContinueNewHomeFragment.newInstance()) } } else { childFragmentManager.commitNow { add(R.id.homeMainContainer, FastContinueFragment.newInstance(), fastContinueTag) add(R.id.homeMainContainer, CourseListUserHorizontalFragment.newInstance()) if (homeInteractor.isUserAuthorized()) { add(R.id.homeMainContainer, LearningActionsFragment.newInstance()) } add(R.id.homeMainContainer, CourseListVisitedHorizontalFragment.newInstance()) add(R.id.homeMainContainer, CourseListPopularFragment.newInstance()) } } } override fun onFastContinueLoaded(isVisible: Boolean) { val padding = if (isVisible) { resources.getDimensionPixelOffset(R.dimen.fast_continue_widget_height) } else { 0 } homeNestedScrollView.setPadding(0, 0, 0, padding) } }
apache-2.0
bc0a2c79c00d54512f653ece2a5a7915
39.557047
116
0.718186
4.695416
false
true
false
false
exponentjs/exponent
packages/expo-mail-composer/android/src/main/java/expo/modules/mailcomposer/MailIntentBuilder.kt
2
2437
package expo.modules.mailcomposer import android.app.Application import android.content.ComponentName import android.content.Intent import android.net.Uri import android.text.Html import android.util.Log import androidx.core.content.FileProvider import expo.modules.core.arguments.ReadableArguments import java.io.File class MailIntentBuilder( private val options: ReadableArguments ) { private val mailIntent = Intent(Intent.ACTION_SEND_MULTIPLE) @Suppress("UNCHECKED_CAST") private fun getStringArrayFrom(key: String): Array<String?> { return (options.getList(key) as List<String?>).toTypedArray() } private fun contentUriFromFile(file: File, application: Application): Uri = try { FileProvider.getUriForFile( application, application.packageName + ".MailComposerFileProvider", file ) } catch (e: Exception) { Uri.fromFile(file) } fun build() = mailIntent fun setComponentName(pkg: String, cls: String) = apply { mailIntent.component = ComponentName(pkg, cls) } fun putExtraIfKeyExists(key: String, intentName: String) = apply { if (options.containsKey(key)) { if (options.getList(key) != null) { mailIntent.putExtra(intentName, getStringArrayFrom(key)) } else { mailIntent.putExtra(intentName, options.getString(key)) } } } fun putExtraIfKeyExists(key: String, intentName: String, isBodyHtml: Boolean) = apply { if (options.containsKey(key)) { val body = if (isBodyHtml) { Html.fromHtml(options.getString(key)) } else { options.getString(key) } mailIntent.putExtra(intentName, body) } } fun putParcelableArrayListExtraIfKeyExists( key: String, intentName: String, application: Application, ) = apply { try { if (options.containsKey(key)) { val requestedAttachments = getStringArrayFrom(key) val attachments = requestedAttachments.map { requestedAttachment -> val path = Uri.parse(requestedAttachment).path requireNotNull(path, { "Path to attachment can not be null" }) val attachmentFile = File(path) contentUriFromFile(attachmentFile, application) }.toCollection(ArrayList()) mailIntent.putParcelableArrayListExtra(intentName, attachments) } } catch (error: IllegalArgumentException) { Log.e("ExpoMailComposer", "Illegal argument:", error) } } }
bsd-3-clause
851ec98ab1e10979812c7adee8d9702d
29.4625
89
0.695527
4.230903
false
false
false
false
realm/realm-java
realm/realm-annotations-processor/src/main/java/io/realm/processor/RealmVersionChecker.kt
1
3460
/* * Copyright 2019 Realm 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 io.realm.processor import java.io.BufferedReader import java.io.IOException import java.io.InputStreamReader import java.net.HttpURLConnection import java.net.URL import javax.annotation.processing.ProcessingEnvironment import javax.tools.Diagnostic class RealmVersionChecker private constructor(private val processingEnvironment: ProcessingEnvironment) { private val REALM_ANDROID_DOWNLOAD_URL = "https://static.realm.io/downloads/java/latest" private val VERSION_URL = "https://static.realm.io/update/java?" private val REALM_VERSION = Version.VERSION private val REALM_VERSION_PATTERN = "\\d+\\.\\d+\\.\\d+" private val READ_TIMEOUT = 2000 private val CONNECT_TIMEOUT = 4000 fun executeRealmVersionUpdate() { val backgroundThread = Thread(Runnable { launchRealmCheck() }) backgroundThread.start() try { backgroundThread.join((CONNECT_TIMEOUT + READ_TIMEOUT).toLong()) } catch (ignore: InterruptedException) { // We ignore this exception on purpose not to break the build system if this class fails } } private fun launchRealmCheck() { //Check Realm version server val latestVersionStr = checkLatestVersion() if (latestVersionStr != REALM_VERSION) { printMessage("Version $latestVersionStr of Realm is now available: $REALM_ANDROID_DOWNLOAD_URL") } } private fun checkLatestVersion(): String { var result = REALM_VERSION try { val url = URL(VERSION_URL + REALM_VERSION) val conn = url.openConnection() as HttpURLConnection conn.connectTimeout = CONNECT_TIMEOUT conn.readTimeout = READ_TIMEOUT val rd = BufferedReader(InputStreamReader(conn.inputStream)) val latestVersion = rd.readLine() // if the obtained string does not match the pattern, we are in a separate network. if (latestVersion.matches(REALM_VERSION_PATTERN.toRegex())) { result = latestVersion } rd.close() } catch (e: IOException) { // We ignore this exception on purpose not to break the build system if this class fails } return result } private fun printMessage(message: String) { processingEnvironment.messager.printMessage(Diagnostic.Kind.OTHER, message) } companion object { private var instance: RealmVersionChecker? = null fun getInstance(env: ProcessingEnvironment): RealmVersionChecker { if (instance == null) { synchronized(RealmVersionChecker::class.java) { if (instance == null) { instance = RealmVersionChecker(env) } } } return instance!! } } }
apache-2.0
99482dde3b3eddfa37b180d67b17fab5
35.808511
108
0.657225
4.873239
false
true
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/workers/reminder/ReminderScheduler.kt
1
2346
package org.wordpress.android.workers.reminder import androidx.work.Data import androidx.work.ExistingWorkPolicy.REPLACE import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkManager import org.wordpress.android.viewmodel.ContextProvider import java.time.Duration import java.time.LocalDateTime import java.time.LocalTime import java.util.UUID import java.util.concurrent.TimeUnit.MILLISECONDS import javax.inject.Inject class ReminderScheduler @Inject constructor( val contextProvider: ContextProvider ) { val workManager by lazy { WorkManager.getInstance(contextProvider.getContext()) } fun schedule(siteId: Int, hour: Int, minute: Int, reminderConfig: ReminderConfig) { val uniqueName = getUniqueName(siteId) val next = reminderConfig.calculateNext().atTime(LocalTime.of(hour, minute)) val delay = Duration.between(LocalDateTime.now(), next) val inputData = Data.Builder() .putInt(REMINDER_SITE_ID, siteId) .putInt(REMINDER_HOUR, hour) .putInt(REMINDER_MINUTE, minute) .putAll(reminderConfig.toMap()) .build() val workRequest = OneTimeWorkRequestBuilder<ReminderWorker>() .addTag(REMINDER_TAG) .setInitialDelay(delay.toMillis(), MILLISECONDS) .setInputData(inputData) .build() workManager.enqueueUniqueWork(uniqueName, REPLACE, workRequest) } fun cancelById(id: UUID) = workManager.cancelWorkById(id) fun cancelBySiteId(siteId: Int) = workManager.cancelUniqueWork(getUniqueName(siteId)) fun cancelAll() = workManager.cancelAllWorkByTag(REMINDER_TAG) fun getById(id: UUID) = workManager.getWorkInfoByIdLiveData(id) fun getBySiteId(siteId: Int) = workManager.getWorkInfosForUniqueWorkLiveData(getUniqueName(siteId)) fun getAll() = workManager.getWorkInfosByTagLiveData(REMINDER_TAG) private fun getUniqueName(siteId: Int) = "${REMINDER_TAG}_$siteId" companion object { private const val REMINDER_TAG = "reminder" const val REMINDER_SITE_ID = "reminder_site_id" const val DEFAUlT_START_HOUR = 10 const val DEFAULT_START_MINUTE = 0 const val REMINDER_HOUR = "reminder_hour" const val REMINDER_MINUTE = "reminder_minute" } }
gpl-2.0
6ab0912cebd80d0aedb6bfaff421fa14
36.83871
103
0.708014
4.564202
false
true
false
false
mdaniel/intellij-community
plugins/kotlin/jvm-debugger/core-fe10/src/org/jetbrains/kotlin/idea/debugger/stepping/smartStepInto/KotlinLambdaAsyncMethodFilter.kt
1
4645
// 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.debugger.stepping.smartStepInto import com.intellij.debugger.SourcePosition import com.intellij.debugger.engine.DebugProcessImpl import com.intellij.debugger.engine.RequestHint import com.intellij.debugger.engine.SuspendContextImpl import com.intellij.debugger.engine.evaluation.EvaluateException import com.intellij.debugger.engine.evaluation.EvaluationContextImpl import com.intellij.debugger.jdi.StackFrameProxyImpl import com.intellij.debugger.ui.breakpoints.StepIntoBreakpoint import com.intellij.openapi.project.Project import com.intellij.util.Range import com.sun.jdi.Location import com.sun.jdi.Method import com.sun.jdi.ObjectReference import com.sun.jdi.ReferenceType import com.sun.jdi.event.LocatableEvent import org.jetbrains.kotlin.idea.debugger.DebuggerUtils.isGeneratedIrBackendLambdaMethodName import org.jetbrains.kotlin.idea.debugger.base.util.safeAllLineLocations import org.jetbrains.kotlin.idea.debugger.base.util.safeMethod import org.jetbrains.kotlin.idea.debugger.base.util.safeThisObject import org.jetbrains.kotlin.psi.KtDeclaration class KotlinLambdaAsyncMethodFilter( declaration: KtDeclaration?, callingExpressionLines: Range<Int>?, private val lambdaInfo: KotlinLambdaInfo, private val lambdaFilter: KotlinLambdaMethodFilter ) : KotlinMethodFilter(declaration, callingExpressionLines, lambdaInfo.callerMethodInfo) { private var visitedLocations = 0 override fun locationMatches(process: DebugProcessImpl, location: Location?, frameProxy: StackFrameProxyImpl?): Boolean { if (frameProxy == null || !super.locationMatches(process, location, frameProxy)) { return false } visitedLocations++ val lambdaReference = frameProxy.getLambdaReference() ?: return false val lambdaMethod = lambdaReference.referenceType().getLambdaMethod() ?: return false val locationInLambda = lambdaMethod.safeAllLineLocations().firstOrNull() // We failed to get the location inside lambda (it can happen for SAM conversions in IR backend). // So we fall back to ordinal check. if (locationInLambda == null) { return visitedLocations == lambdaInfo.callerMethodOrdinal } return lambdaFilter.locationMatches(process, locationInLambda) } private fun ReferenceType.getLambdaMethod(): Method? = methods().firstOrNull { it.isPublic && !it.isBridge } override fun onReached(context: SuspendContextImpl, hint: RequestHint?): Int { try { val breakpoint = createBreakpoint(context) if (breakpoint != null) { DebugProcessImpl.prepareAndSetSteppingBreakpoint(context, breakpoint, hint, true) return RequestHint.RESUME } } catch (ignored: EvaluateException) { } return RequestHint.STOP } private fun createBreakpoint(context: SuspendContextImpl): KotlinLambdaInstanceBreakpoint? { val lambdaReference = context.frameProxy?.getLambdaReference() ?: return null val position = lambdaFilter.breakpointPosition ?: return null return KotlinLambdaInstanceBreakpoint( context.debugProcess.project, position, lambdaReference.uniqueID(), lambdaFilter ) } private fun StackFrameProxyImpl.getLambdaReference(): ObjectReference? = argumentValues.getOrNull(lambdaInfo.parameterIndex) as? ObjectReference private class KotlinLambdaInstanceBreakpoint( project: Project, pos: SourcePosition, private val lambdaId: Long, private val lambdaFilter: KotlinLambdaMethodFilter ) : StepIntoBreakpoint(project, pos, lambdaFilter) { override fun evaluateCondition(context: EvaluationContextImpl, event: LocatableEvent): Boolean { if (!super.evaluateCondition(context, event)) { return false } val thread = context.suspendContext.thread ?: return false val methodName = event.location().safeMethod()?.name() ?: return false if (!lambdaFilter.isTargetLambdaName(methodName)) { return false } val frameIndex = if (methodName.isGeneratedIrBackendLambdaMethodName()) 1 else 0 val lambdaReference = thread.frame(frameIndex).safeThisObject() return lambdaReference != null && lambdaReference.uniqueID() == lambdaId } } }
apache-2.0
0cce4c5a89e44864919efffd1a1d8675
44.539216
158
0.725727
5.121279
false
false
false
false
mdaniel/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/extensions/jcef/commandRunner/CommandRunnerExtension.kt
1
14577
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.extensions.jcef.commandRunner import com.intellij.execution.Executor import com.intellij.execution.ExecutorRegistry import com.intellij.execution.executors.DefaultRunExecutor import com.intellij.icons.AllIcons import com.intellij.ide.actions.runAnything.RunAnythingAction import com.intellij.ide.actions.runAnything.RunAnythingContext import com.intellij.ide.actions.runAnything.RunAnythingRunConfigurationProvider import com.intellij.ide.actions.runAnything.activity.RunAnythingCommandProvider import com.intellij.ide.actions.runAnything.activity.RunAnythingProvider import com.intellij.ide.actions.runAnything.activity.RunAnythingRecentProjectProvider import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.impl.SimpleDataContext import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.invokeLater import com.intellij.openapi.application.runReadAction import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.fileEditor.TextEditorWithPreview import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.AppUIUtil import org.intellij.plugins.markdown.MarkdownBundle import org.intellij.plugins.markdown.MarkdownUsageCollector.Companion.RUNNER_EXECUTED import org.intellij.plugins.markdown.extensions.MarkdownBrowserPreviewExtension import org.intellij.plugins.markdown.extensions.MarkdownExtensionsUtil import org.intellij.plugins.markdown.fileActions.utils.MarkdownFileEditorUtils import org.intellij.plugins.markdown.injection.aliases.CodeFenceLanguageGuesser import org.intellij.plugins.markdown.settings.MarkdownExtensionsSettings import org.intellij.plugins.markdown.ui.preview.MarkdownEditorWithPreview import org.intellij.plugins.markdown.ui.preview.MarkdownHtmlPanel import org.intellij.plugins.markdown.ui.preview.PreviewStaticServer import org.intellij.plugins.markdown.ui.preview.ResourceProvider import org.intellij.plugins.markdown.ui.preview.html.MarkdownUtil import java.util.concurrent.ConcurrentHashMap internal class CommandRunnerExtension(val panel: MarkdownHtmlPanel, private val provider: Provider) : MarkdownBrowserPreviewExtension, ResourceProvider, MarkdownEditorWithPreview.SplitLayoutListener { override val scripts: List<String> = listOf("commandRunner/commandRunner.js") override val styles: List<String> = listOf("commandRunner/commandRunner.css") private val hash2Cmd = mutableMapOf<String, String>() private var splitEditor: MarkdownEditorWithPreview? = null init { panel.browserPipe?.subscribe(RUN_LINE_EVENT, this::runLine) panel.browserPipe?.subscribe(RUN_BLOCK_EVENT, this::runBlock) panel.browserPipe?.subscribe(PAGE_READY_EVENT, this::onPageReady) invokeLater { MarkdownFileEditorUtils.findMarkdownSplitEditor(panel.project!!, panel.virtualFile!!)?.let { splitEditor = it it.addLayoutListener(this) } } Disposer.register(this) { panel.browserPipe?.removeSubscription(RUN_LINE_EVENT, ::runLine) panel.browserPipe?.removeSubscription(RUN_BLOCK_EVENT, ::runBlock) splitEditor?.removeLayoutListener(this) } } override fun onLayoutChange(oldLayout: TextEditorWithPreview.Layout?, newLayout: TextEditorWithPreview.Layout) { panel.browserPipe?.send(LAYOUT_CHANGE_EVENT, newLayout.name) } private fun onPageReady(ready: String) { splitEditor?.let { panel.browserPipe?.send(LAYOUT_CHANGE_EVENT, it.layout.name) } } override val resourceProvider: ResourceProvider = this override fun canProvide(resourceName: String): Boolean = resourceName in scripts || resourceName in styles override fun loadResource(resourceName: String): ResourceProvider.Resource? { return ResourceProvider.loadInternalResource(this::class, resourceName) } fun processCodeLine(rawCodeLine: String, insideFence: Boolean): String { processLine(rawCodeLine, !insideFence)?.let { hash -> return getHtmlForLineRunner(insideFence, hash) } return "" } private fun processLine(rawCodeLine: String, allowRunConfigurations: Boolean): String? { try { val project = panel.project val file = panel.virtualFile if (project != null && file != null && file.parent != null && matches(project, file.parent.canonicalPath, true, rawCodeLine.trim(), allowRunConfigurations) ) { val hash = MarkdownUtil.md5(rawCodeLine, "") hash2Cmd[hash] = rawCodeLine return hash } else return null } catch (e: Exception) { LOG.warn(e) return null } } private fun getHtmlForLineRunner(insideFence: Boolean, hash: String): String { val cssClass = "run-icon hidden" + if (insideFence) " code-block" else "" return "<a class='${cssClass}' href='#' role='button' data-command='${DefaultRunExecutor.EXECUTOR_ID}:$hash'>" + "<img src='${PreviewStaticServer.getStaticUrl(provider, RUN_LINE_ICON)}'>" + "</a>" } fun processCodeBlock(codeFenceRawContent: String, language: String): String { try { val lang = CodeFenceLanguageGuesser.guessLanguageForInjection(language) val runner = MarkdownRunner.EP_NAME.extensionList.firstOrNull { it.isApplicable(lang) } if (runner == null) return "" val hash = MarkdownUtil.md5(codeFenceRawContent, "") hash2Cmd[hash] = codeFenceRawContent val lines = codeFenceRawContent.trimEnd().lines() val firstLineHash = if (lines.size > 1) processLine(lines[0], false) else null val firstLineData = if (firstLineHash.isNullOrBlank()) "" else "data-firstLine='$firstLineHash'" val cssClass = "run-icon hidden code-block" return "<a class='${cssClass}' href='#' role='button' " + "data-command='${DefaultRunExecutor.EXECUTOR_ID}:$hash' " + "data-commandtype='block'" + firstLineData + ">" + "<img src='${PreviewStaticServer.getStaticUrl(provider, RUN_BLOCK_ICON)}'>" + "</a>" } catch (e: Exception) { LOG.warn(e) return "" } } private fun runLine(encodedLine: String) { val executorId = encodedLine.substringBefore(":") val cmdHash: String = encodedLine.substringAfter(":") val command = hash2Cmd[cmdHash] if (command == null) { LOG.error("Command index $cmdHash not found. Please attach .md file to error report. commandCache = ${hash2Cmd}") return } executeLineCommand(command, executorId) } private fun executeLineCommand(command: String, executorId: String) { val executor = ExecutorRegistry.getInstance().getExecutorById(executorId) ?: DefaultRunExecutor.getRunExecutorInstance() val project = panel.project val virtualFile = panel.virtualFile if (project != null && virtualFile != null) { execute(project, virtualFile.parent.canonicalPath, true, command, executor, RunnerPlace.PREVIEW) } } private fun executeBlock(command: String, executorId: String) { val runner = MarkdownRunner.EP_NAME.extensionList.first() val executor = ExecutorRegistry.getInstance().getExecutorById(executorId) ?: DefaultRunExecutor.getRunExecutorInstance() val project = panel.project val virtualFile = panel.virtualFile if (project != null && virtualFile != null) { TrustedProjectUtil.executeIfTrusted(project) { RUNNER_EXECUTED.log(project, RunnerPlace.PREVIEW, RunnerType.BLOCK, runner.javaClass) invokeLater { runner.run(command, project, virtualFile.parent.canonicalPath, executor) } } } } private fun runBlock(encodedLine: String) { val args = encodedLine.split(":") val executorId = args[0] val cmdHash: String = args[1] val command = hash2Cmd[cmdHash] val firstLineCommand = hash2Cmd[args[2]] if (command == null) { LOG.error("Command hash $cmdHash not found. Please attach .md file to error report.\n${hash2Cmd}") return } val trimmedCmd = trimPrompt(command) if (firstLineCommand == null) { ApplicationManager.getApplication().invokeLater { executeBlock(trimmedCmd, executorId) } return } val x = args[3].toInt() val y = args[4].toInt() val actionManager = ActionManager.getInstance() val actionGroup = DefaultActionGroup() val runBlockAction = object : AnAction({ MarkdownBundle.message("markdown.runner.launch.block") }, AllIcons.RunConfigurations.TestState.Run_run) { override fun actionPerformed(e: AnActionEvent) { ApplicationManager.getApplication().invokeLater { executeBlock(trimmedCmd, executorId) } } } val runLineAction = object : AnAction({ MarkdownBundle.message("markdown.runner.launch.line") }, AllIcons.RunConfigurations.TestState.Run) { override fun actionPerformed(e: AnActionEvent) { ApplicationManager.getApplication().invokeLater { executeLineCommand(firstLineCommand, executorId) } } } actionGroup.add(runBlockAction) actionGroup.add(runLineAction) AppUIUtil.invokeOnEdt { actionManager.createActionPopupMenu(ActionPlaces.EDITOR_GUTTER_POPUP, actionGroup) .component.show(panel.component, x, y) } } override fun dispose() { provider.extensions.remove(panel.virtualFile) } class Provider: MarkdownBrowserPreviewExtension.Provider, ResourceProvider { val extensions = ConcurrentHashMap<VirtualFile, CommandRunnerExtension>() init { PreviewStaticServer.instance.registerResourceProvider(this) } override fun createBrowserExtension(panel: MarkdownHtmlPanel): MarkdownBrowserPreviewExtension? { val virtualFile = panel.virtualFile ?: return null if (!isExtensionEnabled()) { return null } return extensions.computeIfAbsent(virtualFile) { CommandRunnerExtension(panel, this) } } val icons: List<String> = listOf(RUN_LINE_ICON, RUN_BLOCK_ICON) override fun canProvide(resourceName: String): Boolean { return resourceName in icons } override fun loadResource(resourceName: String): ResourceProvider.Resource? { val icon = when (resourceName) { RUN_LINE_ICON -> AllIcons.RunConfigurations.TestState.Run RUN_BLOCK_ICON -> AllIcons.RunConfigurations.TestState.Run_run else -> return null } val format = resourceName.substringAfterLast(".") return ResourceProvider.Resource(MarkdownExtensionsUtil.loadIcon(icon, format)) } } companion object { private const val RUN_LINE_EVENT = "runLine" private const val RUN_BLOCK_EVENT = "runBlock" private const val PAGE_READY_EVENT = "pageReady" private const val LAYOUT_CHANGE_EVENT = "layoutChange" private const val RUN_LINE_ICON = "run.png" private const val RUN_BLOCK_ICON = "runrun.png" const val extensionId = "MarkdownCommandRunnerExtension" fun isExtensionEnabled(): Boolean { return MarkdownExtensionsSettings.getInstance().extensionsEnabledState[extensionId] ?: true } fun getRunnerByFile(file: VirtualFile) : CommandRunnerExtension? { val provider = MarkdownExtensionsUtil.findBrowserExtensionProvider<Provider>() return provider?.extensions?.get(file) } fun matches(project: Project, workingDirectory: String?, localSession: Boolean, command: String, allowRunConfigurations: Boolean = false): Boolean { val trimmedCmd = command.trim() if (trimmedCmd.isEmpty()) return false val dataContext = createDataContext(project, localSession, workingDirectory) return runReadAction { RunAnythingProvider.EP_NAME.extensionList.asSequence() .filter { checkForCLI(it, allowRunConfigurations) } .any { provider -> provider.findMatchingValue(dataContext, trimmedCmd) != null } } } fun execute( project: Project, workingDirectory: String?, localSession: Boolean, command: String, executor: Executor, place: RunnerPlace ): Boolean { val dataContext = createDataContext(project, localSession, workingDirectory, executor) val trimmedCmd = command.trim() return runReadAction { for (provider in RunAnythingProvider.EP_NAME.extensionList) { val value = provider.findMatchingValue(dataContext, trimmedCmd) ?: continue return@runReadAction TrustedProjectUtil.executeIfTrusted(project) { RUNNER_EXECUTED.log(project, place, RunnerType.LINE, provider.javaClass) invokeLater { provider.execute(dataContext, value) } } } return@runReadAction false } } private fun createDataContext(project: Project, localSession: Boolean, workingDirectory: String?, executor: Executor? = null): DataContext { val virtualFile = if (localSession && workingDirectory != null) LocalFileSystem.getInstance().findFileByPath(workingDirectory) else null return SimpleDataContext.builder() .add(CommonDataKeys.PROJECT, project) .add(RunAnythingAction.EXECUTOR_KEY, executor) .apply { if (virtualFile != null) { add(CommonDataKeys.VIRTUAL_FILE, virtualFile) add(RunAnythingProvider.EXECUTING_CONTEXT, RunAnythingContext.RecentDirectoryContext(virtualFile.path)) } } .build() } private fun checkForCLI(it: RunAnythingProvider<*>?, allowRunConfigurations: Boolean): Boolean { return (it !is RunAnythingCommandProvider && it !is RunAnythingRecentProjectProvider && (it !is RunAnythingRunConfigurationProvider || allowRunConfigurations)) } private val LOG = logger<CommandRunnerExtension>() internal fun trimPrompt(cmd: String): String { return cmd.lines() .filter { line -> line.isNotEmpty() } .joinToString("\n") { line -> if (line.startsWith("$")) line.substringAfter("$") else line } } } } enum class RunnerPlace { EDITOR, PREVIEW } enum class RunnerType { BLOCK, LINE }
apache-2.0
a57f85d17037168d4611db564b4ee34c
38.61413
158
0.71064
4.903128
false
false
false
false
ingokegel/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/OoParentEntityImpl.kt
1
10358
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToOneChild import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class OoParentEntityImpl : OoParentEntity, WorkspaceEntityBase() { companion object { internal val CHILD_CONNECTION_ID: ConnectionId = ConnectionId.create(OoParentEntity::class.java, OoChildEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false) internal val ANOTHERCHILD_CONNECTION_ID: ConnectionId = ConnectionId.create(OoParentEntity::class.java, OoChildWithNullableParentEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, true) val connections = listOf<ConnectionId>( CHILD_CONNECTION_ID, ANOTHERCHILD_CONNECTION_ID, ) } @JvmField var _parentProperty: String? = null override val parentProperty: String get() = _parentProperty!! override val child: OoChildEntity? get() = snapshot.extractOneToOneChild(CHILD_CONNECTION_ID, this) override val anotherChild: OoChildWithNullableParentEntity? get() = snapshot.extractOneToOneChild(ANOTHERCHILD_CONNECTION_ID, this) override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: OoParentEntityData?) : ModifiableWorkspaceEntityBase<OoParentEntity>(), OoParentEntity.Builder { constructor() : this(OoParentEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity OoParentEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isParentPropertyInitialized()) { error("Field OoParentEntity#parentProperty should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as OoParentEntity this.entitySource = dataSource.entitySource this.parentProperty = dataSource.parentProperty if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var parentProperty: String get() = getEntityData().parentProperty set(value) { checkModificationAllowed() getEntityData().parentProperty = value changedProperty.add("parentProperty") } override var child: OoChildEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToOneChild(CHILD_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] as? OoChildEntity } else { this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] as? OoChildEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, CHILD_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToOneChildOfParent(CHILD_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, CHILD_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] = value } changedProperty.add("child") } override var anotherChild: OoChildWithNullableParentEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToOneChild(ANOTHERCHILD_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, ANOTHERCHILD_CONNECTION_ID)] as? OoChildWithNullableParentEntity } else { this.entityLinks[EntityLink(true, ANOTHERCHILD_CONNECTION_ID)] as? OoChildWithNullableParentEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, ANOTHERCHILD_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToOneChildOfParent(ANOTHERCHILD_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(false, ANOTHERCHILD_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(true, ANOTHERCHILD_CONNECTION_ID)] = value } changedProperty.add("anotherChild") } override fun getEntityData(): OoParentEntityData = result ?: super.getEntityData() as OoParentEntityData override fun getEntityClass(): Class<OoParentEntity> = OoParentEntity::class.java } } class OoParentEntityData : WorkspaceEntityData<OoParentEntity>() { lateinit var parentProperty: String fun isParentPropertyInitialized(): Boolean = ::parentProperty.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<OoParentEntity> { val modifiable = OoParentEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): OoParentEntity { val entity = OoParentEntityImpl() entity._parentProperty = parentProperty entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return OoParentEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return OoParentEntity(parentProperty, entitySource) { } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as OoParentEntityData if (this.entitySource != other.entitySource) return false if (this.parentProperty != other.parentProperty) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as OoParentEntityData if (this.parentProperty != other.parentProperty) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + parentProperty.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + parentProperty.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
20d28679f5a2e4984550bdb9b15ab962
36.258993
166
0.686233
5.333677
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/repeatingquest/entity/RepeatPattern.kt
1
18898
package io.ipoli.android.repeatingquest.entity import io.ipoli.android.common.datetime.* import org.threeten.bp.DayOfWeek import org.threeten.bp.LocalDate import org.threeten.bp.Month import org.threeten.bp.temporal.TemporalAdjusters /** * Created by Venelin Valkov <[email protected]> * on 02/14/2018. */ sealed class RepeatPattern { abstract val startDate: LocalDate abstract val endDate: LocalDate? abstract val lastScheduledPeriodStart: LocalDate? abstract val skipEveryXPeriods: Int val doEveryXPeriods get() = skipEveryXPeriods + 1 abstract val countInPeriod: Int abstract fun periodRangeFor(date: LocalDate): PeriodRange abstract fun createPlaceholderDates( startDate: LocalDate, endDate: LocalDate, skipScheduled: Boolean ): List<LocalDate> fun createSchedule( currentDate: LocalDate, lastDate: LocalDate? ): Schedule { val s = doCreateSchedule(currentDate) return s.copy( dates = s.dates.filter { date -> lastDate?.let { date.isBeforeOrEqual(lastDate) } ?: true }, newRepeatPattern = s.newRepeatPattern ) } abstract fun doCreateSchedule( currentDate: LocalDate ): Schedule data class Schedule(val dates: List<LocalDate>, val newRepeatPattern: RepeatPattern) data class Daily( override val startDate: LocalDate = LocalDate.now(), override val endDate: LocalDate? = null, override val lastScheduledPeriodStart: LocalDate? = null, override val skipEveryXPeriods: Int = 0 ) : RepeatPattern() { override val countInPeriod get() = DayOfWeek.values().size override fun createPlaceholderDates( startDate: LocalDate, endDate: LocalDate, skipScheduled: Boolean ): List<LocalDate> { var periodStart = periodRangeFor(startDate).start if (skipScheduled) { lastScheduledPeriodStart?.let { while (periodStart.isBeforeOrEqual(lastScheduledPeriodStart)) { periodStart = periodStart.plusWeeks(1) } } } if (periodStart.isBefore(startDate)) { periodStart = startDate } return periodStart.datesBetween(endDate).filter { it.isAfterOrEqual(startDate) && it.isBeforeOrEqual(endDate) && shouldDoOn(it) } } override fun periodRangeFor(date: LocalDate) = PeriodRange( start = date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)), end = date.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY)) ) private fun shouldDoOn(date: LocalDate): Boolean { if (doEveryXPeriods == 1) return true return startDate.daysUntil(date) % doEveryXPeriods == 0L } override fun doCreateSchedule(currentDate: LocalDate): Schedule { val nextMonday = currentDate.plusWeeks(1).with( TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY) ) return Schedule( dates = datesForPeriod(currentDate) + datesForPeriod(nextMonday), newRepeatPattern = copy( lastScheduledPeriodStart = nextMonday ) ) } private fun datesForPeriod( startDateForPeriod: LocalDate ): List<LocalDate> { val period = periodRangeFor(startDateForPeriod) if (lastScheduledPeriodStart != null && period.start.isBeforeOrEqual( lastScheduledPeriodStart ) ) { return emptyList() } return startDateForPeriod.datesBetween(period.end).filter { shouldDoOn(it) } } } data class Yearly( val dayOfMonth: Int, val month: Month, override val startDate: LocalDate = LocalDate.now(), override val endDate: LocalDate? = null, override val lastScheduledPeriodStart: LocalDate? = null ) : RepeatPattern() { override val countInPeriod = 1 override val skipEveryXPeriods: Int = 0 override fun createPlaceholderDates( startDate: LocalDate, endDate: LocalDate, skipScheduled: Boolean ): List<LocalDate> { var periodStart = periodRangeFor(startDate).start if (skipScheduled) { lastScheduledPeriodStart?.let { while (periodStart.isBeforeOrEqual(lastScheduledPeriodStart)) { periodStart = periodStart.plusYears(1) } } } if (periodStart.isBefore(startDate)) { periodStart = startDate } val dates = mutableListOf<LocalDate>() while (periodStart.isBeforeOrEqual(endDate)) { val date = LocalDate.of(periodStart.year, month, dayOfMonth) dates.add(date) periodStart = periodStart.plusYears(1) } return dates.filter { it.isAfterOrEqual(startDate) && it.isBeforeOrEqual(endDate) } } override fun periodRangeFor(date: LocalDate) = PeriodRange( start = date.with(TemporalAdjusters.firstDayOfYear()), end = date.with(TemporalAdjusters.lastDayOfYear()) ) override fun doCreateSchedule(currentDate: LocalDate): Schedule { val firstOfNextYear = currentDate.plusYears(1) return Schedule( dates = datesForPeriod(currentDate) + datesForPeriod(firstOfNextYear), newRepeatPattern = copy(lastScheduledPeriodStart = firstOfNextYear) ) } private fun datesForPeriod( dateInPeriod: LocalDate ): List<LocalDate> { val period = periodRangeFor(dateInPeriod) if (lastScheduledPeriodStart != null && period.start.isBeforeOrEqual( lastScheduledPeriodStart ) ) { return emptyList() } return listOf(LocalDate.of(dateInPeriod.year, month, dayOfMonth)) } } data class Weekly( val daysOfWeek: Set<DayOfWeek>, override val startDate: LocalDate = LocalDate.now(), override val endDate: LocalDate? = null, override val lastScheduledPeriodStart: LocalDate? = null, override val skipEveryXPeriods: Int = 0 ) : RepeatPattern() { override val countInPeriod get() = daysOfWeek.size override fun createPlaceholderDates( startDate: LocalDate, endDate: LocalDate, skipScheduled: Boolean ): List<LocalDate> { var periodStart = periodRangeFor(startDate).start if (skipScheduled) { lastScheduledPeriodStart?.let { while (periodStart.isBeforeOrEqual(lastScheduledPeriodStart)) { periodStart = periodStart.plusWeeks(1) } } } if (periodStart.isBefore(startDate)) { periodStart = startDate } val repeatStart = periodRangeFor(this.startDate).start return periodStart.datesBetween(endDate).filter { val weeksPassed = repeatStart.weeksUntil(periodRangeFor(it).start) val shouldDoOnWeek = weeksPassed % doEveryXPeriods == 0L it.isAfterOrEqual(startDate) && it.isBeforeOrEqual(endDate) && shouldDoOnWeek && shouldDoOn(it) } } override fun periodRangeFor(date: LocalDate) = PeriodRange( start = date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)), end = date.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY)) ) override fun doCreateSchedule(currentDate: LocalDate): Schedule { val nextMonday = currentDate.plusWeeks(1).with( TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY) ) return Schedule( dates = datesForPeriod(currentDate) + datesForPeriod(nextMonday), newRepeatPattern = copy(lastScheduledPeriodStart = nextMonday) ) } private fun shouldDoOn(date: LocalDate) = daysOfWeek.contains(date.dayOfWeek) private fun datesForPeriod(startDateForPeriod: LocalDate): List<LocalDate> { val period = periodRangeFor(startDateForPeriod) val weeksPassed = periodRangeFor(startDate).start.weeksUntil(startDateForPeriod) val shouldDoOnWeek = weeksPassed % doEveryXPeriods == 0L if (!shouldDoOnWeek || (lastScheduledPeriodStart != null && period.start.isBeforeOrEqual(lastScheduledPeriodStart)) ) { return emptyList() } return startDateForPeriod.datesBetween(period.end) .filter { shouldDoOn(it) } } } data class Monthly( val daysOfMonth: Set<Int>, override val startDate: LocalDate = LocalDate.now(), override val endDate: LocalDate? = null, override val lastScheduledPeriodStart: LocalDate? = null, override val skipEveryXPeriods: Int = 0 ) : RepeatPattern() { override val countInPeriod get() = daysOfMonth.size override fun createPlaceholderDates( startDate: LocalDate, endDate: LocalDate, skipScheduled: Boolean ): List<LocalDate> { var periodStart = periodRangeFor(startDate).start if (skipScheduled) { lastScheduledPeriodStart?.let { while (periodStart.isBeforeOrEqual(lastScheduledPeriodStart)) { periodStart = periodStart.plusMonths(1) } } } if (periodStart.isBefore(startDate)) { periodStart = startDate } val repeatStart = periodRangeFor(this.startDate).start return periodStart.datesBetween(endDate).filter { val monthsPassed = repeatStart.monthsUntil(periodRangeFor(it).start) val shouldDoOnMonth = monthsPassed % doEveryXPeriods == 0L it.isAfterOrEqual(startDate) && it.isBeforeOrEqual(endDate) && shouldDoOnMonth && shouldDoOn(it) } } override fun periodRangeFor(date: LocalDate) = PeriodRange( start = date.with(TemporalAdjusters.firstDayOfMonth()), end = date.with(TemporalAdjusters.lastDayOfMonth()) ) override fun doCreateSchedule(currentDate: LocalDate): Schedule { val nextFirstDayOfMonth = currentDate.plusMonths(1).with( TemporalAdjusters.firstDayOfMonth() ) return Schedule( dates = datesForPeriod(currentDate) + datesForPeriod(nextFirstDayOfMonth), newRepeatPattern = copy(lastScheduledPeriodStart = nextFirstDayOfMonth) ) } private fun shouldDoOn(date: LocalDate) = daysOfMonth.contains(date.dayOfMonth) private fun datesForPeriod(startDateForPeriod: LocalDate): List<LocalDate> { val period = periodRangeFor(startDateForPeriod) val monthsPassed = periodRangeFor(startDate).start.monthsUntil(startDateForPeriod) val shouldDoOnMonth = monthsPassed % doEveryXPeriods == 0L if (!shouldDoOnMonth || (lastScheduledPeriodStart != null && period.start.isBeforeOrEqual(lastScheduledPeriodStart)) ) { return emptyList() } return startDateForPeriod.datesBetween(period.end) .filter { shouldDoOn(it) } } } sealed class Flexible : RepeatPattern() { data class Weekly( val timesPerWeek: Int, val preferredDays: Set<DayOfWeek> = DayOfWeek.values().toSet(), override val startDate: LocalDate = LocalDate.now(), override val endDate: LocalDate? = null, override val lastScheduledPeriodStart: LocalDate? = null, override val skipEveryXPeriods: Int = 0 ) : Flexible() { override val countInPeriod get() = timesPerWeek override fun createPlaceholderDates( startDate: LocalDate, endDate: LocalDate, skipScheduled: Boolean ) = emptyList<LocalDate>() override fun periodRangeFor(date: LocalDate) = PeriodRange( start = date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)), end = date.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY)) ) override fun doCreateSchedule(currentDate: LocalDate): Schedule { val nextMonday = currentDate.plusWeeks(1).with( TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY) ) return Schedule( dates = datesForPeriod(currentDate) + datesForPeriod(nextMonday), newRepeatPattern = copy(lastScheduledPeriodStart = nextMonday) ) } private fun datesForPeriod( startDateForPeriod: LocalDate ): List<LocalDate> { val weeksPassed = periodRangeFor(startDate).start.weeksUntil(startDateForPeriod) val shouldDoOnWeek = weeksPassed % doEveryXPeriods == 0L if (!shouldDoOnWeek || (lastScheduledPeriodStart != null && periodRangeFor(startDateForPeriod).start.isBeforeOrEqual( lastScheduledPeriodStart )) ) { return emptyList() } val daysOfWeek = DayOfWeek.values().toList() val days = if (preferredDays.isNotEmpty()) { preferredDays.shuffled().take(timesPerWeek) } else { daysOfWeek.shuffled().take(timesPerWeek) } return days .filter { it >= startDateForPeriod.dayOfWeek } .map { startDateForPeriod.with(TemporalAdjusters.nextOrSame(it)) } } } data class Monthly( val timesPerMonth: Int, val preferredDays: Set<Int>, override val startDate: LocalDate = LocalDate.now(), override val endDate: LocalDate? = null, override val lastScheduledPeriodStart: LocalDate? = null, override val skipEveryXPeriods: Int ) : Flexible() { override val countInPeriod get() = timesPerMonth override fun createPlaceholderDates( startDate: LocalDate, endDate: LocalDate, skipScheduled: Boolean ) = emptyList<LocalDate>() override fun periodRangeFor(date: LocalDate) = PeriodRange( start = date.with(TemporalAdjusters.firstDayOfMonth()), end = date.with(TemporalAdjusters.lastDayOfMonth()) ) override fun doCreateSchedule( currentDate: LocalDate ): Schedule { val nextFirstDayOfMonth = currentDate.plusMonths(1).with( TemporalAdjusters.firstDayOfMonth() ) return Schedule( dates = datesForPeriod(currentDate) + datesForPeriod(nextFirstDayOfMonth), newRepeatPattern = copy(lastScheduledPeriodStart = nextFirstDayOfMonth) ) } private fun datesForPeriod( startDateForPeriod: LocalDate ): List<LocalDate> { val period = periodRangeFor(startDateForPeriod) val monthsPassed = periodRangeFor(startDate).start.monthsUntil(startDateForPeriod) val shouldDoOnMonth = monthsPassed % doEveryXPeriods == 0L if (!shouldDoOnMonth || (lastScheduledPeriodStart != null && period.start.isBeforeOrEqual(lastScheduledPeriodStart)) ) { return emptyList() } val daysOfMonth = (1..period.start.lengthOfMonth()).map { it }.shuffled().take(timesPerMonth) val days = if (preferredDays.isNotEmpty()) { preferredDays.shuffled().take(timesPerMonth) } else { daysOfMonth.shuffled().take(timesPerMonth) } return days .filter { it >= startDateForPeriod.dayOfMonth } .map { startDateForPeriod.withDayOfMonth(it) } } } } data class Manual(override val startDate: LocalDate = LocalDate.now()) : RepeatPattern() { override val endDate: LocalDate? = null override val lastScheduledPeriodStart: LocalDate? = null override val skipEveryXPeriods: Int = 0 override val countInPeriod = 0 override fun periodRangeFor(date: LocalDate) = PeriodRange( start = date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)), end = date.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY)) ) override fun createPlaceholderDates( startDate: LocalDate, endDate: LocalDate, skipScheduled: Boolean ): List<LocalDate> = emptyList() override fun doCreateSchedule(currentDate: LocalDate) = Schedule(emptyList(), this) } } data class PeriodRange(val start: LocalDate, val end: LocalDate) data class PeriodProgress( val completedCount: Int, val scheduledCount: Int ) enum class RepeatType { DAILY, WEEKLY, MONTHLY, YEARLY, MANUAL } val RepeatPattern.repeatType: RepeatType get() = when (this) { is RepeatPattern.Daily -> RepeatType.DAILY is RepeatPattern.Weekly -> RepeatType.WEEKLY is RepeatPattern.Flexible.Weekly -> RepeatType.WEEKLY is RepeatPattern.Monthly -> RepeatType.MONTHLY is RepeatPattern.Flexible.Monthly -> RepeatType.MONTHLY is RepeatPattern.Yearly -> RepeatType.YEARLY is RepeatPattern.Manual -> RepeatType.MANUAL }
gpl-3.0
4b188b67655e17d314203d7cdf79fbdd
35.555126
98
0.581067
5.308427
false
false
false
false
hzsweers/CatchUp
services/newsapi/src/main/kotlin/io/sweers/catchup/service/newsapi/NewsApiApi.kt
1
1544
/* * Copyright (C) 2019. Zac Sweers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.sweers.catchup.service.newsapi import io.reactivex.rxjava3.core.Single import io.sweers.catchup.service.newsapi.model.NewsApiResponse import retrofit2.http.GET import retrofit2.http.Query /** * Models the NewsApi API. See https://newsapi.org/docs/get-started */ internal interface NewsApiApi { @GET("/v2/everything") fun getStories( @Query("pageSize") pageSize: Int, @Query("page") page: Int, @Query("from") from: String, @Query("q") query: String, @Query("language") language: Language, @Query("sortBy") sortBy: SortBy ): Single<NewsApiResponse> companion object { private const val SCHEME = "https" const val HOST = "newsapi.org" const val ENDPOINT = "$SCHEME://$HOST" } } internal enum class Language { EN; override fun toString() = super.toString().toLowerCase() } internal enum class SortBy { POPULARITY; override fun toString() = super.toString().toLowerCase() }
apache-2.0
7b63796e536e3cf05512d26666ff4ae9
26.571429
75
0.712435
3.831266
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/branchedTransformations/IfThenToSafeAccessInspection.kt
1
6816
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections.branchedTransformations import com.intellij.codeInspection.ProblemHighlightType import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiDocumentManager import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractApplicabilityBasedInspection import org.jetbrains.kotlin.idea.intentions.branchedTransformations.* import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.idea.refactoring.rename.KotlinVariableInplaceRenameHandler import com.intellij.openapi.application.runWriteAction import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.calls.util.getType class IfThenToSafeAccessInspection @JvmOverloads constructor(private val inlineWithPrompt: Boolean = true) : AbstractApplicabilityBasedInspection<KtIfExpression>(KtIfExpression::class.java) { override fun isApplicable(element: KtIfExpression): Boolean = isApplicableTo(element, expressionShouldBeStable = true) override fun inspectionHighlightRangeInElement(element: KtIfExpression) = element.fromIfKeywordToRightParenthesisTextRangeInThis() override fun inspectionText(element: KtIfExpression) = KotlinBundle.message("foldable.if.then") override fun inspectionHighlightType(element: KtIfExpression): ProblemHighlightType = if (element.shouldBeTransformed()) ProblemHighlightType.GENERIC_ERROR_OR_WARNING else ProblemHighlightType.INFORMATION override val defaultFixText get() = KotlinBundle.message("simplify.foldable.if.then") override fun fixText(element: KtIfExpression): String = fixTextFor(element) override val startFixInWriteAction = false override fun applyTo(element: KtIfExpression, project: Project, editor: Editor?) { convert(element, editor, inlineWithPrompt) } companion object { @Nls fun fixTextFor(element: KtIfExpression): String { val ifThenToSelectData = element.buildSelectTransformationData() return if (ifThenToSelectData?.baseClauseEvaluatesToReceiver() == true) { if (ifThenToSelectData.condition is KtIsExpression) { KotlinBundle.message("replace.if.expression.with.safe.cast.expression") } else { KotlinBundle.message("remove.redundant.if.expression") } } else { KotlinBundle.message("replace.if.expression.with.safe.access.expression") } } fun convert(ifExpression: KtIfExpression, editor: Editor?, inlineWithPrompt: Boolean) { val ifThenToSelectData = ifExpression.buildSelectTransformationData() ?: return val factory = KtPsiFactory(ifExpression) val resultExpr = runWriteAction { val replacedBaseClause = ifThenToSelectData.replacedBaseClause(factory) val newExpr = ifExpression.replaced(replacedBaseClause) KtPsiUtil.deparenthesize(newExpr) } if (editor != null && resultExpr is KtSafeQualifiedExpression) { resultExpr.inlineReceiverIfApplicable(editor, inlineWithPrompt) resultExpr.renameLetParameter(editor) } } fun isApplicableTo(element: KtIfExpression, expressionShouldBeStable: Boolean): Boolean { val ifThenToSelectData = element.buildSelectTransformationData() ?: return false if (expressionShouldBeStable && !ifThenToSelectData.receiverExpression.isStableSimpleExpression(ifThenToSelectData.context) ) return false return ifThenToSelectData.clausesReplaceableBySafeCall() } internal fun KtSafeQualifiedExpression.renameLetParameter(editor: Editor) { val callExpression = selectorExpression as? KtCallExpression ?: return if (callExpression.calleeExpression?.text != "let") return val parameter = callExpression.lambdaArguments.singleOrNull()?.getLambdaExpression()?.valueParameters?.singleOrNull() ?: return PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.document) editor.caretModel.moveToOffset(parameter.startOffset) KotlinVariableInplaceRenameHandler().doRename(parameter, editor, null) } } } private fun IfThenToSelectData.clausesReplaceableBySafeCall(): Boolean = when { baseClause == null -> false negatedClause == null && baseClause.isUsedAsExpression(context) -> false negatedClause != null && !negatedClause.isNullExpression() -> false context.diagnostics.forElement(condition) .any { it.factory == Errors.SENSELESS_COMPARISON || it.factory == Errors.USELESS_IS_CHECK } -> false baseClause.evaluatesTo(receiverExpression) -> true (baseClause as? KtCallExpression)?.calleeExpression?.evaluatesTo(receiverExpression) == true && baseClause.isCallingInvokeFunction(context) -> true baseClause.hasFirstReceiverOf(receiverExpression) -> withoutResultInCallChain(baseClause, context) baseClause.anyArgumentEvaluatesTo(receiverExpression) -> true receiverExpression is KtThisExpression -> getImplicitReceiver()?.let { it.type == receiverExpression.getType(context) } == true else -> false } private fun withoutResultInCallChain(expression: KtExpression, context: BindingContext): Boolean { if (expression !is KtDotQualifiedExpression || expression.receiverExpression !is KtDotQualifiedExpression) return true return !hasResultInCallExpression(expression, context) } private fun hasResultInCallExpression(expression: KtExpression, context: BindingContext): Boolean = if (expression is KtDotQualifiedExpression) returnTypeIsResult(expression.callExpression, context) || hasResultInCallExpression(expression.receiverExpression, context) else false private fun returnTypeIsResult(call: KtCallExpression?, context: BindingContext) = call ?.getType(context) ?.constructor ?.declarationDescriptor ?.importableFqName == RESULT_FQNAME private val RESULT_FQNAME = FqName("kotlin.Result")
apache-2.0
2da48f1c17516fc2104d3c4326dc65e4
51.030534
158
0.752494
5.312549
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/inspections/naming/objectPrivateProperty/test.kt
3
456
object Foo { private val _Foo: String = "" private val _FAR_A: String = "" private val _FAR_: String = "" private val `F%AR`: String = "" val Foo: String = "" var FOO_BAR: Int = 0 } class D { private val _foo: String private val FOO_BAR: String private val F%AR: String = "" companion object { private var _bar: String = "default" val Foo: String = "" var FOO_BAR: Int = 0 } }
apache-2.0
f79689199b63b5864404466c20225385
14.233333
44
0.532895
3.590551
false
false
false
false
GunoH/intellij-community
plugins/kotlin/injection/src/org/jetbrains/kotlin/idea/injection/KotlinLanguageInjectionContributor.kt
2
24079
// 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.injection import com.intellij.codeInsight.AnnotationUtil import com.intellij.lang.injection.general.LanguageInjectionContributor import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtilRt import com.intellij.patterns.PatternCondition import com.intellij.patterns.PatternConditionPlus import com.intellij.patterns.PsiClassNamePatternCondition import com.intellij.patterns.ValuePatternCondition import com.intellij.psi.* import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.asSafely import org.intellij.plugins.intelliLang.Configuration import org.intellij.plugins.intelliLang.inject.InjectorUtils import org.intellij.plugins.intelliLang.inject.LanguageInjectionSupport import org.intellij.plugins.intelliLang.inject.TemporaryPlacesRegistry import org.intellij.plugins.intelliLang.inject.config.BaseInjection import org.intellij.plugins.intelliLang.inject.config.Injection import org.intellij.plugins.intelliLang.inject.config.InjectionPlace import org.intellij.plugins.intelliLang.inject.java.JavaLanguageInjectionSupport import org.intellij.plugins.intelliLang.util.AnnotationUtilEx import org.jetbrains.kotlin.base.fe10.analysis.findAnnotation import org.jetbrains.kotlin.base.fe10.analysis.getStringValue import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.annotations.Annotated import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter import org.jetbrains.kotlin.idea.base.projectStructure.matches import org.jetbrains.kotlin.idea.base.psi.KotlinPsiHeuristics import org.jetbrains.kotlin.idea.caches.resolve.allowResolveInDispatchThread import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.core.util.runInReadActionWithWriteActionPriority import org.jetbrains.kotlin.idea.patterns.KotlinFunctionPattern import org.jetbrains.kotlin.idea.references.KtReference import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.references.resolveToDescriptors import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor import org.jetbrains.kotlin.idea.util.findAnnotation import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.utils.SmartList import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import org.intellij.lang.annotations.Language as LanguageAnnotation class KotlinLanguageInjectionContributor : LanguageInjectionContributor { private val absentKotlinInjection = BaseInjection("ABSENT_KOTLIN_BASE_INJECTION") companion object { private val STRING_LITERALS_REGEXP = "\"([^\"]*)\"".toRegex() } private val kotlinSupport: KotlinLanguageInjectionSupport? by lazy { ArrayList(InjectorUtils.getActiveInjectionSupports()).filterIsInstance(KotlinLanguageInjectionSupport::class.java).firstOrNull() } private data class KotlinCachedInjection(val modificationCount: Long, val baseInjection: BaseInjection) private var KtElement.cachedInjectionWithModification: KotlinCachedInjection? by UserDataProperty( Key.create<KotlinCachedInjection>("CACHED_INJECTION_WITH_MODIFICATION") ) private fun getBaseInjection(ktHost: KtElement, support: LanguageInjectionSupport): Injection { if (!RootKindFilter.projectAndLibrarySources.matches(ktHost.containingFile.originalFile)) return absentKotlinInjection val needImmediateAnswer = with(ApplicationManager.getApplication()) { isDispatchThread } val kotlinCachedInjection = ktHost.cachedInjectionWithModification if (needImmediateAnswer) { // Can't afford long counting or typing will be laggy. Force cache reuse even if it's outdated. kotlinCachedInjection?.baseInjection?.let { return it } } val modificationCount = PsiManager.getInstance(ktHost.project).modificationTracker.modificationCount return when { kotlinCachedInjection != null && (modificationCount == kotlinCachedInjection.modificationCount) -> // Cache is up-to-date kotlinCachedInjection.baseInjection else -> { fun computeAndCache(): BaseInjection { val computedInjection = computeBaseInjection(ktHost, support) ?: absentKotlinInjection ktHost.cachedInjectionWithModification = KotlinCachedInjection(modificationCount, computedInjection) return computedInjection } if (ApplicationManager.getApplication().run { !isDispatchThread && isReadAccessAllowed } && ProgressManager.getInstance().progressIndicator == null) { // The action cannot be canceled by caller and by internal checkCanceled() calls. // Force creating new indicator that is canceled on write action start, otherwise there might be lags in typing. runInReadActionWithWriteActionPriority(::computeAndCache) ?: kotlinCachedInjection?.baseInjection ?: absentKotlinInjection } else { computeAndCache() } } } } override fun getInjection(context: PsiElement): com.intellij.lang.injection.general.Injection? { if (context !is KtElement) return null if (!isSupportedElement(context)) return null val support = kotlinSupport ?: return null return getBaseInjection(context, support).takeIf { it != absentKotlinInjection } } private fun computeBaseInjection( ktHost: KtElement, support: LanguageInjectionSupport ): BaseInjection? { val containingFile = ktHost.containingFile val languageInjectionHost = when (ktHost) { is PsiLanguageInjectionHost -> ktHost is KtBinaryExpression -> flattenBinaryExpression(ktHost).firstIsInstanceOrNull<PsiLanguageInjectionHost>() else -> null } ?: return null val unwrapped = unwrapTrims(ktHost) // put before TempInjections for side effects, because TempInjection could also be trim-indented val tempInjectedLanguage = TemporaryPlacesRegistry.getInstance(ktHost.project).getLanguageFor(languageInjectionHost, containingFile) if (tempInjectedLanguage != null) { return BaseInjection(support.id).apply { injectedLanguageId = tempInjectedLanguage.id prefix = tempInjectedLanguage.prefix suffix = tempInjectedLanguage.suffix } } return findInjectionInfo(unwrapped)?.toBaseInjection(support) } private fun unwrapTrims(ktHost: KtElement): KtElement { if (!Registry.`is`("kotlin.injection.handle.trimindent", true)) return ktHost val dotQualifiedExpression = ktHost.parent as? KtDotQualifiedExpression ?: return ktHost val callExpression = dotQualifiedExpression.selectorExpression.asSafely<KtCallExpression>() ?: return ktHost val callFqn = callExpression.resolveToCall(BodyResolveMode.PARTIAL)?.candidateDescriptor?.fqNameOrNull()?.asString() if (callFqn == "kotlin.text.trimIndent") { ktHost.indentHandler = TrimIndentHandler() return dotQualifiedExpression } if (callFqn == "kotlin.text.trimMargin") { val marginChar = callExpression.valueArguments.getOrNull(0)?.getArgumentExpression().asSafely<KtStringTemplateExpression>() ?.entries?.singleOrNull()?.asSafely<KtLiteralStringTemplateEntry>()?.text ?: "|" ktHost.indentHandler = TrimIndentHandler(marginChar) return dotQualifiedExpression } return ktHost } private fun findInjectionInfo(place: KtElement, originalHost: Boolean = true): InjectionInfo? { return injectWithExplicitCodeInstruction(place) ?: injectWithCall(place) ?: injectReturnValue(place) ?: injectInAnnotationCall(place) ?: injectWithReceiver(place) ?: injectWithVariableUsage(place, originalHost) ?: injectWithMutation(place) } private val stringMutationOperators = listOf(KtTokens.EQ, KtTokens.PLUSEQ) private fun injectWithMutation(host: KtElement): InjectionInfo? { val parent = (host.parent as? KtBinaryExpression)?.takeIf { it.operationToken in stringMutationOperators } ?: return null if (parent.right != host) return null if (isAnalyzeOff(host.project)) return null val property = when (val left = parent.left) { is KtQualifiedExpression -> left.selectorExpression else -> left } ?: return null for (reference in property.references) { ProgressManager.checkCanceled() val resolvedTo = reference.resolve() if (resolvedTo is KtProperty) { val annotation = resolvedTo.findAnnotation(FqName(AnnotationUtil.LANGUAGE)) ?: return null return kotlinSupport?.toInjectionInfo(annotation) } } return null } private fun injectReturnValue(place: KtElement): InjectionInfo? { val parent = place.parent tailrec fun findReturnExpression(expression: PsiElement?): KtReturnExpression? = when (expression) { is KtReturnExpression -> expression is KtBinaryExpression -> findReturnExpression(expression.takeIf { it.operationToken == KtTokens.ELVIS }?.parent) is KtContainerNodeForControlStructureBody, is KtIfExpression -> findReturnExpression(expression.parent) else -> null } val returnExp = findReturnExpression(parent) ?: return null if (returnExp.labeledExpression != null) return null val callableDeclaration = PsiTreeUtil.getParentOfType(returnExp, KtDeclaration::class.java) as? KtCallableDeclaration ?: return null if (callableDeclaration.annotationEntries.isEmpty()) return null val descriptor = callableDeclaration.descriptor ?: return null return injectionInfoByAnnotation(descriptor) } private fun injectWithExplicitCodeInstruction(host: KtElement): InjectionInfo? { val support = kotlinSupport ?: return null return InjectionInfo.fromBaseInjection(support.findCommentInjection(host)) ?: support.findAnnotationInjectionLanguageId(host) } private fun injectWithReceiver(host: KtElement): InjectionInfo? { val qualifiedExpression = host.parent as? KtDotQualifiedExpression ?: return null if (qualifiedExpression.receiverExpression != host) return null val callExpression = qualifiedExpression.selectorExpression as? KtCallExpression ?: return null val callee = callExpression.calleeExpression ?: return null if (isAnalyzeOff(host.project)) return null val kotlinInjections = Configuration.getProjectInstance(host.project).getInjections(KOTLIN_SUPPORT_ID) val calleeName = callee.text val possibleNames = collectPossibleNames(kotlinInjections) if (calleeName !in possibleNames) { return null } for (reference in callee.references) { ProgressManager.checkCanceled() val resolvedTo = reference.resolve() if (resolvedTo is KtFunction) { val injectionInfo = findInjection(resolvedTo.receiverTypeReference, kotlinInjections) if (injectionInfo != null) { return injectionInfo } } } return null } private fun collectPossibleNames(injections: List<BaseInjection>): Set<String> { val result = HashSet<String>() for (injection in injections) { val injectionPlaces = injection.injectionPlaces for (place in injectionPlaces) { val placeStr = place.toString() val literals = STRING_LITERALS_REGEXP.findAll(placeStr).map { it.groupValues[1] } result.addAll(literals) } } return result } private fun injectWithVariableUsage(host: KtElement, originalHost: Boolean): InjectionInfo? { // Given place is not original host of the injection so we stop to prevent stepping through indirect references if (!originalHost) return null val ktProperty = host.parent as? KtProperty ?: return null if (ktProperty.initializer != host) return null if (isAnalyzeOff(host.project)) return null val searchScope = LocalSearchScope(arrayOf(ktProperty.containingFile), "", true) return ReferencesSearch.search(ktProperty, searchScope).asSequence().mapNotNull { psiReference -> val element = psiReference.element as? KtElement ?: return@mapNotNull null findInjectionInfo(element, false) }.firstOrNull() } private tailrec fun injectWithCall(host: KtElement): InjectionInfo? { val argument = getArgument(host) ?: return null val callExpression = PsiTreeUtil.getParentOfType(argument, KtCallElement::class.java) ?: return null if (getCallableShortName(callExpression) == "arrayOf") return injectWithCall(callExpression) val callee = getNameReference(callExpression.calleeExpression) ?: return null if (isAnalyzeOff(host.project)) return null for (reference in callee.references) { ProgressManager.checkCanceled() val resolvedTo = allowResolveInDispatchThread { reference.resolve() } if (resolvedTo is PsiMethod) { val injectionForJavaMethod = injectionForJavaMethod(argument, resolvedTo) if (injectionForJavaMethod != null) { return injectionForJavaMethod } } else if (resolvedTo is KtFunction) { val injectionForJavaMethod = injectionForKotlinCall(argument, resolvedTo, reference) if (injectionForJavaMethod != null) { return injectionForJavaMethod } } } return null } private fun getNameReference(callee: KtExpression?): KtNameReferenceExpression? { if (callee is KtConstructorCalleeExpression) return callee.constructorReferenceExpression as? KtNameReferenceExpression return callee as? KtNameReferenceExpression } private fun getArgument(host: KtElement): KtValueArgument? = when (val parent = host.parent) { is KtValueArgument -> parent is KtCollectionLiteralExpression, is KtCallElement -> parent.parent as? KtValueArgument else -> null } private tailrec fun injectInAnnotationCall(host: KtElement): InjectionInfo? { val argument = getArgument(host) ?: return null val annotationEntry = argument.parent.parent as? KtCallElement ?: return null val callableShortName = getCallableShortName(annotationEntry) ?: return null if (callableShortName == "arrayOf") return injectInAnnotationCall(annotationEntry) if (!fastCheckInjectionsExists(callableShortName, host.project)) return null val calleeExpression = annotationEntry.calleeExpression ?: return null val callee = getNameReference(calleeExpression)?.mainReference?.let { reference -> allowResolveInDispatchThread { reference.resolve() } } when (callee) { is PsiClass -> { val psiClass = callee as? PsiClass ?: return null val argumentName = argument.getArgumentName()?.asName?.identifier ?: "value" val method = psiClass.findMethodsByName(argumentName, false).singleOrNull() ?: return null return findInjection( method, Configuration.getProjectInstance(host.project).getInjections(JavaLanguageInjectionSupport.JAVA_SUPPORT_ID) ) } else -> return null } } private fun injectionForJavaMethod(argument: KtValueArgument, javaMethod: PsiMethod): InjectionInfo? { val argumentIndex = (argument.parent as KtValueArgumentList).arguments.indexOf(argument) val psiParameter = javaMethod.parameterList.parameters.getOrNull(argumentIndex) ?: return null val injectionInfo = findInjection(psiParameter, Configuration.getProjectInstance(argument.project) .getInjections(JavaLanguageInjectionSupport.JAVA_SUPPORT_ID) ) if (injectionInfo != null) { return injectionInfo } val annotations = AnnotationUtilEx.getAnnotationFrom( psiParameter, Configuration.getProjectInstance(argument.project).advancedConfiguration.languageAnnotationPair, true ) if (annotations.isNotEmpty()) { return processAnnotationInjectionInner(annotations) } return null } private fun injectionForKotlinCall(argument: KtValueArgument, ktFunction: KtFunction, reference: PsiReference): InjectionInfo? { val argumentName = argument.getArgumentName()?.asName val argumentIndex = (argument.parent as KtValueArgumentList).arguments.indexOf(argument) // Prefer using argument name if present val ktParameter = if (argumentName != null) { ktFunction.valueParameters.firstOrNull { it.nameAsName == argumentName } } else { ktFunction.valueParameters.getOrNull(argumentIndex) } ?: return null val patternInjection = findInjection(ktParameter, Configuration.getProjectInstance(argument.project).getInjections(KOTLIN_SUPPORT_ID)) if (patternInjection != null) { return patternInjection } // Found psi element after resolve can be obtained from compiled declaration but annotations parameters are lost there. // Search for original descriptor from reference. val ktReference = reference as? KtReference ?: return null val functionDescriptor = allowResolveInDispatchThread { val bindingContext = ktReference.element.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS) ktReference.resolveToDescriptors(bindingContext).singleOrNull() as? FunctionDescriptor } ?: return null val parameterDescriptor = if (argumentName != null) { functionDescriptor.valueParameters.firstOrNull { it.name == argumentName } } else { functionDescriptor.valueParameters.getOrNull(argumentIndex) } ?: return null return injectionInfoByAnnotation(parameterDescriptor) } private fun injectionInfoByAnnotation(annotated: Annotated): InjectionInfo? { val injectAnnotation = annotated.findAnnotation<LanguageAnnotation>() ?: return null val languageId = injectAnnotation.getStringValue(LanguageAnnotation::value) ?: return null val prefix = injectAnnotation.getStringValue(LanguageAnnotation::prefix) val suffix = injectAnnotation.getStringValue(LanguageAnnotation::suffix) return InjectionInfo(languageId, prefix, suffix) } private fun findInjection(element: PsiElement?, injections: List<BaseInjection>): InjectionInfo? { for (injection in injections) { if (injection.acceptsPsiElement(element)) { return InjectionInfo(injection.injectedLanguageId, injection.prefix, injection.suffix) } } return null } private fun isAnalyzeOff(project: Project): Boolean { return Configuration.getProjectInstance(project).advancedConfiguration.dfaOption == Configuration.DfaOption.OFF } private fun processAnnotationInjectionInner(annotations: Array<PsiAnnotation>): InjectionInfo { val id = AnnotationUtilEx.calcAnnotationValue(annotations, "value") val prefix = AnnotationUtilEx.calcAnnotationValue(annotations, "prefix") val suffix = AnnotationUtilEx.calcAnnotationValue(annotations, "suffix") return InjectionInfo(id, prefix, suffix) } private fun createCachedValue(project: Project): CachedValueProvider.Result<HashSet<String>> = with(Configuration.getProjectInstance(project)) { CachedValueProvider.Result.create( (getInjections(JavaLanguageInjectionSupport.JAVA_SUPPORT_ID) + getInjections(KOTLIN_SUPPORT_ID)) .asSequence() .flatMap { it.injectionPlaces.asSequence() } .flatMap { retrieveJavaPlaceTargetClassesFQNs(it).asSequence() + retrieveKotlinPlaceTargetClassesFQNs(it).asSequence() } .map { StringUtilRt.getShortName(it) } .toHashSet(), this) } private fun getInjectableTargetClassShortNames(project: Project) = CachedValuesManager.getManager(project).createCachedValue({ createCachedValue(project) }, false) private fun fastCheckInjectionsExists( annotationShortName: String, project: Project ) = annotationShortName in getInjectableTargetClassShortNames(project).value private fun getCallableShortName(annotationEntry: KtCallElement): String? { val referencedName = getNameReference(annotationEntry.calleeExpression)?.getReferencedName() ?: return null return KotlinPsiHeuristics.unwrapImportAlias(annotationEntry.containingKtFile, referencedName).singleOrNull() ?: referencedName } private fun retrieveJavaPlaceTargetClassesFQNs(place: InjectionPlace): Collection<String> { val classCondition = place.elementPattern.condition.conditions.firstOrNull { it.debugMethodName == "definedInClass" } as? PatternConditionPlus<*, *> ?: return emptyList() val psiClassNamePatternCondition = classCondition.valuePattern.condition.conditions.firstIsInstanceOrNull<PsiClassNamePatternCondition>() ?: return emptyList() val valuePatternCondition = psiClassNamePatternCondition.namePattern.condition.conditions.firstIsInstanceOrNull<ValuePatternCondition<String>>() ?: return emptyList() return valuePatternCondition.values } private fun retrieveKotlinPlaceTargetClassesFQNs(place: InjectionPlace): Collection<String> { val classNames = SmartList<String>() fun collect(condition: PatternCondition<*>) { when (condition) { is PatternConditionPlus<*, *> -> condition.valuePattern.condition.conditions.forEach { collect(it) } is KotlinFunctionPattern.DefinedInClassCondition -> classNames.add(condition.fqName) } } place.elementPattern.condition.conditions.forEach { collect(it) } return classNames } } internal fun isSupportedElement(context: KtElement): Boolean { if (context.parent?.isConcatenationExpression() != false) return false // we will handle the top concatenation only, will not handle KtFile-s if (context is KtStringTemplateExpression && context.isValidHost) return true if (context.isConcatenationExpression()) return true return false } internal var KtElement.indentHandler: IndentHandler? by UserDataProperty( Key.create<IndentHandler>("KOTLIN_INDENT_HANDLER") )
apache-2.0
22f498de8933e3b68c8e0dd6e2c519a0
47.351406
167
0.709706
5.729003
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ide/customize/transferSettings/models/Keymaps.kt
2
3550
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.customize.transferSettings.models import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.KeyboardShortcut import com.intellij.openapi.keymap.Keymap import com.intellij.openapi.keymap.ex.KeymapManagerEx import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.NlsSafe import org.jetbrains.annotations.Nls interface Keymap { val displayName: @Nls String val demoShortcuts: List<SimpleActionDescriptor> } class BundledKeymap(override val displayName: @Nls String, val keymap: Keymap, override val demoShortcuts: List<SimpleActionDescriptor>): com.intellij.ide.customize.transferSettings.models.Keymap { companion object { fun fromManager(keymapName: String, demoShortcuts: List<SimpleActionDescriptor>): BundledKeymap { val keymap = KeymapManagerEx.getInstanceEx().getKeymap(keymapName) ?: error("Keymap $keymapName was not found") return BundledKeymap(keymap.displayName, keymap, demoShortcuts) } fun fromManager(keymapName: String) = fromManager(keymapName, emptyList()) } } class PluginKeymap(override val displayName: @Nls String, val pluginId: String, val installedName: String, val fallback: BundledKeymap, override val demoShortcuts: List<SimpleActionDescriptor>) : com.intellij.ide.customize.transferSettings.models.Keymap class PatchedKeymap(var parent: com.intellij.ide.customize.transferSettings.models.Keymap, val overrides: List<KeyBinding>, val removal: List<KeyBinding>) : com.intellij.ide.customize.transferSettings.models.Keymap { override val displayName: String get() = parent.displayName override val demoShortcuts by lazy { mergeShortcutsForDemo() } private fun mergeShortcutsForDemo(): List<SimpleActionDescriptor> { val overrides = overrides.associate { it.toPair() } val removal = removal.associate { it.toPair() } val res = parent.demoShortcuts.mapNotNull { val newShortcuts = it.defaultShortcut as? KeyboardShortcut ?: return@mapNotNull it if (removal[it.action]?.contains(newShortcuts) == true) return@mapNotNull null val overridesSc = overrides[it.action] if (!overridesSc.isNullOrEmpty()) { SimpleActionDescriptor(it.action, it.humanName, overridesSc.random()) } else { it } } return res } } data class KeyBinding( @NlsSafe val actionId: String, val shortcuts: List<KeyboardShortcut> ) { override fun toString(): String { return "$actionId: ${shortcuts}\n" } fun toPair(): Pair<String, List<KeyboardShortcut>> = actionId to shortcuts } class SimpleActionDescriptor( val action: String, @NlsContexts.Label val humanName: String, val defaultShortcut: Any // KeyboardShortcut or DummyKeyboardShortcut ) { companion object { private fun fromKeymap(keymap: Keymap, actionIds: List<String>): List<SimpleActionDescriptor> { return actionIds.map { SimpleActionDescriptor( it, ActionManager.getInstance().getAction(it).templateText ?: error("Action $it doesn't contain its name"), keymap.getShortcuts(it).filterIsInstance<KeyboardShortcut>() ) } } fun fromManager(keymapName: String, actionIds: List<String>): List<SimpleActionDescriptor> { val keymap = KeymapManagerEx.getInstanceEx().getKeymap(keymapName) ?: error("Keymap was not found") return fromKeymap(keymap, actionIds) } } }
apache-2.0
102e5fa187854f6c54de916931c284cd
40.27907
253
0.749577
4.454203
false
false
false
false
andrewoma/dexx
collection/src/test/java/com/github/andrewoma/dexx/collection/performance/PerformanceMeasurement.kt
1
3692
/* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection.performance import com.github.andrewoma.dexx.TestMode import java.security.SecureRandom import java.util.* import kotlin.test.assertEquals import com.github.andrewoma.dexx.collection.Set as DSet interface PerformanceMeasurement { data class Result(val nanoDuration: Long, val result: Long) fun uniqueRandomInts(size: Int): IntArray { val random = SecureRandom() val generated = LinkedHashSet<Int>() while (generated.size < size) { generated.add(random.nextInt()) } val ints = IntArray(generated.size) var i = 0 for (value in generated) { ints[i++] = value } return ints } fun randomInts(size: Int): IntArray { val random = SecureRandom() val ints = IntArray(size) for (i in 0..size - 1) { ints[i] = random.nextInt() } return ints } fun randomAccesses(size: Int, data: IntArray, returnValue: Boolean): IntArray { val random = SecureRandom() val accesses = IntArray(size) for (i in 0..size - 1) { val index = random.nextInt(data.size) accesses[i] = (if (returnValue) data[index] else index) } return accesses } fun compare(description: String, operations: Int, java: Result, dexx: Result) { fun nanoPerOp(nanoDuration: Long) = nanoDuration.toDouble() / operations.toDouble() fun delta(java: Long, dexx: Long): String { return if (java > dexx) { "Dexx is ${"%.2f".format(java.toDouble() / dexx.toDouble())} times faster" } else { "Java is ${"%.2f".format(dexx.toDouble() / java.toDouble())} times faster" } } assertEquals(java.result, dexx.result) println("BENCHMARK: $description: Java: ${nanoPerOp(java.nanoDuration)}ns/op Dexx: ${nanoPerOp(dexx.nanoDuration)}ns/op. ${delta(java.nanoDuration, dexx.nanoDuration)}") } fun time(iterations: Int, f: () -> Result): Result { var last: Result? = null val times = arrayListOf<Long>() repeat(iterations) { val result = f() if (last != null) { assertEquals(last!!.result, result.result) } last = result times.add(result.nanoDuration) } return Result(times.min()!!, last!!.result) } fun disabled() = !TestMode.isEnabled(TestMode.BENCHMARK) }
mit
4134c6b5433131246319b7e2fc05bbba
33.830189
177
0.63299
4.30303
false
false
false
false
google/android-fhir
engine/src/main/java/com/google/android/fhir/db/DatabaseEncryptionException.kt
1
7428
/* * 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 com.google.android.fhir.db import com.google.android.fhir.db.DatabaseEncryptionException.DatabaseEncryptionErrorCode.TIMEOUT import com.google.android.fhir.db.DatabaseEncryptionException.DatabaseEncryptionErrorCode.UNKNOWN import com.google.android.fhir.db.DatabaseEncryptionException.DatabaseEncryptionErrorCode.UNSUPPORTED import com.google.android.fhir.db.KeyStoreExceptionErrorCode.ERROR_SECURE_HW_BUSY import com.google.android.fhir.db.KeyStoreExceptionErrorCode.ERROR_SECURE_HW_COMMUNICATION_FAILED import com.google.android.fhir.db.KeyStoreExceptionErrorCode.ERROR_UNSUPPORTED_ALGORITHM import com.google.android.fhir.db.KeyStoreExceptionErrorCode.ERROR_UNSUPPORTED_BLOCK_MODE import com.google.android.fhir.db.KeyStoreExceptionErrorCode.ERROR_UNSUPPORTED_DIGEST import com.google.android.fhir.db.KeyStoreExceptionErrorCode.ERROR_UNSUPPORTED_EC_FIELD import com.google.android.fhir.db.KeyStoreExceptionErrorCode.ERROR_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM import com.google.android.fhir.db.KeyStoreExceptionErrorCode.ERROR_UNSUPPORTED_KEY_FORMAT import com.google.android.fhir.db.KeyStoreExceptionErrorCode.ERROR_UNSUPPORTED_KEY_SIZE import com.google.android.fhir.db.KeyStoreExceptionErrorCode.ERROR_UNSUPPORTED_KEY_VERIFICATION_ALGORITHM import com.google.android.fhir.db.KeyStoreExceptionErrorCode.ERROR_UNSUPPORTED_MAC_LENGTH import com.google.android.fhir.db.KeyStoreExceptionErrorCode.ERROR_UNSUPPORTED_MIN_MAC_LENGTH import com.google.android.fhir.db.KeyStoreExceptionErrorCode.ERROR_UNSUPPORTED_PADDING_MODE import com.google.android.fhir.db.KeyStoreExceptionErrorCode.ERROR_UNSUPPORTED_PURPOSE import com.google.android.fhir.db.KeyStoreExceptionErrorCode.ERROR_UNSUPPORTED_TAG import java.security.KeyStoreException /** * An database encryption exception wrapper which maps comprehensive keystore errors to a limited * set of actionable errors. */ class DatabaseEncryptionException(cause: Exception, val errorCode: DatabaseEncryptionErrorCode) : Exception(cause) { enum class DatabaseEncryptionErrorCode { /** Unclassified error. The error could potentially be mitigated by recreating the database. */ UNKNOWN, /** Required encryption algorithm is not available. */ UNSUPPORTED, /** Timeout when accessing encrypted database. */ TIMEOUT, } } val KeyStoreException.databaseEncryptionException: DatabaseEncryptionException get() { message?.let { "-[0-9]+".toRegex().find(it)?.let { matchResult -> matchResult.value.toIntOrNull()?.let { errorCode -> val encryptionException = when (errorCode) { // Unsupported: these errors can't be fixed by retries. ERROR_UNSUPPORTED_PURPOSE, ERROR_UNSUPPORTED_ALGORITHM, ERROR_UNSUPPORTED_KEY_SIZE, ERROR_UNSUPPORTED_BLOCK_MODE, ERROR_UNSUPPORTED_MAC_LENGTH, ERROR_UNSUPPORTED_PADDING_MODE, ERROR_UNSUPPORTED_DIGEST, ERROR_UNSUPPORTED_KEY_FORMAT, ERROR_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM, ERROR_UNSUPPORTED_KEY_VERIFICATION_ALGORITHM, ERROR_UNSUPPORTED_TAG, ERROR_UNSUPPORTED_EC_FIELD, ERROR_UNSUPPORTED_MIN_MAC_LENGTH -> DatabaseEncryptionException(this, UNSUPPORTED) // Timeout: these errors could be recoverable ERROR_SECURE_HW_BUSY, ERROR_SECURE_HW_COMMUNICATION_FAILED -> DatabaseEncryptionException(this, TIMEOUT) else -> DatabaseEncryptionException(this, UNKNOWN) } return encryptionException } } } return DatabaseEncryptionException(this, UNKNOWN) } /** * A list of keystore error. This is a duplicate of * https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/security/keymaster/KeymasterDefs.java */ @Suppress("Unused") object KeyStoreExceptionErrorCode { const val ERROR_OK = 0 const val ERROR_ROOT_OF_TRUST_ALREADY_SET = -1 const val ERROR_UNSUPPORTED_PURPOSE = -2 const val ERROR_INCOMPATIBLE_PURPOSE = -3 const val ERROR_UNSUPPORTED_ALGORITHM = -4 const val ERROR_INCOMPATIBLE_ALGORITHM = -5 const val ERROR_UNSUPPORTED_KEY_SIZE = -6 const val ERROR_UNSUPPORTED_BLOCK_MODE = -7 const val ERROR_INCOMPATIBLE_BLOCK_MODE = -8 const val ERROR_UNSUPPORTED_MAC_LENGTH = -9 const val ERROR_UNSUPPORTED_PADDING_MODE = -10 const val ERROR_INCOMPATIBLE_PADDING_MODE = -11 const val ERROR_UNSUPPORTED_DIGEST = -12 const val ERROR_INCOMPATIBLE_DIGEST = -13 const val ERROR_INVALID_EXPIRATION_TIME = -14 const val ERROR_INVALID_USER_ID = -15 const val ERROR_INVALID_AUTHORIZATION_TIMEOUT = -16 const val ERROR_UNSUPPORTED_KEY_FORMAT = -17 const val ERROR_INCOMPATIBLE_KEY_FORMAT = -18 const val ERROR_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM = -19 const val ERROR_UNSUPPORTED_KEY_VERIFICATION_ALGORITHM = -20 const val ERROR_INVALID_INPUT_LENGTH = -21 const val ERROR_KEY_EXPORT_OPTIONS_INVALID = -22 const val ERROR_DELEGATION_NOT_ALLOWED = -23 const val ERROR_KEY_NOT_YET_VALID = -24 const val ERROR_KEY_EXPIRED = -25 const val ERROR_KEY_USER_NOT_AUTHENTICATED = -26 const val ERROR_OUTPUT_PARAMETER_NULL = -27 const val ERROR_INVALID_OPERATION_HANDLE = -28 const val ERROR_INSUFFICIENT_BUFFER_SPACE = -29 const val ERROR_VERIFICATION_FAILED = -30 const val ERROR_TOO_MANY_OPERATIONS = -31 const val ERROR_UNEXPECTED_NULL_POINTER = -32 const val ERROR_INVALID_KEY_BLOB = -33 const val ERROR_IMPORTED_KEY_NOT_ENCRYPTED = -34 const val ERROR_IMPORTED_KEY_DECRYPTION_FAILED = -35 const val ERROR_IMPORTED_KEY_NOT_SIGNED = -36 const val ERROR_IMPORTED_KEY_VERIFICATION_FAILED = -37 const val ERROR_INVALID_ARGUMENT = -38 const val ERROR_UNSUPPORTED_TAG = -39 const val ERROR_INVALID_TAG = -40 const val ERROR_MEMORY_ALLOCATION_FAILED = -41 const val ERROR_INVALID_RESCOPING = -42 const val ERROR_IMPORT_PARAMETER_MISMATCH = -44 const val ERROR_SECURE_HW_ACCESS_DENIED = -45 const val ERROR_OPERATION_CANCELLED = -46 const val ERROR_CONCURRENT_ACCESS_CONFLICT = -47 const val ERROR_SECURE_HW_BUSY = -48 const val ERROR_SECURE_HW_COMMUNICATION_FAILED = -49 const val ERROR_UNSUPPORTED_EC_FIELD = -50 const val ERROR_MISSING_NONCE = -51 const val ERROR_INVALID_NONCE = -52 const val ERROR_MISSING_MAC_LENGTH = -53 const val ERROR_KEY_RATE_LIMIT_EXCEEDED = -54 const val ERROR_CALLER_NONCE_PROHIBITED = -55 const val ERROR_KEY_MAX_OPS_EXCEEDED = -56 const val ERROR_INVALID_MAC_LENGTH = -57 const val ERROR_MISSING_MIN_MAC_LENGTH = -58 const val ERROR_UNSUPPORTED_MIN_MAC_LENGTH = -59 const val ERROR_CANNOT_ATTEST_IDS = -66 const val ERROR_UNIMPLEMENTED = -100 const val ERROR_VERSION_MISMATCH = -101 const val ERROR_UNKNOWN_ERROR = -1000 }
apache-2.0
7dc6c6a87260ae0ff309e48bcd478981
45.425
125
0.749865
4.041349
false
false
false
false
MichaelRocks/grip
library/src/main/java/io/michaelrocks/grip/mirrors/AnnotationMirror.kt
1
5055
/* * Copyright 2021 Michael Rozumyanskiy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.michaelrocks.grip.mirrors import io.michaelrocks.grip.commons.LazyMap import java.util.Arrays interface AnnotationMirror : Typed<Type.Object> { val values: Map<String, Any> val visible: Boolean val resolved: Boolean class Builder { private var type: Type.Object? = null private var visible: Boolean = false private val values = LazyMap<String, Any>() fun type(type: Type.Object) = apply { this.type = type } fun visible(visible: Boolean) = apply { this.visible = visible } fun addValue(value: Any) = addValue("value", value) fun addValue(name: String, value: Any) = apply { this.values.put(name, value) } fun addValues(mirror: AnnotationMirror) = apply { this.values.putAll(mirror.values) } fun build(): AnnotationMirror = ImmutableAnnotationMirror(this) private class ImmutableAnnotationMirror(builder: Builder) : AbstractAnnotationMirror() { override val type = builder.type!! override val values = builder.values.immutableCopy() override val visible = builder.visible override val resolved: Boolean get() = true } } } internal abstract class AbstractAnnotationMirror : AnnotationMirror { override fun toString(): String = "AnnotationMirror{type = $type, values = $values, visible = $visible}" override fun equals(other: Any?): Boolean { if (this === other) { return true } val that = other as? AnnotationMirror ?: return false if (type != that.type || values.size != that.values.size || visible != that.visible || resolved != that.resolved) { return false } return values.all { val value = that.values[it.key] ?: return false if (value.javaClass.isArray) { when (value) { is BooleanArray -> Arrays.equals(value, it.value as? BooleanArray) is ByteArray -> Arrays.equals(value, it.value as? ByteArray) is CharArray -> Arrays.equals(value, it.value as? CharArray) is DoubleArray -> Arrays.equals(value, it.value as? DoubleArray) is FloatArray -> Arrays.equals(value, it.value as? FloatArray) is IntArray -> Arrays.equals(value, it.value as? IntArray) is LongArray -> Arrays.equals(value, it.value as? LongArray) is ShortArray -> Arrays.equals(value, it.value as? ShortArray) is Array<*> -> Arrays.equals(value, it.value as? Array<*>) else -> error("Huh, unknown array type: $value") } } else { it.value == value } } } override fun hashCode(): Int { val valuesHashCode = values.entries.fold(37) { hashCode, entry -> hashCode + (entry.key.hashCode() xor hashCode(entry.value)) } var hashCode = 37 hashCode = hashCode * 17 + type.hashCode() hashCode = hashCode * 17 + valuesHashCode hashCode = hashCode * 17 + visible.hashCode() hashCode = hashCode * 17 + resolved.hashCode() return hashCode } private fun hashCode(value: Any?): Int { value ?: return 0 return if (value.javaClass.isArray) { when (value) { is BooleanArray -> Arrays.hashCode(value) is ByteArray -> Arrays.hashCode(value) is CharArray -> Arrays.hashCode(value) is DoubleArray -> Arrays.hashCode(value) is FloatArray -> Arrays.hashCode(value) is IntArray -> Arrays.hashCode(value) is LongArray -> Arrays.hashCode(value) is ShortArray -> Arrays.hashCode(value) is Array<*> -> value.fold(37) { current, item -> current * 17 + hashCode(item) } else -> error("Huh, unknown array type: $value") } } else { value.hashCode() } } } internal class UnresolvedAnnotationMirror( override val type: Type.Object ) : AbstractAnnotationMirror() { override val values: Map<String, Any> get() = emptyMap() override val visible: Boolean get() = false override val resolved: Boolean get() = false override fun toString(): String = "UnresolvedAnnotationMirror{type = $type}" } fun buildAnnotation(type: Type.Object, visible: Boolean): AnnotationMirror { return AnnotationMirror.Builder() .type(type) .visible(visible) .build() } inline fun buildAnnotation( type: Type.Object, visible: Boolean, body: AnnotationMirror.Builder.() -> Unit ): AnnotationMirror { return AnnotationMirror.Builder().run { type(type) visible(visible) body() build() } }
apache-2.0
d17aa2ba746448432ffee05db46b0d5b
30.792453
119
0.660336
4.230126
false
false
false
false
jrenner/kotlin_raytracer
core/src/org/jrenner/raytracer/Extensions.kt
1
1036
package org.jrenner.raytracer import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.math.MathUtils import com.badlogic.gdx.math.Vector3 import com.badlogic.gdx.math.collision.Ray fun Vector3.randomize(): Vector3 { x = rand(-1f, 1f) y = rand(-1f, 1f) z = rand(-1f, 1f) this.nor() return this } fun Color.randomize(): Color { r = rand() g = rand() b = rand() return this } fun rand(n: Float=1f): Float { return MathUtils.random(n) } fun rand(n1: Float, n2: Float): Float { return MathUtils.random(n1, n2) } fun Vector3.clamp(): Vector3 { x = MathUtils.clamp(x, 0f, 1f) y = MathUtils.clamp(y, 0f, 1f) z = MathUtils.clamp(z, 0f, 1f) return this } fun <T> Array<T>.random(): T { val idx = MathUtils.random(size-1) return this[idx] } val Float.fmt: String get() = "%.2f".format(this) val Vector3.fmt: String get() { return "x: ${x.fmt} y: ${y.fmt} z: ${z.fmt}" } val Ray.fmt: String get() { return "origin: ${origin.fmt}, dir: ${direction.fmt}" }
apache-2.0
9acba59db26833dc8d341ea9eb1a34a4
18.942308
57
0.623552
2.755319
false
false
false
false
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/program/programindicatorengine/internal/AnalyticsBoundaryParser.kt
1
2990
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.program.programindicatorengine.internal internal object AnalyticsBoundaryParser { private val dataElementRegex = "^#\\{(\\w{11})\\.(\\w{11})\\}$".toRegex() private val attributeRegex = "^A\\{(\\w{11})\\}$".toRegex() private val psEventDateRegex = "^PS_EVENTDATE:(\\w{11})$".toRegex() fun parseBoundaryTarget(target: String?): AnalyticsBoundaryTarget? { return if (target == null) { null } else if (target == "EVENT_DATE") { AnalyticsBoundaryTarget.EventDate } else if (target == "ENROLLMENT_DATE") { AnalyticsBoundaryTarget.EnrollmentDate } else if (target == "INCIDENT_DATE") { AnalyticsBoundaryTarget.IncidentDate } else { dataElementRegex.find(target)?.let { match -> val (programStageUid, dataElementUid) = match.destructured AnalyticsBoundaryTarget.Custom.DataElement(programStageUid, dataElementUid) } ?: attributeRegex.find(target)?.let { match -> val (attributeUid) = match.destructured AnalyticsBoundaryTarget.Custom.Attribute(attributeUid) } ?: psEventDateRegex.find(target)?.let { match -> val (programStageUid) = match.destructured AnalyticsBoundaryTarget.Custom.PSEventDate(programStageUid) } } } }
bsd-3-clause
8cd1c19177fe50ec5aa4637def1d0a9d
49.677966
91
0.697324
4.657321
false
false
false
false
iSoron/uhabits
uhabits-core/src/jvmMain/java/org/isoron/uhabits/core/ui/screens/habits/show/ShowHabitMenuPresenter.kt
1
3345
/* * Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]> * * This file is part of Loop Habit Tracker. * * Loop Habit Tracker 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. * * Loop Habit Tracker 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 org.isoron.uhabits.core.ui.screens.habits.show import org.isoron.uhabits.core.commands.CommandRunner import org.isoron.uhabits.core.commands.DeleteHabitsCommand import org.isoron.uhabits.core.models.Entry import org.isoron.uhabits.core.models.Habit import org.isoron.uhabits.core.models.HabitList import org.isoron.uhabits.core.tasks.ExportCSVTask import org.isoron.uhabits.core.tasks.TaskRunner import org.isoron.uhabits.core.ui.callbacks.OnConfirmedCallback import org.isoron.uhabits.core.utils.DateUtils import java.io.File import java.util.Random import kotlin.math.max import kotlin.math.min class ShowHabitMenuPresenter( private val commandRunner: CommandRunner, private val habit: Habit, private val habitList: HabitList, private val screen: Screen, private val system: System, private val taskRunner: TaskRunner, ) { fun onEditHabit() { screen.showEditHabitScreen(habit) } fun onExportCSV() { val outputDir = system.getCSVOutputDir() taskRunner.execute( ExportCSVTask(habitList, listOf(habit), outputDir) { filename: String? -> if (filename != null) { screen.showSendFileScreen(filename) } else { screen.showMessage(Message.COULD_NOT_EXPORT) } } ) } fun onDeleteHabit() { screen.showDeleteConfirmationScreen { commandRunner.run(DeleteHabitsCommand(habitList, listOf(habit))) screen.close() } } fun onRandomize() { val random = Random() habit.originalEntries.clear() var strength = 50.0 for (i in 0 until 365 * 5) { if (i % 7 == 0) strength = max(0.0, min(100.0, strength + 10 * random.nextGaussian())) if (random.nextInt(100) > strength) continue var value = Entry.YES_MANUAL if (habit.isNumerical) value = (1000 + 250 * random.nextGaussian() * strength / 100).toInt() * 1000 habit.originalEntries.add(Entry(DateUtils.getToday().minus(i), value)) } habit.recompute() screen.refresh() } enum class Message { COULD_NOT_EXPORT } interface Screen { fun showEditHabitScreen(habit: Habit) fun showMessage(m: Message?) fun showSendFileScreen(filename: String) fun showDeleteConfirmationScreen(callback: OnConfirmedCallback) fun close() fun refresh() } interface System { fun getCSVOutputDir(): File } }
gpl-3.0
03b3ba6fe118a359bdcb99006b765979
33.122449
111
0.669258
4.270754
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/completion/contributors/FirSuperEntryContributor.kt
4
2077
// 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.completion.contributors import com.intellij.codeInsight.lookup.LookupElementBuilder import org.jetbrains.kotlin.idea.completion.context.FirBasicCompletionContext import org.jetbrains.kotlin.idea.completion.context.FirSuperTypeCallNameReferencePositionContext import org.jetbrains.kotlin.idea.completion.contributors.helpers.FirSuperEntriesProvider.getSuperClassesAvailableForSuperCall import org.jetbrains.kotlin.idea.completion.contributors.helpers.SuperCallLookupObject import org.jetbrains.kotlin.idea.completion.contributors.helpers.SuperCallInsertionHandler import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.Name internal class FirSuperEntryContributor( basicContext: FirBasicCompletionContext, priority: Int, ) : FirCompletionContributorBase<FirSuperTypeCallNameReferencePositionContext>(basicContext, priority) { override fun KtAnalysisSession.complete(positionContext: FirSuperTypeCallNameReferencePositionContext) { getSuperClassesAvailableForSuperCall(positionContext.nameExpression).forEach { superType -> val tailText = superType.classIdIfNonLocal?.asString()?.let { "($it)" } LookupElementBuilder.create(SuperLookupObject(superType.name, superType.classIdIfNonLocal), superType.name.asString()) .withTailText(tailText) .withInsertHandler(SuperCallInsertionHandler) .let { sink.addElement(it) } } } } private class SuperLookupObject(val className: Name, val classId: ClassId?) : SuperCallLookupObject { override val replaceTo: String get() = when { classId != null -> "${classId.asSingleFqName().asString()}>" else -> "${className.asString()}>" } override val shortenReferencesInReplaced: Boolean get() = classId != null }
apache-2.0
f277fc92706ac935de1af0ba941c8132
50.925
158
0.772749
5.004819
false
false
false
false
android/snippets
slice/src/main/java/com/example/android/slice/kotlin/MySliceProvider.kt
1
8865
/* * Copyright 2018 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 com.example.android.slice.kotlin import android.app.PendingIntent import android.net.Uri import androidx.core.graphics.drawable.IconCompat import androidx.slice.Slice import androidx.slice.SliceProvider import androidx.slice.builders.ListBuilder import androidx.slice.builders.ListBuilder.LARGE_IMAGE import androidx.slice.builders.SliceAction import androidx.slice.builders.cell import androidx.slice.builders.gridRow import androidx.slice.builders.header import androidx.slice.builders.inputRange import androidx.slice.builders.list import androidx.slice.builders.row import androidx.slice.builders.seeMoreRow import androidx.slice.core.SliceHints import androidx.slice.core.SliceHints.ICON_IMAGE import com.example.android.snippets.R class MySliceProvider : SliceProvider() { var isConnected: Boolean = false lateinit var wifiTogglePendingIntent: PendingIntent lateinit var wifiUri: Uri lateinit var seeAllNetworksPendingIntent: PendingIntent lateinit var takeNoteIntent: PendingIntent lateinit var voiceNoteIntent: PendingIntent lateinit var cameraNoteIntent: PendingIntent lateinit var pendingIntent: PendingIntent lateinit var intent1: PendingIntent lateinit var intent2: PendingIntent lateinit var intent3: PendingIntent lateinit var intent4: PendingIntent lateinit var icon: IconCompat lateinit var image1: IconCompat lateinit var image2: IconCompat lateinit var image3: IconCompat lateinit var image4: IconCompat lateinit var volumeChangedPendingIntent: PendingIntent lateinit var wifiSettingsPendingIntent: PendingIntent override fun onBindSlice(sliceUri: Uri): Slice? { return null } override fun onCreateSliceProvider(): Boolean { return false } // [START create_slice_with_header] fun createSliceWithHeader(sliceUri: Uri) = list(context, sliceUri, ListBuilder.INFINITY) { setAccentColor(0xff0F9D) // Specify color for tinting icons header { title = "Get a ride" subtitle = "Ride in 4 min" summary = "Work in 1 hour 45 min | Home in 12 min" } row { title = "Home" subtitle = "12 miles | 12 min | $9.00" addEndItem( IconCompat.createWithResource(context, R.drawable.ic_home), ListBuilder.ICON_IMAGE ) } } // [END create_slice_with_header] // [START create_slice_with_action_in_header] fun createSliceWithActionInHeader(sliceUri: Uri): Slice { // Construct our slice actions. val noteAction = SliceAction.create( takeNoteIntent, IconCompat.createWithResource(context, R.drawable.ic_pencil), ICON_IMAGE, "Take note" ) val voiceNoteAction = SliceAction.create( voiceNoteIntent, IconCompat.createWithResource(context, R.drawable.ic_mic), ICON_IMAGE, "Take voice note" ) val cameraNoteAction = SliceAction.create( cameraNoteIntent, IconCompat.createWithResource(context, R.drawable.ic_camera), ICON_IMAGE, "Create photo note" ) // Construct the list. return list(context, sliceUri, ListBuilder.INFINITY) { setAccentColor(0xfff4b4) // Specify color for tinting icons header { title = "Create new note" subtitle = "Easily done with this note taking app" } addAction(noteAction) addAction(voiceNoteAction) addAction(cameraNoteAction) } } // [END create_slice_with_action_in_header] // [START create_action_with_action_in_row] fun createActionWithActionInRow(sliceUri: Uri): Slice { // Primary action - open wifi settings. val wifiAction = SliceAction.create( wifiSettingsPendingIntent, IconCompat.createWithResource(context, R.drawable.ic_wifi), ICON_IMAGE, "Wi-Fi Settings" ) // Toggle action - toggle wifi. val toggleAction = SliceAction.createToggle( wifiTogglePendingIntent, "Toggle Wi-Fi", isConnected /* isChecked */ ) // Create the parent builder. return list(context, wifiUri, ListBuilder.INFINITY) { setAccentColor(0xff4285) // Specify color for tinting icons / controls. row { title = "Wi-Fi" primaryAction = wifiAction addEndItem(toggleAction) } } } // [END create_action_with_action_in_row] // [START create_slice_with_gridrow] fun createSliceWithGridRow(sliceUri: Uri): Slice { // Create the parent builder. return list(context, sliceUri, ListBuilder.INFINITY) { header { title = "Famous restaurants" primaryAction = SliceAction.create( pendingIntent, icon, ListBuilder.ICON_IMAGE, "Famous restaurants" ) } gridRow { cell { addImage(image1, LARGE_IMAGE) addTitleText("Top Restaurant") addText("0.3 mil") contentIntent = intent1 } cell { addImage(image2, LARGE_IMAGE) addTitleText("Fast and Casual") addText("0.5 mil") contentIntent = intent2 } cell { addImage(image3, LARGE_IMAGE) addTitleText("Casual Diner") addText("0.9 mi") contentIntent = intent3 } cell { addImage(image4, LARGE_IMAGE) addTitleText("Ramen Spot") addText("1.2 mi") contentIntent = intent4 } } } } // [END create_slice_with_gridrow] // [START create_slice_with_range] fun createSliceWithRange(sliceUri: Uri): Slice { return list(context, sliceUri, ListBuilder.INFINITY) { inputRange { title = "Ring Volume" inputAction = volumeChangedPendingIntent max = 100 value = 30 } } } // [END create_slice_with_range] // [START create_slice_showing_loading] fun createSliceShowingLoading(sliceUri: Uri): Slice { // We’re waiting to load the time to work so indicate that on the slice by // setting the subtitle with the overloaded method and indicate true. return list(context, sliceUri, ListBuilder.INFINITY) { row { title = "Ride to work" setSubtitle(null, true) addEndItem(IconCompat.createWithResource(context, R.drawable.ic_work), ICON_IMAGE) } } } // [END create_slice_showing_loading] // [START see_more_action] fun seeMoreActionSlice(sliceUri: Uri) = list(context, sliceUri, ListBuilder.INFINITY) { // [START_EXCLUDE] // [END_EXCLUDE] setSeeMoreAction(seeAllNetworksPendingIntent) // [START_EXCLUDE] // [END_EXCLUDE] } // [END see_more_action] // [START see_more_row] fun seeMoreRowSlice(sliceUri: Uri) = list(context, sliceUri, ListBuilder.INFINITY) { // [START_EXCLUDE] // [END_EXCLUDE] seeMoreRow { title = "See all available networks" addEndItem( IconCompat.createWithResource(context, R.drawable.ic_right_caret), ICON_IMAGE ) primaryAction = SliceAction.create( seeAllNetworksPendingIntent, IconCompat.createWithResource(context, R.drawable.ic_wifi), ListBuilder.ICON_IMAGE, "Wi-Fi Networks" ) } } // [END see_more_row] }
apache-2.0
59a6643dfb5fb00ea385c101fed9e2ec
34.598394
98
0.59393
4.788223
false
false
false
false
tateisu/SubwayTooter
sample_apng/src/main/java/jp/juggler/apng/sample/ActViewer.kt
1
3613
package jp.juggler.apng.sample import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.os.Bundle import android.util.Log import android.view.View import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import jp.juggler.apng.ApngFrames import kotlinx.coroutines.* import java.io.File import java.io.FileOutputStream import kotlin.coroutines.CoroutineContext class ActViewer : AppCompatActivity() , CoroutineScope { companion object { const val TAG="ActViewer" const val EXTRA_RES_ID = "res_id" const val EXTRA_CAPTION = "caption" fun open(context : Context, resId : Int, caption : String) { val intent = Intent(context, ActViewer::class.java) intent.putExtra(EXTRA_RES_ID, resId) intent.putExtra(EXTRA_CAPTION, caption) context.startActivity(intent) } } private lateinit var apngView : ApngView private lateinit var tvError : TextView private lateinit var activityJob: Job override val coroutineContext: CoroutineContext get() = Dispatchers.Main + activityJob override fun onCreate(savedInstanceState : Bundle?) { activityJob = Job() super.onCreate(savedInstanceState) val intent = this.intent val resId = intent.getIntExtra(EXTRA_RES_ID, 0) this.title = intent.getStringExtra(EXTRA_CAPTION) ?: "?" setContentView(R.layout.act_apng_view) this.apngView = findViewById(R.id.apngView) this.tvError = findViewById(R.id.tvError) apngView.setOnLongClickListener { val apngFrames = apngView.apngFrames if( apngFrames != null ){ save(apngFrames) } return@setOnLongClickListener true } launch{ var apngFrames : ApngFrames? = null try { apngFrames = withContext(Dispatchers.IO) { try { ApngFrames.parse( 1024, debug = true ){resources?.openRawResource(resId)} } catch(ex : Throwable) { ex.printStackTrace() null } } apngView.visibility = View.VISIBLE tvError.visibility = View.GONE apngView.apngFrames = apngFrames apngFrames = null } catch(ex : Throwable) { ex.printStackTrace() Log.e(ActList.TAG, "load error: ${ex.javaClass.simpleName} ${ex.message}") val message = "%s %s".format(ex.javaClass.simpleName, ex.message) if(! isDestroyed) { apngView.visibility = View.GONE tvError.visibility = View.VISIBLE tvError.text = message } }finally{ apngFrames?.dispose() } } } override fun onDestroy() { super.onDestroy() apngView.apngFrames?.dispose() activityJob.cancel() } private fun save(apngFrames:ApngFrames){ val title = this.title launch(Dispatchers.IO){ //deprecated in Android 10 (API level 29) //val dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) val dir = getExternalFilesDir(null) if(dir==null){ Log.e(TAG, "getExternalFilesDir(null) returns null.") return@launch } dir.mkdirs() if(! dir.exists() ) { Log.e(TAG, "Directory not exists: $dir") return@launch } val frames = apngFrames.frames if( frames == null ){ Log.e(TAG, "missing frames") return@launch } var i=0 for( f in frames) { Log.d(TAG, "$title[$i] timeWidth=${f.timeWidth}") val bitmap = f.bitmap FileOutputStream( File(dir,"${title}_${i}.png")).use{ fo -> bitmap.compress (Bitmap.CompressFormat.PNG,100,fo) } ++i } } } }
apache-2.0
c86e9ac78c989ce6bfd41d18d85e9abd
23.638298
92
0.657625
3.122731
false
false
false
false
cbeust/klaxon
klaxon/src/main/kotlin/com/beust/klaxon/KlaxonParser.kt
1
7702
package com.beust.klaxon import com.beust.klaxon.token.* import java.io.InputStream import java.io.Reader import java.io.StringReader import java.nio.charset.Charset internal class KlaxonParser( private val pathMatchers: List<PathMatcher>, private val passedLexer: Lexer?, private val streaming: Boolean ) : Parser { override fun parse(rawValue: StringBuilder): Any = StringReader(rawValue.toString()).use { parse(it) } override fun parse(inputStream: InputStream, charset: Charset): Any { return parse(inputStream.reader(charset)) } override fun parse(reader: Reader): Any { return if (streaming) partialParseLoop(stateMachine, (reader as JsonReader).reader) else fullParseLoop(stateMachine, reader) } /** * A loop that ends either on an EOF or a closing brace or bracket (used in streaming mode). */ private fun partialParseLoop(sm: StateMachine, reader: Reader): Any { val lexer = passedLexer ?: Lexer(reader) var world = World(Status.INIT, pathMatchers) var wasNested: Boolean if (lexer.peek() is COMMA) lexer.nextToken() do { val token = lexer.nextToken() log("Token: $token") wasNested = world.isNestedStatus() world = sm.next(world, token) } while (wasNested || (token !is RIGHT_BRACE && token !is RIGHT_BRACKET && token !is EOF ) ) return world.popValue() as JsonBase } /** * A loop that only ends on EOF (used in non streaming mode). */ private fun fullParseLoop(sm: StateMachine, reader: Reader): Any { val lexer = passedLexer ?: Lexer(reader) var world = World(Status.INIT, pathMatchers) do { val token = lexer.nextToken() log("Token: $token") world.index = lexer.index world.line = lexer.line world = sm.next(world, token) } while (token !is EOF) return world.result!! } // // Initialize the state machine // private val stateMachine = StateMachine(streaming) init { with(stateMachine) { put( Status.INIT, VALUE_TYPE.tokenType, { world: World, token: Token -> world.pushAndSet(Status.IN_FINISHED_VALUE, (token as Value<*>).value!!) }) put( Status.INIT, LEFT_BRACE.tokenType, { world: World, _: Token -> world.pushAndSet(Status.IN_OBJECT, JsonObject()) }) put( Status.INIT, LEFT_BRACKET.tokenType, { world: World, _: Token -> world.pushAndSet(Status.IN_ARRAY, JsonArray<Any>()) }) // else error put( Status.IN_FINISHED_VALUE, EOF.tokenType, { world: World, _: Token -> world.result = world.popValue() world }) // else error put( Status.IN_OBJECT, COMMA.tokenType, { world: World, _: Token -> world.foundValue() world }) put( Status.IN_OBJECT, VALUE_TYPE.tokenType, { world: World, token: Token -> world.pushAndSet(Status.PASSED_PAIR_KEY, (token as Value<*>).value!!) }) put( Status.IN_OBJECT, RIGHT_BRACE.tokenType, { world: World, _: Token -> world.foundValue() with(world) { status = if (hasValues()) { popStatus() popValue() peekStatus() } else { Status.IN_FINISHED_VALUE } this } }) put( Status.PASSED_PAIR_KEY, COLON.tokenType, { world: World, _: Token -> world }) put( Status.PASSED_PAIR_KEY, VALUE_TYPE.tokenType, { world: World, token: Token -> with(world) { popStatus() val key = popValue() if (key !is String) { throw KlaxonException("Object keys must be strings, got: $key") } parent = getFirstObject() parent[key] = (token as Value<*>).value status = peekStatus() this } }) put( Status.PASSED_PAIR_KEY, LEFT_BRACKET.tokenType, { world: World, _: Token -> with(world) { popStatus() val key = popValue() if (key !is String) { throw KlaxonException("Object keys must be strings, got: $key") } parent = getFirstObject() val newArray = JsonArray<Any>() parent[key] = newArray pushAndSet(Status.IN_ARRAY, newArray) } }) put( Status.PASSED_PAIR_KEY, LEFT_BRACE.tokenType, { world: World, _: Token -> with(world) { popStatus() val key = popValue() if (key !is String) { throw KlaxonException("Object keys must be strings, got: $key") } parent = getFirstObject() val newObject = JsonObject() parent[key] = newObject pushAndSet(Status.IN_OBJECT, newObject) } }) // else error put( Status.IN_ARRAY, COMMA.tokenType, { world: World, _: Token -> world }) put( Status.IN_ARRAY, VALUE_TYPE.tokenType, { world: World, token: Token -> val value = world.getFirstArray() value.add((token as Value<*>).value) world }) put( Status.IN_ARRAY, RIGHT_BRACKET.tokenType, { world: World, _: Token -> world.foundValue() with(world) { status = if (hasValues()) { popStatus() popValue() peekStatus() } else { Status.IN_FINISHED_VALUE } this } }) put( Status.IN_ARRAY, LEFT_BRACE.tokenType, { world: World, _: Token -> val value = world.getFirstArray() val newObject = JsonObject() value.add(newObject) world.pushAndSet(Status.IN_OBJECT, newObject) }) put( Status.IN_ARRAY, LEFT_BRACKET.tokenType, { world: World, _: Token -> val value = world.getFirstArray() val newArray = JsonArray<Any>() value.add(newArray) world.pushAndSet(Status.IN_ARRAY, newArray) }) } // else error } private fun log(s: String) { if (Debug.verbose) { println("[Parser] $s") } } }
apache-2.0
c6b5df4109da64fe8c55c2e389ace5a5
32.055794
96
0.45274
5.12783
false
false
false
false
georocket/georocket
src/test/kotlin/io/georocket/util/CoordinateTransformerTest.kt
1
1758
package io.georocket.util import org.geotools.referencing.CRS import org.junit.Assert import org.junit.Test /** * Test the [CoordinateTransformer] * @author Tim Hellhake */ class CoordinateTransformerTest { /** * Test transformation with EPSG code * @throws Exception if something has happened */ @Test @Throws(Exception::class) fun testEPSG() { val crs = CRS.decode("EPSG:31467") val transformer = CoordinateTransformer(crs) val source = doubleArrayOf(3477534.683, 5605739.857) val destination = doubleArrayOf(8.681739535269804, 50.58691850210496) testTransformation(transformer, source, destination) } /** * Test transformation with WKT code * @throws Exception if something has happened */ @Test @Throws(Exception::class) fun testWKT() { val crs = CRS.decode("EPSG:31467") val wktCrs = CoordinateTransformer.decode(crs.toWKT()) val transformer = CoordinateTransformer(wktCrs) val source = doubleArrayOf(3477534.683, 5605739.857) val destination = doubleArrayOf(8.681739535269804, 50.58691850210496) testTransformation(transformer, source, destination) } /** * Test transformation * @param transformer the transformer * @param source the source coordinates * @param destination the expected destination coordinates in * [DefaultGeographicCRS.WGS84] * @throws Exception if something has happened */ @Throws(Exception::class) fun testTransformation( transformer: CoordinateTransformer, source: DoubleArray?, destination: DoubleArray ) { val transformed = transformer.transform(source!!, 2) Assert.assertEquals(destination[0], transformed!![0], 0.00001) Assert.assertEquals(destination[1], transformed[1], 0.00001) } }
apache-2.0
809f4ce6ec87f5286dfa7766f9a49c2d
29.310345
73
0.724687
3.915367
false
true
false
false
googlecodelabs/tv-recommendations-kotlin
step_final/src/main/java/com/android/tv/classics/utils/TvLauncherUtils.kt
1
20408
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.tv.classics.utils import android.annotation.SuppressLint import android.content.ContentResolver import android.content.Context import android.content.res.Resources import android.graphics.drawable.Drawable import android.net.Uri import android.util.Log import android.util.Rational import android.util.Size import androidx.annotation.RequiresApi import androidx.tvprovider.media.tv.PreviewChannel import androidx.tvprovider.media.tv.PreviewChannelHelper import androidx.tvprovider.media.tv.PreviewProgram import androidx.tvprovider.media.tv.TvContractCompat import com.android.tv.classics.models.TvMediaMetadata import androidx.tvprovider.media.tv.WatchNextProgram import com.android.tv.classics.R import com.android.tv.classics.models.TvMediaCollection /** Collection of static methods used to handle Android TV Home Screen Launcher operations */ @RequiresApi(26) @SuppressLint("RestrictedApi") class TvLauncherUtils private constructor() { companion object { private val TAG = TvLauncherUtils::class.java.simpleName /** Helper function used to get the URI of something from the resources folder */ fun resourceUri(resources: Resources, id: Int): Uri = Uri.Builder() .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE) .authority(resources.getResourcePackageName(id)) .appendPath(resources.getResourceTypeName(id)) .appendPath(resources.getResourceEntryName(id)) .build() /** * Parse an aspect ratio constant into the equivalent rational number. For example, * [TvContractCompat.PreviewPrograms.ASPECT_RATIO_16_9] becomes `Rational(16, 9)`. The * constant must be one of ASPECT_RATIO_* in [TvContractCompat.PreviewPrograms]. */ fun parseAspectRatio(ratioConstant: Int): Rational = when(ratioConstant) { TvContractCompat.PreviewPrograms.ASPECT_RATIO_16_9 -> Rational(16, 9) TvContractCompat.PreviewPrograms.ASPECT_RATIO_1_1 -> Rational(1, 1) TvContractCompat.PreviewPrograms.ASPECT_RATIO_2_3 -> Rational(2, 3) TvContractCompat.PreviewPrograms.ASPECT_RATIO_3_2 -> Rational(3, 2) TvContractCompat.PreviewPrograms.ASPECT_RATIO_4_3 -> Rational(4, 3) TvContractCompat.PreviewPrograms.ASPECT_RATIO_MOVIE_POSTER -> Rational(1000, 1441) else -> throw IllegalArgumentException( "Constant must be one of ASPECT_RATIO_* in TvContractCompat.PreviewPrograms") } /** * Retrieve the preview programs associated with the given channel ID or, if ID is null, * return all programs associated with any channel. */ fun getPreviewPrograms(context: Context, channelId: Long? = null): List<PreviewProgram> { val programs: MutableList<PreviewProgram> = mutableListOf() try { val cursor = context.contentResolver.query( TvContractCompat.PreviewPrograms.CONTENT_URI, PreviewProgram.PROJECTION, null, null, null) if (cursor != null && cursor.moveToFirst()) { do { val program = PreviewProgram.fromCursor(cursor) if (channelId == null || channelId == program.channelId) { programs.add(program) } } while (cursor.moveToNext()) } cursor?.close() } catch (exc: IllegalArgumentException) { Log.e(TAG, "Error retrieving preview programs", exc) } return programs } /** Retrieve all programs in watch next row that are ours */ fun getWatchNextPrograms(context: Context): List<WatchNextProgram> { val programs: MutableList<WatchNextProgram> = mutableListOf() try { val cursor = context.contentResolver.query( TvContractCompat.WatchNextPrograms.CONTENT_URI, WatchNextProgram.PROJECTION, null, null, null) if (cursor != null && cursor.moveToFirst()) { do { programs.add(WatchNextProgram.fromCursor(cursor)) } while (cursor.moveToNext()) } cursor?.close() } catch (exc: IllegalArgumentException) { Log.e(TAG, "Error retrieving Watch Next programs", exc) } return programs } /** Remove a program given a [TvMediaMetadata] object */ @Synchronized fun removeProgram(context: Context, metadata: TvMediaMetadata): Long? { Log.d(TAG, "Removing content from watch next: $metadata") // First, get all the programs from all of our channels val allPrograms = getPreviewPrograms(context) // Now find the program with the matching content ID for our metadata // Note that we are only getting the first match, this is because in our data models // we only allow for a program to be in one "collection" (aka channel) but nothing // prevents more than one program added to the content provider sharing content ID by // adding the same program to multiple channels val foundProgram = allPrograms.find { it.contentId == metadata.id } if (foundProgram == null) Log.e(TAG, "No program found with content ID ${metadata.id}") // Use the found program's URI to delete it from the content resolver return foundProgram?.let { PreviewChannelHelper(context).deletePreviewProgram(it.id) Log.d(TAG, "Program successfully removed from home screen") it.id } } /** * Insert or update a channel given a [TvMediaCollection] object. Setting the argument * [clearPrograms] to true makes sure that the channel end up with only the items in * the [metadatas] argument. */ @Synchronized fun upsertChannel( context: Context, collection: TvMediaCollection, metadatas: List<TvMediaMetadata>, clearPrograms: Boolean = false ): Long? { // Retrieve the app host URL from our string resources val host = context.getString(R.string.host_name) // Retrieve a list of all previously created channels val allChannels: List<PreviewChannel> = try { PreviewChannelHelper(context).allChannels } catch (exc: IllegalArgumentException) { listOf() } val channelLogoUri = collection.artUri ?: resourceUri(context.resources, R.mipmap.ic_channel_logo) // This must match the desired intent filter in the manifest for VIEW intent action val appUri = Uri.parse("https://$host/channel/${collection.id}") // If we already have a channel with this ID, use it as a base for updated channel // This is the only way to set the internal ID field when using [PreviewChannel.Builder] // NOTE: This means that any fields not set in the updated channel that were set in the // existing channel will be preserved val existingChannel = allChannels.find { it.internalProviderId == collection.id } // TODO: Step 1 create or find an existing channel. val channelBuilder = if (existingChannel == null) { PreviewChannel.Builder() } else { PreviewChannel.Builder(existingChannel) } // TODO: End of Step 1. // Build an updated channel object and add our metadata // TODO: Step 2 add collection metadata and build channel object. val updatedChannel = channelBuilder .setInternalProviderId(collection.id) .setLogo(channelLogoUri) .setAppLinkIntentUri(appUri) .setDisplayName(collection.title) .setDescription(collection.description) .build() // TODO: End of Step 2. // Check if a channel with a matching ID already exists val channelId = if (existingChannel != null) { // Delete all the programs from existing channel if requested // NOTE: This is in general a bad practice, since there could be metadata loss such // as playback position, interaction count, etc. if (clearPrograms) { // To delete all programs from a channel, we can build a special URI that // references all programs associated with a channel and delete just that one val channelPrograms = TvContractCompat.buildPreviewProgramsUriForChannel(existingChannel.id) context.contentResolver.delete(channelPrograms, null, null) } // Update channel in the system's content provider // TODO: Step 3.1 update an existing channel. PreviewChannelHelper(context) .updatePreviewChannel(existingChannel.id, updatedChannel) Log.d(TAG, "Updated channel ${existingChannel.id}") // Return the existing channel's ID existingChannel.id // TODO: End of Step 3.1. } else { // Insert channel, return null if URI in content provider is null try { // TODO: Step 3.2 publish a channel. val channelId = PreviewChannelHelper(context).publishChannel(updatedChannel) Log.d(TAG, "Published channel $channelId") channelId // TODO: End of Step 3.2. } catch (exc: Throwable) { // Early exit: return null if we couldn't insert the channel Log.e(TAG, "Unable to publish channel", exc) return null } } // If it's the first channel being shown, make it the app's default channel // TODO: Step 4 make default channel visible. if(allChannels.none { it.isBrowsable }) { TvContractCompat.requestChannelBrowsable(context, channelId) } // TODO: End of Step 4. // Retrieve programs already added to this channel, if any val existingProgramList = getPreviewPrograms(context, channelId) // Create a list of programs from the content URIs, adding as much metadata as // possible for each piece of content. The more metadata added, the better the // content will be presented in the user's home screen. metadatas.forEach { metadata -> // If we already have a program with this ID, use it as a base for updated program // This is the only way to set the internal ID field when using the builder // NOTE: This means that any fields not set in the updated program that were set in // the existing program will be preserved // TODO: Step 7 create or find an existing preview program. val existingProgram = existingProgramList.find { it.contentId == metadata.id } val programBuilder = if (existingProgram == null) { PreviewProgram.Builder() } else { PreviewProgram.Builder(existingProgram) } // TODO: End of Step 7. // Copy all metadata into our program builder // TODO: Step 8 build preview program. val updatedProgram = programBuilder.also { metadata.copyToBuilder(it) } // Set the same channel ID in all programs .setChannelId(channelId) // This must match the desired intent filter in the manifest for VIEW action .setIntentUri(Uri.parse("https://$host/program/${metadata.id}")) // Build the program at once .build() // TODO: End of step 8. // Insert new program into the channel or update if another one with same ID exists // TODO: Step 9 add preview program to channel. try { if (existingProgram == null) { PreviewChannelHelper(context).publishPreviewProgram(updatedProgram) Log.d(TAG, "Inserted program into channel: $updatedProgram") } else { PreviewChannelHelper(context) .updatePreviewProgram(existingProgram.id, updatedProgram) Log.d(TAG, "Updated program in channel: $updatedProgram") } } catch (exc: IllegalArgumentException) { Log.e(TAG, "Unable to add program: $updatedProgram", exc) } // TODO: End of step 9. } // Return ID of the created channel return channelId } /** Remove a [TvMediaCollection] object from the channel list */ @Synchronized fun removeChannel(context: Context, collection: TvMediaCollection): Long? { Log.d(TAG, "Removing channel from home screen: $collection") // TODO: step 6 remove a channel. // First, get all the channels added to the home screen val allChannels = PreviewChannelHelper(context).allChannels // Now find the channel with the matching content ID for our collection val foundChannel = allChannels.find { it.internalProviderId == collection.id } if (foundChannel == null) Log.e(TAG, "No channel with ID ${collection.id}") // Use the found channel's ID to delete it from the content resolver return foundChannel?.let { PreviewChannelHelper(context).deletePreviewChannel(it.id) Log.d(TAG, "Channel successfully removed from home screen") // Remove all of the channel programs as well val channelPrograms = TvContractCompat.buildPreviewProgramsUriForChannel(it.id) context.contentResolver.delete(channelPrograms, null, null) // Return the ID of the channel removed it.id } // TODO: End of step 6. } /** Insert or update a [TvMediaMetadata] into the watch next row */ @Synchronized fun upsertWatchNext(context: Context, metadata: TvMediaMetadata): Long? { Log.d(TAG, "Adding program to watch next row: $metadata") // If we already have a program with this ID, use it as a base for updated program val existingProgram = getWatchNextPrograms(context).find { it.contentId == metadata.id } val programBuilder = if (existingProgram == null) { WatchNextProgram.Builder() } else { WatchNextProgram.Builder(existingProgram) }.also { metadata.copyToBuilder(it) } // Required for CONTINUE program type: set last engagement time // TODO: step 13 build a watch next program. programBuilder.setLastEngagementTimeUtcMillis(System.currentTimeMillis()) // Set the specific intent for this program in the watch next row // Watch next type is inferred from media playback using the following rules: // 1. NEXT - If position is NULL // 2. CONTINUE - If position not NULL AND duration is not NULL // 3. UNKNOWN - If position < 0 OR (position is not NULL AND duration is NULL) programBuilder.setWatchNextType(metadata.playbackPositionMillis?.let { position -> if (position > 0 && metadata.playbackDurationMillis?.let { it > 0 } == true) { Log.d(TAG, "Inferred watch next type: CONTINUE") TvContractCompat.WatchNextPrograms.WATCH_NEXT_TYPE_CONTINUE } else { Log.d(TAG, "Inferred watch next type: UNKNOWN") WatchNextProgram.WATCH_NEXT_TYPE_UNKNOWN } } ?: TvContractCompat.WatchNextPrograms.WATCH_NEXT_TYPE_NEXT) // This must match the desired intent filter in the manifest for VIEW intent action programBuilder.setIntentUri(Uri.parse( "https://${context.getString(R.string.host_name)}/program/${metadata.id}")) // Build the program with all the metadata val updatedProgram = programBuilder.build() // TODO: End of step 13. // Check if a program matching this one already exists in the watch next row return if (existingProgram != null) { // If the program is already in the watch next row, update it // TODO: step 14.2 update a watch next program. PreviewChannelHelper(context) .updateWatchNextProgram(updatedProgram, existingProgram.id) Log.d(TAG, "Updated program in watch next row: $updatedProgram") existingProgram.id // TODO: End of step 14.2. } else { // Otherwise build the program and insert it into the channel try { // TODO: step 14.1 publish a watch next program val programId = PreviewChannelHelper(context) .publishWatchNextProgram(updatedProgram) Log.d(TAG, "Added program to watch next row: $updatedProgram") programId // TODO: End of step 14.1. } catch (exc: IllegalArgumentException) { Log.e(TAG, "Unable to add program to watch next row") null } } } /** Remove a [TvMediaMetadata] object from the watch next row */ @Synchronized fun removeFromWatchNext(context: Context, metadata: TvMediaMetadata): Uri? { Log.d(TAG, "Removing content from watch next: $metadata") // First, get all the programs in the watch next row val allPrograms = getWatchNextPrograms(context) // Now find the program with the matching content ID for our metadata val foundProgram = allPrograms.find { it.contentId == metadata.id } if (foundProgram == null) Log.e(TAG, "No program found in Watch Next with content ID ${metadata.id}") // Use the found program's URI to delete it from the content resolver return foundProgram?.let { // TODO: step 15 remove program. val programUri = TvContractCompat.buildWatchNextProgramUri(it.id) val deleteCount = context.contentResolver.delete( programUri, null, null) // TODO: End of step 15. if (deleteCount == 1) { Log.d(TAG, "Content successfully removed from watch next") programUri } else { Log.e(TAG, "Content failed to be removed from watch next " + "(delete count $deleteCount)") null } } } } }
apache-2.0
af3dc9f02b4d422a285c7c2f4eb24c85
46.573427
100
0.590455
5.25573
false
false
false
false
PaulWoitaschek/MaterialAudiobookPlayer
app/src/main/java/de/ph1b/audiobook/uitools/CoverFromDiscCollector.kt
1
3366
package de.ph1b.audiobook.uitools import android.app.ActivityManager import android.graphics.Bitmap import com.squareup.picasso.Picasso import de.ph1b.audiobook.data.Book import de.ph1b.audiobook.data.Chapter import de.ph1b.audiobook.misc.FileRecognition import de.ph1b.audiobook.misc.coverFile import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.subjects.PublishSubject import timber.log.Timber import java.io.File import java.io.IOException import java.util.UUID import javax.inject.Inject import javax.inject.Singleton /** * Class for retrieving covers from disc. */ @Singleton class CoverFromDiscCollector @Inject constructor( private val activityManager: ActivityManager, private val imageHelper: ImageHelper ) { private val picasso = Picasso.get() private val coverChangedSubject = PublishSubject.create<UUID>() /** Find and stores covers for each book */ suspend fun findCovers(books: List<Book>) { books.forEach { findCoverForBook(it) } } private suspend fun findCoverForBook(book: Book) { val coverFile = book.coverFile() if (coverFile.exists()) return val foundOnDisc = findAndSaveCoverFromDisc(book) if (foundOnDisc) return findAndSaveCoverEmbedded(book) } private suspend fun findAndSaveCoverEmbedded(book: Book) { getEmbeddedCover(book.content.chapters)?.let { val coverFile = book.coverFile() imageHelper.saveCover(it, coverFile) picasso.invalidate(coverFile) coverChangedSubject.onNext(book.id) } } private suspend fun findAndSaveCoverFromDisc(book: Book): Boolean { if (book.type === Book.Type.COLLECTION_FOLDER || book.type === Book.Type.SINGLE_FOLDER) { val root = File(book.root) if (root.exists()) { val images = root.walk().filter { FileRecognition.imageFilter.accept(it) } getCoverFromDisk(images.toList())?.let { val coverFile = book.coverFile() imageHelper.saveCover(it, coverFile) picasso.invalidate(coverFile) coverChangedSubject.onNext(book.id) return true } } } return false } /** emits the bookId of a cover that has changed */ fun coverChanged(): Observable<UUID> = coverChangedSubject .hide() .observeOn(AndroidSchedulers.mainThread()) /** Find the embedded cover of a chapter */ private fun getEmbeddedCover(chapters: List<Chapter>): Bitmap? { chapters.forEachIndexed { index, (file) -> val cover = imageHelper.getEmbeddedCover(file) if (cover != null || index == 5) return cover } return null } /** Returns the first bitmap that could be parsed from an image file */ private fun getCoverFromDisk(coverFiles: List<File>): Bitmap? { // if there are images, get the first one. val mi = ActivityManager.MemoryInfo() activityManager.getMemoryInfo(mi) val dimen = imageHelper.smallerScreenSize // only read cover if its size is less than a third of the available memory coverFiles.filter { it.length() < (mi.availMem / 3L) }.forEach { try { return picasso.load(it) .resize(dimen, dimen) .onlyScaleDown() .centerCrop() .get() } catch (ex: IOException) { Timber.e(ex, "Error when saving cover $it") } } return null } }
lgpl-3.0
57ce406645c8f68bdaf0d9961653f513
29.6
93
0.695781
4.031138
false
false
false
false
paplorinc/intellij-community
platform/projectModel-impl/src/com/intellij/configurationStore/scheme-impl.kt
1
5337
// 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.configurationStore import com.intellij.openapi.extensions.AbstractExtensionPointBean import com.intellij.openapi.options.* import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtil import com.intellij.project.isDirectoryBased import com.intellij.util.SmartList import com.intellij.util.io.sanitizeFileName import com.intellij.util.isEmpty import com.intellij.util.lang.CompoundRuntimeException import com.intellij.util.xmlb.annotations.Attribute import org.jdom.Element import java.io.OutputStream import java.security.MessageDigest import java.util.concurrent.atomic.AtomicReference import java.util.function.Function typealias SchemeNameToFileName = (name: String) -> String val OLD_NAME_CONVERTER: SchemeNameToFileName = { FileUtil.sanitizeFileName(it, true) } val CURRENT_NAME_CONVERTER: SchemeNameToFileName = { FileUtil.sanitizeFileName(it, false) } val MODERN_NAME_CONVERTER: SchemeNameToFileName = { sanitizeFileName(it) } interface SchemeDataHolder<in T> { /** * You should call updateDigest() after read on init. */ fun read(): Element fun updateDigest(scheme: T) fun updateDigest(data: Element?) } /** * A scheme processor can implement this interface to provide a file extension different from default .xml. * @see SchemeProcessor */ interface SchemeExtensionProvider { /** * @return The scheme file extension **with a leading dot**, for example ".ext". */ val schemeExtension: String } // applicable only for LazySchemeProcessor interface SchemeContentChangedHandler<MUTABLE_SCHEME> { fun schemeContentChanged(scheme: MUTABLE_SCHEME, name: String, dataHolder: SchemeDataHolder<MUTABLE_SCHEME>) } abstract class LazySchemeProcessor<SCHEME, MUTABLE_SCHEME : SCHEME>(private val nameAttribute: String = "name") : SchemeProcessor<SCHEME, MUTABLE_SCHEME>() { open fun getSchemeKey(attributeProvider: Function<String, String?>, fileNameWithoutExtension: String): String? { return attributeProvider.apply(nameAttribute) } abstract fun createScheme(dataHolder: SchemeDataHolder<MUTABLE_SCHEME>, name: String, attributeProvider: Function<in String, String?>, isBundled: Boolean = false): MUTABLE_SCHEME override fun writeScheme(scheme: MUTABLE_SCHEME): Element? = (scheme as SerializableScheme).writeScheme() open fun isSchemeFile(name: CharSequence) = true open fun isSchemeDefault(scheme: MUTABLE_SCHEME, digest: ByteArray) = false open fun isSchemeEqualToBundled(scheme: MUTABLE_SCHEME) = false } class DigestOutputStream(val digest: MessageDigest) : OutputStream() { override fun write(b: Int) { digest.update(b.toByte()) } override fun write(b: ByteArray, off: Int, len: Int) { digest.update(b, off, len) } override fun toString() = "[Digest Output Stream] $digest" } private val sha1Provider = java.security.Security.getProvider("SUN") // sha-1 is enough, sha-256 is slower, see https://www.nayuki.io/page/native-hash-functions-for-java fun createDataDigest(): MessageDigest = MessageDigest.getInstance("SHA-1", sha1Provider) fun Element.digest(): ByteArray { val digest = createDataDigest() serializeElementToBinary(this, DigestOutputStream(digest)) return digest.digest() } abstract class SchemeWrapper<out T>(name: String) : ExternalizableSchemeAdapter(), SerializableScheme { protected abstract val lazyScheme: Lazy<T> val scheme: T get() = lazyScheme.value override fun getSchemeState(): SchemeState = if (lazyScheme.isInitialized()) SchemeState.POSSIBLY_CHANGED else SchemeState.UNCHANGED init { this.name = name } } abstract class LazySchemeWrapper<T>(name: String, dataHolder: SchemeDataHolder<SchemeWrapper<T>>, protected val writer: (scheme: T) -> Element) : SchemeWrapper<T>(name) { protected val dataHolder: AtomicReference<SchemeDataHolder<SchemeWrapper<T>>> = AtomicReference(dataHolder) final override fun writeScheme(): Element { val dataHolder = dataHolder.get() @Suppress("IfThenToElvis") return if (dataHolder == null) writer(scheme) else dataHolder.read() } } class InitializedSchemeWrapper<out T : Scheme>(scheme: T, private val writer: (scheme: T) -> Element) : SchemeWrapper<T>(scheme.name) { override val lazyScheme: Lazy<T> = lazyOf(scheme) override fun writeScheme() = writer(scheme) } fun unwrapState(element: Element, project: Project, iprAdapter: SchemeManagerIprProvider?, schemeManager: SchemeManager<*>): Element? { val data = if (project.isDirectoryBased) element.getChild("settings") else element iprAdapter?.let { it.load(data) schemeManager.reload() } return data } fun wrapState(element: Element, project: Project): Element { if (element.isEmpty() || !project.isDirectoryBased) { element.name = "state" return element } val wrapper = Element("state") wrapper.addContent(element) return wrapper } class BundledSchemeEP : AbstractExtensionPointBean() { @Attribute("path") var path: String? = null } fun SchemeManager<*>.save() { val errors = SmartList<Throwable>() save(errors) CompoundRuntimeException.throwIfNotEmpty(errors) }
apache-2.0
7c93b5f3ce73052a7f7097ca5f4bde1d
34.118421
170
0.750234
4.407102
false
false
false
false
algra/pact-jvm
pact-jvm-model/src/main/kotlin/au/com/dius/pact/model/OptionalBody.kt
1
1848
package au.com.dius.pact.model /** * Class to represent missing, empty, null and present bodies */ data class OptionalBody(val state: State, val value: String? = null) { enum class State { MISSING, EMPTY, NULL, PRESENT } companion object { @JvmStatic fun missing(): OptionalBody { return OptionalBody(State.MISSING) } @JvmStatic fun empty(): OptionalBody { return OptionalBody(State.EMPTY, "") } @JvmStatic fun nullBody(): OptionalBody { return OptionalBody(State.NULL) } @JvmStatic fun body(body: String?): OptionalBody { return when { body == null -> nullBody() body.isEmpty() -> empty() else -> OptionalBody(State.PRESENT, body) } } } fun isMissing(): Boolean { return state == State.MISSING } fun isEmpty(): Boolean { return state == State.EMPTY } fun isNull(): Boolean { return state == State.NULL } fun isPresent(): Boolean { return state == State.PRESENT } fun isNotPresent(): Boolean { return state != State.PRESENT } fun orElse(defaultValue: String): String { return if (state == State.EMPTY || state == State.PRESENT) { this.value!! } else { defaultValue } } fun unwrap(): String { if (isPresent()) { return value!! } else { throw UnwrapMissingBodyException("Failed to unwrap value from a $state body") } } } fun OptionalBody?.isMissing() = this == null || this.isMissing() fun OptionalBody?.isEmpty() = this != null && this.isEmpty() fun OptionalBody?.isNull() = this == null || this.isNull() fun OptionalBody?.isPresent() = this != null && this.isPresent() fun OptionalBody?.isNotPresent() = this == null || this.isNotPresent() fun OptionalBody?.orElse(defaultValue: String) = this?.orElse(defaultValue) ?: defaultValue
apache-2.0
7a77648e7ccfeb05addd6e527e5f0550
21.536585
91
0.630952
4.258065
false
false
false
false
JetBrains/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/WorkspaceBuilderChangeLog.kt
1
9461
// 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 import com.intellij.openapi.diagnostic.logger import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.WorkspaceEntity internal typealias ChangeLog = MutableMap<EntityId, ChangeEntry> class WorkspaceBuilderChangeLog { var modificationCount: Long = 0 internal val changeLog: ChangeLog = LinkedHashMap() internal fun clear() { modificationCount++ changeLog.clear() } internal fun addReplaceEvent( entityId: EntityId, copiedData: WorkspaceEntityData<out WorkspaceEntity>, originalEntity: WorkspaceEntityData<out WorkspaceEntity>, originalParents: Map<ConnectionId, ParentEntityId>, addedChildren: List<Pair<ConnectionId, ChildEntityId>>, removedChildren: Set<Pair<ConnectionId, ChildEntityId>>, parentsMapRes: Map<ConnectionId, ParentEntityId?>, ) { modificationCount++ val existingChange = changeLog[entityId] val replaceEvent = ChangeEntry.ReplaceEntity(originalEntity, originalParents, copiedData, addedChildren, removedChildren.toList(), parentsMapRes) val makeReplaceEvent = { replaceEntity: ChangeEntry.ReplaceEntity -> val addedChildrenSet = addedChildren.toSet() val newAddedChildren = (replaceEntity.newChildren.toSet() - removedChildren + (addedChildrenSet - replaceEntity.removedChildren.toSet())).toList() val newRemovedChildren = (replaceEntity.removedChildren.toSet() - addedChildrenSet + (removedChildren - replaceEntity.newChildren.toSet())).toList() val newChangedParents = (replaceEntity.modifiedParents + parentsMapRes).toMutableMap() originalParents.forEach { (key, value) -> newChangedParents.remove(key, value) } if (originalEntity.equalsIgnoringEntitySource( copiedData) && newAddedChildren.isEmpty() && newRemovedChildren.isEmpty() && newChangedParents.isEmpty()) { null } else ChangeEntry.ReplaceEntity(originalEntity, originalParents, copiedData, newAddedChildren, newRemovedChildren, newChangedParents) } if (existingChange == null) { if (!(originalEntity.equalsIgnoringEntitySource( copiedData) && addedChildren.isEmpty() && removedChildren.isEmpty() && parentsMapRes.isEmpty())) { changeLog[entityId] = replaceEvent } } else { when (existingChange) { is ChangeEntry.AddEntity -> changeLog[entityId] = ChangeEntry.AddEntity(copiedData, entityId.clazz) is ChangeEntry.RemoveEntity -> LOG.error("Trying to update removed entity. Skip change event. $copiedData") is ChangeEntry.ChangeEntitySource -> changeLog[entityId] = ChangeEntry.ReplaceAndChangeSource.from(replaceEvent, existingChange) is ChangeEntry.ReplaceEntity -> { val event = makeReplaceEvent(existingChange) if (event != null) { changeLog[entityId] = event } else { changeLog.remove(entityId) } Unit } is ChangeEntry.ReplaceAndChangeSource -> { val newReplaceEvent = makeReplaceEvent(existingChange.dataChange) if (newReplaceEvent != null) { changeLog[entityId] = ChangeEntry.ReplaceAndChangeSource.from(newReplaceEvent, existingChange.sourceChange) } else { changeLog[entityId] = existingChange.sourceChange } } }.let { } } } internal fun <T : WorkspaceEntity> addAddEvent(pid: EntityId, pEntityData: WorkspaceEntityData<T>) { modificationCount++ // XXX: This check should exist, but some tests fails with it. //if (targetEntityId in it) LOG.error("Trying to add entity again. ") changeLog[pid] = ChangeEntry.AddEntity(pEntityData, pid.clazz) } internal fun <T : WorkspaceEntity> addChangeSourceEvent(entityId: EntityId, copiedData: WorkspaceEntityData<T>, originalSource: EntitySource) { modificationCount++ val existingChange = changeLog[entityId] val changeSourceEvent = ChangeEntry.ChangeEntitySource(originalSource, copiedData) if (existingChange == null) { if (copiedData.entitySource != originalSource) { changeLog[entityId] = changeSourceEvent } } else { when (existingChange) { is ChangeEntry.AddEntity -> changeLog[entityId] = ChangeEntry.AddEntity(copiedData, entityId.clazz) is ChangeEntry.RemoveEntity -> LOG.error("Trying to update removed entity. Skip change event. $copiedData") is ChangeEntry.ChangeEntitySource -> { if (copiedData.entitySource != originalSource) { changeLog[entityId] = changeSourceEvent } else { changeLog.remove(entityId) } Unit } is ChangeEntry.ReplaceEntity -> { if (copiedData.entitySource != originalSource) { changeLog[entityId] = ChangeEntry.ReplaceAndChangeSource.from(existingChange, changeSourceEvent) } Unit } is ChangeEntry.ReplaceAndChangeSource -> { if (copiedData.entitySource != originalSource) { changeLog[entityId] = ChangeEntry.ReplaceAndChangeSource.from(existingChange.dataChange, changeSourceEvent) } else { changeLog[entityId] = existingChange.dataChange } } }.let { } } } internal fun addRemoveEvent(removedEntityId: EntityId, originalData: WorkspaceEntityData<WorkspaceEntity>, oldParents: Map<ConnectionId, ParentEntityId>) { modificationCount++ val existingChange = changeLog[removedEntityId] val removeEvent = ChangeEntry.RemoveEntity(originalData, oldParents, removedEntityId) if (existingChange == null) { changeLog[removedEntityId] = removeEvent } else { when (existingChange) { is ChangeEntry.AddEntity -> changeLog.remove(removedEntityId) is ChangeEntry.ChangeEntitySource -> changeLog[removedEntityId] = removeEvent is ChangeEntry.ReplaceEntity -> changeLog[removedEntityId] = removeEvent is ChangeEntry.ReplaceAndChangeSource -> changeLog[removedEntityId] = removeEvent is ChangeEntry.RemoveEntity -> Unit } } } companion object { val LOG = logger<WorkspaceBuilderChangeLog>() } } internal sealed class ChangeEntry { data class AddEntity(val entityData: WorkspaceEntityData<out WorkspaceEntity>, val clazz: Int) : ChangeEntry() data class RemoveEntity( val oldData: WorkspaceEntityData<out WorkspaceEntity>, val oldParents: Map<ConnectionId, ParentEntityId>, val id: EntityId, ) : ChangeEntry() data class ChangeEntitySource( val originalSource: EntitySource, val newData: WorkspaceEntityData<out WorkspaceEntity> ) : ChangeEntry() /** * Fields about children or parents contain information only about changes on this particular entity. This means, that if some entity * is removed, information about its removal is NOT added to the parent using this mechanism */ data class ReplaceEntity( val oldData: WorkspaceEntityData<out WorkspaceEntity>, val oldParents: Map<ConnectionId, ParentEntityId>, val newData: WorkspaceEntityData<out WorkspaceEntity>, val newChildren: List<Pair<ConnectionId, ChildEntityId>>, val removedChildren: List<Pair<ConnectionId, ChildEntityId>>, val modifiedParents: Map<ConnectionId, ParentEntityId?> ) : ChangeEntry() data class ReplaceAndChangeSource( val dataChange: ReplaceEntity, val sourceChange: ChangeEntitySource, ) : ChangeEntry() { companion object { fun from(dataChange: ReplaceEntity, sourceChange: ChangeEntitySource): ReplaceAndChangeSource { return ReplaceAndChangeSource(dataChange, sourceChange) } } } } internal fun MutableEntityStorageImpl.getOriginalEntityData(id: EntityId): WorkspaceEntityData<*> { return this.changeLog.changeLog[id]?.let { when (it) { is ChangeEntry.ReplaceEntity -> it.oldData is ChangeEntry.AddEntity -> it.entityData is ChangeEntry.ChangeEntitySource -> it.newData is ChangeEntry.RemoveEntity -> it.oldData is ChangeEntry.ReplaceAndChangeSource -> it.dataChange.oldData } }?.clone() ?: this.entityDataByIdOrDie(id).clone() } internal fun MutableEntityStorageImpl.getOriginalParents(id: ChildEntityId): Map<ConnectionId, ParentEntityId> { return this.changeLog.changeLog[id.id]?.let { when (it) { is ChangeEntry.ReplaceEntity -> it.oldParents is ChangeEntry.AddEntity -> this.refs.getParentRefsOfChild(id) is ChangeEntry.ChangeEntitySource -> this.refs.getParentRefsOfChild(id) is ChangeEntry.RemoveEntity -> it.oldParents is ChangeEntry.ReplaceAndChangeSource -> it.dataChange.oldParents } } ?: this.refs.getParentRefsOfChild(id) } internal fun MutableEntityStorageImpl.getOriginalSourceFromChangelog(id: EntityId): EntitySource? { return this.changeLog.changeLog[id]?.let { when (it) { is ChangeEntry.ChangeEntitySource -> it.originalSource is ChangeEntry.ReplaceAndChangeSource -> it.sourceChange.originalSource else -> null } } }
apache-2.0
14ab461dbc0506f974665a12329b357f
39.95671
154
0.699503
4.766247
false
false
false
false
youdonghai/intellij-community
java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/preContracts.kt
1
6523
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInspection.dataFlow import com.intellij.codeInsight.NullableNotNullManager import com.intellij.codeInspection.dataFlow.ContractInferenceInterpreter.negateConstraint import com.intellij.codeInspection.dataFlow.ContractInferenceInterpreter.withConstraint import com.intellij.codeInspection.dataFlow.MethodContract.ValueConstraint.* import com.intellij.codeInspection.dataFlow.instructions.MethodCallInstruction import com.intellij.psi.* import com.siyeh.ig.psiutils.SideEffectChecker /** * @author peter */ interface PreContract { fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock): List<MethodContract> fun negate(): PreContract? = NegatingContract(this) } internal data class KnownContract(val contract: MethodContract) : PreContract { override fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock) = listOf(contract) override fun negate() = negateContract(contract)?.let(::KnownContract) } internal data class DelegationContract(internal val expression: ExpressionRange, internal val negated: Boolean) : PreContract { override fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock): List<MethodContract> { val call = expression.restoreExpression(body()) as PsiMethodCallExpression? ?: return emptyList() val result = call.resolveMethodGenerics() val targetMethod = result.element as PsiMethod? ?: return emptyList() val parameters = targetMethod.parameterList.parameters val arguments = call.argumentList.expressions val varArgCall = MethodCallInstruction.isVarArgCall(targetMethod, result.substitutor, arguments, parameters) val fromDelegate = ControlFlowAnalyzer.getMethodContracts(targetMethod).mapNotNull { dc -> convertDelegatedMethodContract(method, parameters, arguments, varArgCall, dc) } if (NullableNotNullManager.isNotNull(targetMethod)) { return fromDelegate.map { returnNotNull(it) } + listOf(MethodContract(emptyConstraints(method), NOT_NULL_VALUE)) } return fromDelegate } private fun convertDelegatedMethodContract(callerMethod: PsiMethod, targetParameters: Array<PsiParameter>, callArguments: Array<PsiExpression>, varArgCall: Boolean, targetContract: MethodContract): MethodContract? { var answer: Array<MethodContract.ValueConstraint>? = emptyConstraints(callerMethod) for (i in targetContract.arguments.indices) { if (i >= callArguments.size) return null val argConstraint = targetContract.arguments[i] if (argConstraint != ANY_VALUE) { if (varArgCall && i >= targetParameters.size - 1) { if (argConstraint == NULL_VALUE) { return null } break } val argument = callArguments[i] val paramIndex = resolveParameter(callerMethod, argument) if (paramIndex >= 0) { answer = withConstraint(answer, paramIndex, argConstraint) ?: return null } else if (argConstraint != getLiteralConstraint(argument)) { return null } } } val returnValue = if (negated) negateConstraint(targetContract.returnValue) else targetContract.returnValue return answer?.let { MethodContract(it, returnValue) } } private fun emptyConstraints(method: PsiMethod) = MethodContract.createConstraintArray(method.parameterList.parametersCount) private fun returnNotNull(mc: MethodContract) = if (mc.returnValue == THROW_EXCEPTION) mc else MethodContract(mc.arguments, NOT_NULL_VALUE) private fun getLiteralConstraint(argument: PsiExpression) = when (argument) { is PsiLiteralExpression -> ContractInferenceInterpreter.getLiteralConstraint(argument.getFirstChild().node.elementType) else -> null } private fun resolveParameter(method: PsiMethod, expr: PsiExpression): Int { val target = if (expr is PsiReferenceExpression && !expr.isQualified) expr.resolve() else null return if (target is PsiParameter && target.parent === method.parameterList) method.parameterList.getParameterIndex(target) else -1 } } internal data class SideEffectFilter(internal val expressionsToCheck: List<ExpressionRange>, internal val contracts: List<PreContract>) : PreContract { override fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock): List<MethodContract> { if (expressionsToCheck.any { d -> mayHaveSideEffects(body(), d) }) { return emptyList() } return contracts.flatMap { c -> c.toContracts(method, body) } } private fun mayHaveSideEffects(body: PsiCodeBlock, range: ExpressionRange) = range.restoreExpression(body)?.let { SideEffectChecker.mayHaveSideEffects(it) } ?: false } internal data class NegatingContract(internal val negated: PreContract) : PreContract { override fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock) = negated.toContracts(method, body).mapNotNull(::negateContract) } private fun negateContract(c: MethodContract): MethodContract? { val ret = c.returnValue return if (ret == TRUE_VALUE || ret == FALSE_VALUE) MethodContract(c.arguments, negateConstraint(ret)) else null } @Suppress("EqualsOrHashCode") internal data class MethodCallContract(internal val call: ExpressionRange, internal val states: List<List<MethodContract.ValueConstraint>>) : PreContract { override fun hashCode() = call.hashCode() * 31 + states.flatten().map { it.ordinal }.hashCode() override fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock): List<MethodContract> { val target = (call.restoreExpression(body()) as PsiMethodCallExpression?)?.resolveMethod() if (target != null && NullableNotNullManager.isNotNull(target)) { return ContractInferenceInterpreter.toContracts(states.map { it.toTypedArray() }, NOT_NULL_VALUE) } return emptyList() } }
apache-2.0
4c270fce7c51ffb127b2b1cda4f6b2f8
45.928058
155
0.729112
4.930461
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/base/analysis/LibraryDependenciesCache.kt
1
23109
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.base.analysis import com.intellij.ProjectTopics import com.intellij.openapi.Disposable import com.intellij.openapi.application.assertReadAccessAllowed import com.intellij.openapi.application.runReadAction import com.intellij.openapi.components.service import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.progress.ProgressManager.checkCanceled import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.ProjectJdkTable import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.* import com.intellij.openapi.roots.impl.libraries.LibraryEx import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.util.Disposer import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.util.concurrency.annotations.RequiresReadLock import com.intellij.util.containers.MultiMap import com.intellij.workspaceModel.ide.WorkspaceModelChangeListener import com.intellij.workspaceModel.ide.WorkspaceModelTopics import com.intellij.workspaceModel.ide.impl.legacyBridge.module.findModule import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.VersionedStorageChange import com.intellij.workspaceModel.storage.bridgeEntities.ModuleEntity import org.jetbrains.kotlin.idea.base.analysis.libraries.LibraryDependencyCandidate import org.jetbrains.kotlin.idea.base.facet.isHMPPEnabled import org.jetbrains.kotlin.idea.base.projectStructure.* import org.jetbrains.kotlin.idea.base.projectStructure.LibraryDependenciesCache.LibraryDependencies import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.LibraryInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.SdkInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.allSdks import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.checkValidity import org.jetbrains.kotlin.idea.base.util.caching.ModuleEntityChangeListener import org.jetbrains.kotlin.idea.base.util.caching.SynchronizedFineGrainedEntityCache import org.jetbrains.kotlin.idea.caches.project.* import org.jetbrains.kotlin.idea.caches.trackers.ModuleModificationTracker import org.jetbrains.kotlin.idea.configuration.isMavenized import org.jetbrains.kotlin.utils.addToStdlib.safeAs private class LibraryDependencyCandidatesAndSdkInfos( val libraryDependencyCandidates: MutableSet<LibraryDependencyCandidate> = linkedSetOf(), val sdkInfos: MutableSet<SdkInfo> = linkedSetOf() ) { operator fun plusAssign(other: LibraryDependencyCandidatesAndSdkInfos) { libraryDependencyCandidates += other.libraryDependencyCandidates sdkInfos += other.sdkInfos } operator fun plusAssign(libraryDependencyCandidate: LibraryDependencyCandidate) { libraryDependencyCandidates += libraryDependencyCandidate } operator fun plusAssign(sdkInfo: SdkInfo) { sdkInfos += sdkInfo } override fun toString(): String { return "[${Integer.toHexString(System.identityHashCode(this))}] libraryDependencyCandidates: ${ libraryDependencyCandidates.map { it.libraries.map(LibraryInfo::name) } } sdkInfos: ${sdkInfos.map { it.sdk.name }}" } } class LibraryDependenciesCacheImpl(private val project: Project) : LibraryDependenciesCache, Disposable { companion object { fun getInstance(project: Project): LibraryDependenciesCache = project.service() } private val cache = LibraryDependenciesInnerCache() private val moduleDependenciesCache = ModuleDependenciesCache() init { Disposer.register(this, cache) Disposer.register(this, moduleDependenciesCache) } override fun getLibraryDependencies(library: LibraryInfo): LibraryDependencies = cache[library] override fun dispose() = Unit private fun computeLibrariesAndSdksUsedWith(libraryInfo: LibraryInfo): LibraryDependencies { val libraryDependencyCandidatesAndSdkInfos = computeLibrariesAndSdksUsedWithNoFilter(libraryInfo) // Maven is Gradle Metadata unaware, and therefore needs stricter filter. See KTIJ-15758 val libraryDependenciesFilter = if (project.isMavenized) StrictEqualityForPlatformSpecificCandidatesFilter else DefaultLibraryDependenciesFilter union SharedNativeLibraryToNativeInteropFallbackDependenciesFilter val libraries = libraryDependenciesFilter( libraryInfo.platform, libraryDependencyCandidatesAndSdkInfos.libraryDependencyCandidates ).flatMap { it.libraries } return LibraryDependencies(libraryInfo, libraries, libraryDependencyCandidatesAndSdkInfos.sdkInfos.toList()) } //NOTE: used LibraryRuntimeClasspathScope as reference private fun computeLibrariesAndSdksUsedWithNoFilter(libraryInfo: LibraryInfo): LibraryDependencyCandidatesAndSdkInfos { val libraryDependencyCandidatesAndSdkInfos = LibraryDependencyCandidatesAndSdkInfos() val modulesLibraryIsUsedIn = getLibraryUsageIndex().getModulesLibraryIsUsedIn(libraryInfo) for (module in modulesLibraryIsUsedIn) { checkCanceled() libraryDependencyCandidatesAndSdkInfos += moduleDependenciesCache[module] } val filteredLibraries = filterForBuiltins(libraryInfo, libraryDependencyCandidatesAndSdkInfos.libraryDependencyCandidates) return LibraryDependencyCandidatesAndSdkInfos(filteredLibraries, libraryDependencyCandidatesAndSdkInfos.sdkInfos) } /* * When built-ins are created from module dependencies (as opposed to loading them from classloader) * we must resolve Kotlin standard library containing some built-ins declarations in the same * resolver for project as JDK. This comes from the following requirements: * - JvmBuiltins need JDK and standard library descriptors -> resolver for project should be able to * resolve them * - Builtins are created in BuiltinsCache -> module descriptors should be resolved under lock of the * SDK resolver to prevent deadlocks * This means we have to maintain dependencies of the standard library manually or effectively drop * resolver for SDK otherwise. Libraries depend on superset of their actual dependencies because of * the inability to get real dependencies from IDEA model. So moving stdlib with all dependencies * down is a questionable option. */ private fun filterForBuiltins( libraryInfo: LibraryInfo, dependencyLibraries: MutableSet<LibraryDependencyCandidate> ): MutableSet<LibraryDependencyCandidate> { return if (!IdeBuiltInsLoadingState.isFromClassLoader && libraryInfo.isCoreKotlinLibrary(project)) { dependencyLibraries.filterTo(mutableSetOf()) { dep -> dep.libraries.any { it.isCoreKotlinLibrary(project) } } } else { dependencyLibraries } } private fun getLibraryUsageIndex(): LibraryUsageIndex = CachedValuesManager.getManager(project).getCachedValue(project) { CachedValueProvider.Result( LibraryUsageIndex(), ModuleModificationTracker.getInstance(project), LibraryModificationTracker.getInstance(project) ) }!! private inner class LibraryDependenciesInnerCache : SynchronizedFineGrainedEntityCache<LibraryInfo, LibraryDependencies>(project, cleanOnLowMemory = true), LibraryInfoListener, ModuleRootListener, ProjectJdkTable.Listener { override fun subscribe() { val connection = project.messageBus.connect(this) connection.subscribe(LibraryInfoListener.TOPIC, this) connection.subscribe(ProjectTopics.PROJECT_ROOTS, this) connection.subscribe(WorkspaceModelTopics.CHANGED, ModelChangeListener()) connection.subscribe(ProjectJdkTable.JDK_TABLE_TOPIC, this) } override fun libraryInfosRemoved(libraryInfos: Collection<LibraryInfo>) { invalidateEntries({ k, v -> k in libraryInfos || v.libraries.any { it in libraryInfos } }) } override fun jdkRemoved(jdk: Sdk) { invalidateEntries({ _, v -> v.sdk.any { it.sdk == jdk } }) } override fun jdkNameChanged(jdk: Sdk, previousName: String) { jdkRemoved(jdk) } override fun calculate(key: LibraryInfo): LibraryDependencies = computeLibrariesAndSdksUsedWith(key) override fun checkKeyValidity(key: LibraryInfo) { key.checkValidity() } override fun checkValueValidity(value: LibraryDependencies) { value.libraries.forEach { it.checkValidity() } } override fun rootsChanged(event: ModuleRootEvent) { if (event.isCausedByWorkspaceModelChangesOnly) return // SDK could be changed (esp in tests) out of message bus subscription val sdks = project.allSdks() invalidateEntries( { _, value -> value.sdk.any { it.sdk !in sdks } }, // unable to check entities properly: an event could be not the last validityCondition = null ) } inner class ModelChangeListener : ModuleEntityChangeListener(project) { override fun entitiesChanged(outdated: List<Module>) { invalidate(writeAccessRequired = true) } } } private inner class ModuleDependenciesCache : SynchronizedFineGrainedEntityCache<Module, LibraryDependencyCandidatesAndSdkInfos>(project), WorkspaceModelChangeListener, ProjectJdkTable.Listener, LibraryInfoListener, ModuleRootListener { override fun subscribe() { val connection = project.messageBus.connect(this) connection.subscribe(WorkspaceModelTopics.CHANGED, this) connection.subscribe(LibraryInfoListener.TOPIC, this) connection.subscribe(ProjectJdkTable.JDK_TABLE_TOPIC, this) connection.subscribe(ProjectTopics.PROJECT_ROOTS, this) } @RequiresReadLock override fun get(key: Module): LibraryDependencyCandidatesAndSdkInfos { assertReadAccessAllowed() return internalGet(key, hashMapOf(), linkedSetOf(), hashMapOf()) } private fun internalGet( key: Module, tmpResults: MutableMap<Module, LibraryDependencyCandidatesAndSdkInfos>, trace: LinkedHashSet<Module>, loops: MutableMap<Module, Set<Module>> ): LibraryDependencyCandidatesAndSdkInfos { checkKeyAndDisposeIllegalEntry(key) useCache { cache -> checkEntitiesIfRequired(cache) cache[key] }?.let { return it } checkCanceled() val newValue = computeLibrariesAndSdksUsedIn(key, tmpResults, trace, loops) if (isValidityChecksEnabled) { checkValueValidity(newValue) } val existedValue = if (trace.isNotEmpty()) { dumpLoopsIfPossible(key, newValue, tmpResults, trace, loops) } else { // it is possible to dump results when all dependencies are resolved hence trace is empty useCache { cache -> val existedValue = cache.putIfAbsent(key, newValue) for (entry in tmpResults.entries) { cache.putIfAbsent(entry.key, entry.value) } existedValue } } return existedValue ?: newValue } /** * It is possible to dump loops from the subtree from the last module from the loop * * @param trace is not empty trace * @return existed value if applicable */ private fun dumpLoopsIfPossible( key: Module, newValue: LibraryDependencyCandidatesAndSdkInfos, tmpResults: MutableMap<Module, LibraryDependencyCandidatesAndSdkInfos>, trace: LinkedHashSet<Module>, loops: MutableMap<Module, Set<Module>>, ): LibraryDependencyCandidatesAndSdkInfos? { val currentLoop = loops[key] ?: return null if (trace.last() in loops) return null return useCache { cache -> val existedValue = cache.putIfAbsent(key, newValue) tmpResults.remove(key) for (loopModule in currentLoop) { tmpResults.remove(loopModule)?.let { cache.putIfAbsent(loopModule, it) } loops.remove(loopModule) } existedValue } } private fun computeLibrariesAndSdksUsedIn( module: Module, tmpResults: MutableMap<Module, LibraryDependencyCandidatesAndSdkInfos>, trace: LinkedHashSet<Module>, loops: MutableMap<Module, Set<Module>> ): LibraryDependencyCandidatesAndSdkInfos { checkCanceled() check(trace.add(module)) { "recursion detected" } val libraryDependencyCandidatesAndSdkInfos = LibraryDependencyCandidatesAndSdkInfos() tmpResults[module] = libraryDependencyCandidatesAndSdkInfos val modulesToVisit = HashSet<Module>() val infoCache = LibraryInfoCache.getInstance(project) ModuleRootManager.getInstance(module).orderEntries() .process(object : RootPolicy<Unit>() { override fun visitModuleOrderEntry(moduleOrderEntry: ModuleOrderEntry, value: Unit) { moduleOrderEntry.module?.let(modulesToVisit::add) } override fun visitLibraryOrderEntry(libraryOrderEntry: LibraryOrderEntry, value: Unit) { checkCanceled() val libraryEx = libraryOrderEntry.library.safeAs<LibraryEx>()?.takeUnless { it.isDisposed } ?: return val candidate = LibraryDependencyCandidate.fromLibraryOrNull(infoCache[libraryEx]) ?: return libraryDependencyCandidatesAndSdkInfos += candidate } override fun visitJdkOrderEntry(jdkOrderEntry: JdkOrderEntry, value: Unit) { checkCanceled() jdkOrderEntry.jdk?.let { jdk -> libraryDependencyCandidatesAndSdkInfos += SdkInfo(project, jdk) } } }, Unit) // handle circular dependency case for (moduleToVisit in modulesToVisit) { checkCanceled() if (moduleToVisit == module) continue if (moduleToVisit !in trace) continue // circular dependency found val reversedTrace = trace.toList().asReversed() val sharedLibraryDependencyCandidatesAndSdkInfos: LibraryDependencyCandidatesAndSdkInfos = run { var shared: LibraryDependencyCandidatesAndSdkInfos? = null val loop = hashSetOf<Module>() val duplicates = hashSetOf<LibraryDependencyCandidatesAndSdkInfos>() for (traceModule in reversedTrace) { loop += traceModule loops[traceModule]?.let { loop += it } loops[traceModule] = loop val traceModuleLibraryDependencyCandidatesAndSdkInfos = tmpResults.getValue(traceModule) if (shared == null && !duplicates.add(traceModuleLibraryDependencyCandidatesAndSdkInfos)) { shared = traceModuleLibraryDependencyCandidatesAndSdkInfos } if (traceModule === moduleToVisit) { break } } shared ?: duplicates.first() } sharedLibraryDependencyCandidatesAndSdkInfos += libraryDependencyCandidatesAndSdkInfos for (traceModule in reversedTrace) { val traceModuleLibraryDependencyCandidatesAndSdkInfos: LibraryDependencyCandidatesAndSdkInfos = tmpResults.getValue(traceModule) if (traceModuleLibraryDependencyCandidatesAndSdkInfos === sharedLibraryDependencyCandidatesAndSdkInfos) { if (traceModule === moduleToVisit) { break } continue } sharedLibraryDependencyCandidatesAndSdkInfos += traceModuleLibraryDependencyCandidatesAndSdkInfos tmpResults[traceModule] = sharedLibraryDependencyCandidatesAndSdkInfos loops[traceModule]?.let { loop -> for (loopModule in loop) { if (loopModule == traceModule) continue val value = tmpResults.getValue(loopModule) if (value === sharedLibraryDependencyCandidatesAndSdkInfos) continue sharedLibraryDependencyCandidatesAndSdkInfos += value tmpResults[loopModule] = sharedLibraryDependencyCandidatesAndSdkInfos } } if (traceModule === moduleToVisit) { break } } } // merge for (moduleToVisit in modulesToVisit) { checkCanceled() if (moduleToVisit == module || moduleToVisit in trace) continue val moduleToVisitLibraryDependencyCandidatesAndSdkInfos = tmpResults[moduleToVisit] ?: internalGet(moduleToVisit, tmpResults, trace, loops = loops) val moduleLibraryDependencyCandidatesAndSdkInfos = tmpResults.getValue(module) // We should not include SDK from dependent modules // see the traverse way of OrderEnumeratorBase#shouldAddOrRecurse for JdkOrderEntry moduleLibraryDependencyCandidatesAndSdkInfos.libraryDependencyCandidates += moduleToVisitLibraryDependencyCandidatesAndSdkInfos.libraryDependencyCandidates } trace.remove(module) return tmpResults.getValue(module) } override fun calculate(key: Module): LibraryDependencyCandidatesAndSdkInfos = throw UnsupportedOperationException("calculate(Module) should not be invoked due to custom impl of get()") override fun checkKeyValidity(key: Module) { key.checkValidity() } override fun checkValueValidity(value: LibraryDependencyCandidatesAndSdkInfos) { value.libraryDependencyCandidates.forEach { it.libraries.forEach { libraryInfo -> libraryInfo.checkValidity() } } } override fun jdkRemoved(jdk: Sdk) { invalidateEntries({ _, candidates -> candidates.sdkInfos.any { it.sdk == jdk } }) } override fun jdkNameChanged(jdk: Sdk, previousName: String) { jdkRemoved(jdk) } override fun rootsChanged(event: ModuleRootEvent) { if (event.isCausedByWorkspaceModelChangesOnly) return // TODO: `invalidate()` to be drop when IDEA-298694 is fixed // Reason: unload modules are untracked with WorkspaceModel invalidate(writeAccessRequired = true) return // SDK could be changed (esp in tests) out of message bus subscription val sdks = project.allSdks() invalidateEntries( { _, candidates -> candidates.sdkInfos.any { it.sdk !in sdks } }, // unable to check entities properly: an event could be not the last validityCondition = null ) } override fun beforeChanged(event: VersionedStorageChange) { val storageBefore = event.storageBefore val changes = event.getChanges(ModuleEntity::class.java).ifEmpty { return } val outdatedModules = mutableSetOf<Module>() for (change in changes) { val moduleEntity = change.oldEntity ?: continue collectOutdatedModules(moduleEntity, storageBefore, outdatedModules) } invalidateKeys(outdatedModules) } private fun collectOutdatedModules(moduleEntity: ModuleEntity, storage: EntityStorage, outdatedModules: MutableSet<Module>) { val module = moduleEntity.findModule(storage) ?: return if (!outdatedModules.add(module)) return storage.referrers(moduleEntity.symbolicId, ModuleEntity::class.java).forEach { collectOutdatedModules(it, storage, outdatedModules) } } override fun libraryInfosRemoved(libraryInfos: Collection<LibraryInfo>) { val infos = libraryInfos.toHashSet() invalidateEntries( { _, v -> v.libraryDependencyCandidates.any { candidate -> candidate.libraries.any { it in infos } } }, // unable to check entities properly: an event could be not the last validityCondition = null ) } } private inner class LibraryUsageIndex { private val modulesLibraryIsUsedIn: MultiMap<Library, Module> = runReadAction { val map: MultiMap<Library, Module> = MultiMap.createSet() val libraryCache = LibraryInfoCache.getInstance(project) for (module in ModuleManager.getInstance(project).modules) { checkCanceled() for (entry in ModuleRootManager.getInstance(module).orderEntries) { if (entry !is LibraryOrderEntry) continue val library = entry.library ?: continue val keyLibrary = libraryCache.deduplicatedLibrary(library) map.putValue(keyLibrary, module) } } map } fun getModulesLibraryIsUsedIn(libraryInfo: LibraryInfo) = sequence<Module> { val ideaModelInfosCache = getIdeaModelInfosCache(project) for (module in modulesLibraryIsUsedIn[libraryInfo.library]) { val mappedModuleInfos = ideaModelInfosCache.getModuleInfosForModule(module) if (mappedModuleInfos.any { it.platform.canDependOn(libraryInfo, module.isHMPPEnabled) }) { yield(module) } } } } }
apache-2.0
7cc43293c00a3f13e32e10f57cdce662
43.871845
171
0.654723
6.019536
false
false
false
false
fluidsonic/fluid-json
coding/sources-jvm/codecs/extended/CharRangeJsonCodec.kt
1
1081
package io.fluidsonic.json public object CharRangeJsonCodec : AbstractJsonCodec<CharRange, JsonCodingContext>() { override fun JsonDecoder<JsonCodingContext>.decode(valueType: JsonCodingType<CharRange>): CharRange { var endInclusive = 0.toChar() var endInclusiveProvided = false var start = 0.toChar() var startProvided = false readFromMapByElementValue { key -> when (key) { Fields.endInclusive -> { endInclusive = readChar() endInclusiveProvided = true } Fields.start -> { start = readChar() startProvided = true } else -> skipValue() } } if (!startProvided) missingPropertyError(Fields.start) if (!endInclusiveProvided) missingPropertyError(Fields.endInclusive) return start .. endInclusive } override fun JsonEncoder<JsonCodingContext>.encode(value: CharRange) { writeIntoMap { writeMapElement(Fields.start, char = value.first) writeMapElement(Fields.endInclusive, char = value.last) } } private object Fields { const val endInclusive = "endInclusive" const val start = "start" } }
apache-2.0
d1e8d11f287985ced27e9acde58ae43f
22.5
102
0.716004
4.094697
false
false
false
false
CORDEA/MackerelClient
app/src/main/java/jp/cordea/mackerelclient/view/MonitorListItem.kt
1
1476
package jp.cordea.mackerelclient.view import android.content.Context import androidx.fragment.app.Fragment import com.xwray.groupie.databinding.BindableItem import jp.cordea.mackerelclient.R import jp.cordea.mackerelclient.activity.MonitorDetailActivity import jp.cordea.mackerelclient.api.response.MonitorDataResponse import jp.cordea.mackerelclient.databinding.ListItemMonitorBinding import javax.inject.Inject class MonitorListItem @Inject constructor( private val fragment: Fragment ) : BindableItem<ListItemMonitorBinding>() { private lateinit var model: MonitorListItemModel fun update(model: MonitorListItemModel) = apply { this.model = model } override fun getLayout(): Int = R.layout.list_item_monitor override fun bind(binding: ListItemMonitorBinding, position: Int) { binding.model = model binding.root.setOnClickListener { val intent = MonitorDetailActivity.createIntent(fragment.context!!, model.response) fragment.startActivityForResult(intent, MonitorDetailActivity.REQUEST_CODE) } } } class MonitorListItemModel( val response: MonitorDataResponse, defaultName: String ) { companion object { fun from(context: Context, response: MonitorDataResponse) = MonitorListItemModel(response, context.getString(R.string.na_text)) } val type: String = response.type val id: String = response.id val name: String = response.name ?: defaultName }
apache-2.0
1b680c61aea698eed0da322eff1c0319
34.142857
95
0.756098
4.670886
false
false
false
false
JetBrains/teamcity-dnx-plugin
plugin-dotnet-agent/src/test/kotlin/jetbrains/buildServer/dotnet/test/dotnet/DotnetWorkflowAnalyzerTest.kt
1
5040
package jetbrains.buildServer.dotnet.test.dotnet import jetbrains.buildServer.BuildProblemData import jetbrains.buildServer.agent.runner.LoggerService import jetbrains.buildServer.dotnet.CommandResult import jetbrains.buildServer.dotnet.DotnetWorkflowAnalyzer import jetbrains.buildServer.dotnet.DotnetWorkflowAnalyzerContext import jetbrains.buildServer.dotnet.DotnetWorkflowAnalyzerImpl import org.jmock.Expectations import org.jmock.Mockery import org.testng.annotations.BeforeMethod import org.testng.annotations.Test import java.util.* class DotnetWorkflowAnalyzerTest { private lateinit var _ctx: Mockery private lateinit var _loggerService: LoggerService @BeforeMethod fun setUp() { _ctx = Mockery() _loggerService = _ctx.mock<LoggerService>(LoggerService::class.java) } @Test fun shouldLogErrorWhenStepHasFailedTests() { // Given val instance = createInstance() val context = DotnetWorkflowAnalyzerContext() // When _ctx.checking(object : Expectations() { init { oneOf<LoggerService>(_loggerService).writeWarning("Process finished with positive exit code 99 (some tests have failed). Reporting step success as all the tests have run.") } }) instance.registerResult(context, EnumSet.of(CommandResult.Success, CommandResult.FailedTests), 99) // Then _ctx.assertIsSatisfied() } @Test fun shouldCreateBuildProblemWhenStepFailed() { // Given val instance = createInstance() val context = DotnetWorkflowAnalyzerContext() // When _ctx.checking(object : Expectations() { init { oneOf<LoggerService>(_loggerService).writeBuildProblem("dotnet_exit_code-99", BuildProblemData.TC_EXIT_CODE_TYPE, "Process exited with code -99") } }) instance.registerResult(context, EnumSet.of(CommandResult.Fail), -99) // Then _ctx.assertIsSatisfied() } @Test fun shouldNotProduceAnyLogsWhenSuccess() { // Given val instance = createInstance() val context = DotnetWorkflowAnalyzerContext() // When instance.registerResult(context, EnumSet.of(CommandResult.Success), 0) // Then _ctx.assertIsSatisfied() } @Test fun shouldSummarize() { // Given val instance = createInstance() val context = DotnetWorkflowAnalyzerContext() // When _ctx.checking(object : Expectations() { init { oneOf<LoggerService>(_loggerService).writeWarning("Process finished with positive exit code 99 (some tests have failed). Reporting step success as all the tests have run.") oneOf<LoggerService>(_loggerService).writeWarning("Some of processes finished with positive exit code (some tests have failed). Reporting step success as all the tests have run.") } }) instance.registerResult(context, EnumSet.of(CommandResult.Success, CommandResult.FailedTests), 99) instance.registerResult(context, EnumSet.of(CommandResult.Success), 0) instance.summarize(context) // Then _ctx.assertIsSatisfied() } @Test fun shouldNotSummarizeWhenLastResultIsFailedTests() { // Given val instance = createInstance() val context = DotnetWorkflowAnalyzerContext() // When _ctx.checking(object : Expectations() { init { oneOf<LoggerService>(_loggerService).writeWarning("Process finished with positive exit code 99 (some tests have failed). Reporting step success as all the tests have run.") oneOf<LoggerService>(_loggerService).writeWarning("Process finished with positive exit code 33 (some tests have failed). Reporting step success as all the tests have run.") } }) instance.registerResult(context, EnumSet.of(CommandResult.Success, CommandResult.FailedTests), 99) instance.registerResult(context, EnumSet.of(CommandResult.Success, CommandResult.FailedTests), 33) instance.summarize(context) // Then _ctx.assertIsSatisfied() } @Test fun shouldNotSummarizeWhenSingleCommand() { // Given val instance = createInstance() val context = DotnetWorkflowAnalyzerContext() // When _ctx.checking(object : Expectations() { init { oneOf<LoggerService>(_loggerService).writeWarning("Process finished with positive exit code 99 (some tests have failed). Reporting step success as all the tests have run.") } }) instance.registerResult(context, EnumSet.of(CommandResult.Success, CommandResult.FailedTests), 99) instance.summarize(context) // Then _ctx.assertIsSatisfied() } private fun createInstance(): DotnetWorkflowAnalyzer { return DotnetWorkflowAnalyzerImpl(_loggerService) } }
apache-2.0
e09a307e74e7b87ab64d5266d48ba53b
34.251748
195
0.67004
4.965517
false
true
false
false
Bluexin/mek-re
src/main/java/be/bluexin/mekre/guis/MGuiContainer.kt
1
4925
package be.bluexin.mekre.guis import be.bluexin.mekre.Refs import be.bluexin.mekre.containers.OperatingTEContainer import be.bluexin.mekre.tiles.OperatingTE import com.teamwizardry.librarianlib.client.gui.GuiComponent import com.teamwizardry.librarianlib.client.gui.components.ComponentSprite import com.teamwizardry.librarianlib.client.gui.components.ComponentSpriteProgressBar import com.teamwizardry.librarianlib.client.gui.components.ComponentText import com.teamwizardry.librarianlib.client.gui.components.ComponentVoid import com.teamwizardry.librarianlib.client.guicontainer.GuiContainerBase import com.teamwizardry.librarianlib.client.guicontainer.builtin.BaseLayouts import com.teamwizardry.librarianlib.client.sprite.Texture import com.teamwizardry.librarianlib.common.util.MethodHandleHelper import com.teamwizardry.librarianlib.common.util.plus import com.teamwizardry.librarianlib.common.util.vec import net.minecraft.client.resources.I18n /** * Part of mek_re by Bluexin, released under GNU GPLv3. * * @author Bluexin */ open class MGuiContainer(inventorySlotsIn: OperatingTEContainer) : GuiContainerBase(inventorySlotsIn, 176, 166) { private val slots = mutableListOf<ComponentVoid>() private val comp = MethodHandleHelper.wrapperForGetter(GuiContainerBase::class.java, "mainScaleWrapper")(this) as ComponentVoid init { val te = inventorySlotsIn.invBlock.inventory as OperatingTE val bg = ComponentSprite(BG, 0, 0) mainComponents.add(bg) bg.add(ComponentSprite(SL_INPUT, 55, 16)) bg.add(ComponentSprite(SL_POWER, 55, 52)) bg.add(ComponentSprite(SG_POWER, 55, 52)) bg.add(ComponentSprite(SL_OUTPUT_L, 111, 30)) val inventory = BaseLayouts.player(inventorySlotsIn.invPlayer) bg.add(inventory.root) slots.add(inventory.root) inventory.main.pos = vec(8, 84) val input = BaseLayouts.grid(inventorySlotsIn.invBlock.input, 7) input.root.pos = vec(56, 17) slots.add(input.root) bg.add(input.root) val output = BaseLayouts.grid(inventorySlotsIn.invBlock.output, 7) output.root.pos = vec(116, 35) slots.add(output.root) bg.add(output.root) bg.add(ComponentText(88, 6, horizontal = ComponentText.TextAlignH.CENTER).`val`(I18n.format(te.unlocalizedName))) bg.add(ComponentSprite(PROGRESS_BG, 77, 37)) val progressBar = ComponentSpriteProgressBar(PROGRESS_FG, 78, 38) progressBar.direction.setValue(ComponentSpriteProgressBar.ProgressDirection.X_POS) progressBar.progress.func { te.currentOperations[0]?.progress ?: 0f } progressBar.tooltip { I18n.format("gui.progress", ((te.currentOperations[0]?.progress ?: 0f) * 100).toInt()) } bg.add(progressBar) bg.add(ComponentSprite(POWER_BG, 164, 15)) val powerBar = ComponentSpriteProgressBar(POWER_FG, 165, 16) powerBar.direction.setValue(ComponentSpriteProgressBar.ProgressDirection.Y_NEG) powerBar.progress.func { te.energyStored.toFloat() / te.maxEnergyStored } powerBar.tooltip { I18n.format("gui.energy", te.energyStored, te.maxEnergyStored) } bg.add(powerBar) } override fun initGui() { var pos = comp.pos slots.forEach { it.pos += pos } super.initGui() pos = comp.pos guiLeft = pos.xi guiTop = pos.yi slots.forEach { it.pos -= pos } } companion object { private val RES_MAIN = Texture(Refs.getResourceLocation("textures/guis/gui_basic_machine.png")) private val BG = RES_MAIN.getSprite("bg", 176, 166) private val RES_PROGRESS = Texture(Refs.getResourceLocation("textures/guis/parts/gui_progress.png")) private val PROGRESS_BG = RES_PROGRESS.getSprite("regular_bg", 25, 9) private val PROGRESS_FG = RES_PROGRESS.getSprite("regular_fg", 23, 7) private val RES_POWER = Texture(Refs.getResourceLocation("textures/guis/parts/gui_power_bar.png")) private val POWER_BG = RES_POWER.getSprite("regular_bg", 6, 54) private val POWER_FG = RES_POWER.getSprite("regular_fg", 4, 52) private val RES_SLOTS = Texture(Refs.getResourceLocation("textures/guis/parts/gui_slots.png")) private val SL_INPUT = RES_SLOTS.getSprite("input", 18, 18) private val SL_POWER = RES_SLOTS.getSprite("power", 18, 18) private val SL_OUTPUT_L = RES_SLOTS.getSprite("output_large", 26, 26) private val SG_POWER = RES_SLOTS.getSprite("sign_power", 18, 18) } } inline fun GuiComponent<*>.tooltip(crossinline callback: () -> String) { this.BUS.hook(GuiComponent.PostDrawEvent::class.java) { if (this.mouseOver) this.setTooltip(listOf(callback())) } } fun GuiComponent<*>.tooltip(text: String) { this.BUS.hook(GuiComponent.PostDrawEvent::class.java) { if (this.mouseOver) this.setTooltip(listOf(text)) } }
gpl-3.0
d83572ddefd53973a8b95139c42984f8
42.584071
131
0.71066
3.719789
false
false
false
false
smmribeiro/intellij-community
plugins/settings-repository/src/IcsUrlBuilder.kt
10
1297
// 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.settingsRepository import com.intellij.configurationStore.getPerOsSettingsStorageFolderName import com.intellij.openapi.components.RoamingType import com.intellij.openapi.util.SystemInfo private val OS_PREFIXES = arrayOf("_mac/", "_windows/", "_linux/", "_freebsd/", "_unix/") fun getOsFolderName() = when { SystemInfo.isMac -> "_mac" SystemInfo.isWindows -> "_windows" SystemInfo.isLinux -> "_linux" SystemInfo.isFreeBSD -> "_freebsd" SystemInfo.isUnix -> "_unix" else -> "_unknown" } internal fun toRepositoryPath(path: String, roamingType: RoamingType): String { if (roamingType == RoamingType.PER_OS && path.startsWith(getPerOsSettingsStorageFolderName())) { // mac/keymap.xml -> keymap.xml val pathWithoutOsPrefix = path.removePrefix(getPerOsSettingsStorageFolderName() + "/") // keymap.xml -> _mac/keymap.xml return "${getOsFolderName()}/$pathWithoutOsPrefix" } return path } internal fun toIdeaPath(path: String): String { for (prefix in OS_PREFIXES) { val result = path.removePrefix(prefix) if (result !== path) { return result } } return path }
apache-2.0
0acdc81b25254eb4a775a07dc3543b70
34.081081
158
0.721665
4.238562
false
false
false
false
smmribeiro/intellij-community
platform/configuration-store-impl/src/DirectoryBasedStorage.kt
4
9209
// 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.configurationStore import com.intellij.configurationStore.schemeManager.createDir import com.intellij.configurationStore.schemeManager.getOrCreateChild import com.intellij.openapi.components.PathMacroSubstitutor import com.intellij.openapi.components.StateSplitterEx import com.intellij.openapi.components.impl.stores.DirectoryStorageUtil import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.LineSeparator import com.intellij.util.isEmpty import org.jdom.Element import org.jetbrains.annotations.ApiStatus import java.io.IOException import java.nio.ByteBuffer import java.nio.file.Path abstract class DirectoryBasedStorageBase(@Suppress("DEPRECATION") protected val splitter: com.intellij.openapi.components.StateSplitter, protected val pathMacroSubstitutor: PathMacroSubstitutor? = null) : StateStorageBase<StateMap>() { protected var componentName: String? = null protected abstract val dir: Path public override fun loadData(): StateMap { return StateMap.fromMap(DirectoryStorageUtil.loadFrom(dir, pathMacroSubstitutor)) } override fun createSaveSessionProducer(): SaveSessionProducer? = null override fun analyzeExternalChangesAndUpdateIfNeeded(componentNames: MutableSet<in String>) { // todo reload only changed file, compute diff val newData = loadData() storageDataRef.set(newData) if (componentName != null) { componentNames.add(componentName!!) } } override fun getSerializedState(storageData: StateMap, component: Any?, componentName: String, archive: Boolean): Element? { this.componentName = componentName if (storageData.isEmpty()) { return null } // FileStorageCoreUtil on load check both component and name attributes (critical important for external store case, where we have only in-project artifacts, but not external) val state = Element(FileStorageCoreUtil.COMPONENT).setAttribute(FileStorageCoreUtil.NAME, componentName) if (splitter is StateSplitterEx) { for (fileName in storageData.keys()) { val subState = storageData.getState(fileName, archive) ?: return null splitter.mergeStateInto(state, subState.clone()) } } else { val subElements = ArrayList<Element>() for (fileName in storageData.keys()) { val subState = storageData.getState(fileName, archive) ?: return null subElements.add(subState.clone()) } if (subElements.isNotEmpty()) { splitter.mergeStatesInto(state, subElements.toTypedArray()) } } return state } override fun hasState(storageData: StateMap, componentName: String): Boolean = storageData.hasStates() } @ApiStatus.Internal interface DirectoryBasedSaveSessionProducer : SaveSessionProducer { fun setFileState(fileName: String, componentName: String, element: Element?) } open class DirectoryBasedStorage(override val dir: Path, @Suppress("DEPRECATION") splitter: com.intellij.openapi.components.StateSplitter, pathMacroSubstitutor: PathMacroSubstitutor? = null) : DirectoryBasedStorageBase(splitter, pathMacroSubstitutor) { override val isUseVfsForWrite: Boolean get() = true @Volatile private var cachedVirtualFile: VirtualFile? = null private fun getVirtualFile(): VirtualFile? { var result = cachedVirtualFile if (result == null) { result = LocalFileSystem.getInstance().refreshAndFindFileByNioFile(dir) cachedVirtualFile = result } return result } internal fun setVirtualDir(dir: VirtualFile?) { cachedVirtualFile = dir } override fun createSaveSessionProducer(): SaveSessionProducer? = if (checkIsSavingDisabled()) null else MySaveSession(this, getStorageData()) private class MySaveSession(private val storage: DirectoryBasedStorage, private val originalStates: StateMap) : SaveSessionBase(), SaveSession, DirectoryBasedSaveSessionProducer { private var copiedStorageData: MutableMap<String, Any>? = null private val dirtyFileNames = HashSet<String>() private var isSomeFileRemoved = false override fun setSerializedState(componentName: String, element: Element?) { storage.componentName = componentName val stateAndFileNameList = if (element.isEmpty()) emptyList() else storage.splitter.splitState(element!!) if (stateAndFileNameList.isEmpty()) { if (copiedStorageData != null) { copiedStorageData!!.clear() } else if (!originalStates.isEmpty()) { copiedStorageData = HashMap() } return } val existingFiles = HashSet<String>(stateAndFileNameList.size) for (pair in stateAndFileNameList) { doSetState(pair.second, pair.first) existingFiles.add(pair.second) } for (key in originalStates.keys()) { if (existingFiles.contains(key)) { continue } removeFileData(key) } } override fun setFileState(fileName: String, componentName: String, element: Element?) { storage.componentName = componentName if (element != null) { doSetState(fileName, element) } else { removeFileData(fileName) } } private fun removeFileData(fileName: String) { if (copiedStorageData == null) { copiedStorageData = originalStates.toMutableMap() } isSomeFileRemoved = true copiedStorageData!!.remove(fileName) } private fun doSetState(fileName: String, subState: Element) { if (copiedStorageData == null) { copiedStorageData = setStateAndCloneIfNeeded(fileName, subState, originalStates) if (copiedStorageData != null) { dirtyFileNames.add(fileName) } } else if (updateState(copiedStorageData!!, fileName, subState)) { dirtyFileNames.add(fileName) } } override fun createSaveSession() = if (storage.checkIsSavingDisabled() || copiedStorageData == null) null else this override fun save() { val stateMap = StateMap.fromMap(copiedStorageData!!) if (copiedStorageData!!.isEmpty()) { val dir = storage.getVirtualFile() if (dir != null && dir.exists()) { dir.delete(this) } storage.setStorageData(stateMap) return } if (dirtyFileNames.isNotEmpty()) { saveStates(stateMap) } if (isSomeFileRemoved) { val dir = storage.getVirtualFile() if (dir != null && dir.exists()) { deleteFiles(dir) } } storage.setStorageData(stateMap) } private fun saveStates(states: StateMap) { var dir = storage.cachedVirtualFile for (fileName in states.keys()) { if (!dirtyFileNames.contains(fileName)) { continue } val element = states.getElement(fileName) ?: continue if (dir == null || !dir.exists()) { dir = storage.getVirtualFile() if (dir == null || !dir.exists()) { dir = createDir(storage.dir, this) storage.cachedVirtualFile = dir } } try { val file = dir.getOrCreateChild(fileName, this) // we don't write xml prolog due to historical reasons (and should not in any case) val macroManager = if (storage.pathMacroSubstitutor == null) null else (storage.pathMacroSubstitutor as TrackingPathMacroSubstitutorImpl).macroManager val xmlDataWriter = XmlDataWriter(FileStorageCoreUtil.COMPONENT, listOf(element), mapOf(FileStorageCoreUtil.NAME to storage.componentName!!), macroManager, dir.path) writeFile(null, this, file, xmlDataWriter, getOrDetectLineSeparator(file) ?: LineSeparator.getSystemLineSeparator(), false) } catch (e: IOException) { LOG.error(e) } } } private fun deleteFiles(dir: VirtualFile) { val copiedStorageData = copiedStorageData!! for (file in dir.children) { val fileName = file.name if (fileName.endsWith(FileStorageCoreUtil.DEFAULT_EXT) && !copiedStorageData.containsKey(fileName)) { if (file.isWritable) { file.delete(this) } else { throw ReadOnlyModificationException(file, null) } } } } } private fun setStorageData(newStates: StateMap) { storageDataRef.set(newStates) } override fun toString() = "${javaClass.simpleName}(dir=${dir}, componentName=$componentName)" } private fun getOrDetectLineSeparator(file: VirtualFile): LineSeparator? { if (!file.exists()) { return null } file.detectedLineSeparator?.let { return LineSeparator.fromString(it) } val lineSeparator = detectLineSeparators(Charsets.UTF_8.decode(ByteBuffer.wrap(file.contentsToByteArray()))) file.detectedLineSeparator = lineSeparator.separatorString return lineSeparator }
apache-2.0
78891e57132ada8fa4a918120b4f8dd9
34.836576
181
0.688674
5.156215
false
false
false
false
smmribeiro/intellij-community
platform/built-in-server/src/org/jetbrains/builtInWebServer/liveReload/WebServerPageConnectionService.kt
9
20234
// 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.builtInWebServer.liveReload import com.google.common.net.HttpHeaders import com.intellij.CommonBundle import com.intellij.concurrency.JobScheduler import com.intellij.ide.browsers.ReloadMode import com.intellij.ide.browsers.WebBrowserManager import com.intellij.ide.browsers.WebBrowserXmlService import com.intellij.ide.browsers.actions.WebPreviewFileEditor import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.Service import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.editor.impl.EditorComponentImpl import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.options.ShowSettingsUtil import com.intellij.openapi.options.ex.ConfigurableWrapper import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.AsyncFileListener import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.wm.IdeFocusManager import com.intellij.ui.GotItTooltip import com.intellij.util.SingleAlarm import io.netty.buffer.Unpooled import io.netty.handler.codec.http.FullHttpRequest import io.netty.handler.codec.http.QueryStringDecoder import io.netty.util.CharsetUtil import org.jetbrains.ide.BuiltInServerBundle import org.jetbrains.io.jsonRpc.Client import org.jetbrains.io.jsonRpc.ClientManager import org.jetbrains.io.jsonRpc.JsonRpcServer import org.jetbrains.io.jsonRpc.MessageServer import org.jetbrains.io.webSocket.WebSocketClient import org.jetbrains.io.webSocket.WebSocketHandshakeHandler import java.awt.Point import java.net.URI import java.util.* import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicInteger import java.util.function.Supplier /** * Provides support for automatic reloading of pages opened on built-in web server on related files modification. * * Implementation: * * <-- html page with [.RELOAD_URL_PARAM] is requested * --> response with modified html which opens WebSocket connection listening for reload message * * <-- script or other resource of html is requested * start listening for related file changes * * file is changed * --> reload associated pages by sending WebSocket message */ @Service(Service.Level.APP) class WebServerPageConnectionService { private val RELOAD_PAGE_MESSAGE = Unpooled.copiedBuffer(RELOAD_WS_REQUEST, CharsetUtil.US_ASCII).asReadOnly() private var myServer: ClientManager? = null private var myRpcServer: JsonRpcServer? = null private val myState = RequestedPagesState() /** * @return suffix to add to requested file in response */ fun fileRequested(request: FullHttpRequest, onlyIfHtmlFile: Boolean, fileSupplier: Supplier<out VirtualFile?>): String? { var reloadRequest = ReloadMode.DISABLED val uri = request.uri() var path: String? = null if (uri != null && uri.contains(RELOAD_URL_PARAM)) { val decoder = QueryStringDecoder(uri) path = decoder.path() reloadRequest = decoder.parameters()[RELOAD_URL_PARAM]?.get(0)?.let { ReloadMode.valueOf(it) } ?: ReloadMode.DISABLED } if (reloadRequest == ReloadMode.DISABLED && myState.isEmpty) return null val file = fileSupplier.get() if (reloadRequest == ReloadMode.DISABLED && file != null) { myState.resourceRequested(request, file) return null } if (reloadRequest == ReloadMode.DISABLED) return null if (file == null) { LOGGER.warn("VirtualFile for $uri isn't resolved, reload on save can't be started") return null } if (onlyIfHtmlFile && !WebBrowserXmlService.getInstance().isHtmlFile(file)) return null if (path == null) { LOGGER.warn("path not evaluated for $uri") return null } myState.pageRequested(path, file, reloadRequest) val optionalConsoleLog = if (LOGGER.isDebugEnabled) "\nconsole.log('JetBrains Reload on Save script loaded');" else "" //language=HTML return """ <script> (function() {$optionalConsoleLog var ws = new WebSocket('ws://' + window.location.host + '/jb-server-page?$RELOAD_MODE_URL_PARAMETER=$reloadRequest&'+ '$REFERRER_URL_PARAMETER=' + encodeURIComponent(window.location.pathname)); ws.onmessage = function (msg) { if (msg.data === 'reload') { window.location.reload(); } if (msg.data.startsWith('$UPDATE_LINK_WS_REQUEST_PREFIX')) { var messageId = msg.data.substring(${UPDATE_LINK_WS_REQUEST_PREFIX.length}); var links = document.getElementsByTagName('link'); for (var i = 0; i < links.length; i++) { var link = links[i]; if (link.rel !== 'stylesheet') continue; var clonedLink = link.cloneNode(true); var newHref = link.href.replace(/(&|\?)$UPDATE_LINKS_ID_URL_PARAMETER=\d+/, "$1$UPDATE_LINKS_ID_URL_PARAMETER=" + messageId); if (newHref !== link.href) { clonedLink.href = newHref; } else { var indexOfQuest = newHref.indexOf('?'); if (indexOfQuest >= 0) { // to support ?foo#hash clonedLink.href = newHref.substring(0, indexOfQuest + 1) + '$UPDATE_LINKS_ID_URL_PARAMETER=' + messageId + '&' + newHref.substring(indexOfQuest + 1); } else { clonedLink.href += '?' + '$UPDATE_LINKS_ID_URL_PARAMETER=' + messageId; } } link.replaceWith(clonedLink); } } }; })(); </script> """.trimIndent() } fun reloadRelatedClients(modifiedFiles: List<VirtualFile>): AsyncFileListener.ChangeApplier? { myServer ?: return null if (myState.isRequestedFileWithoutReferrerModified(modifiedFiles)) { return object : AsyncFileListener.ChangeApplier { override fun afterVfsChange() { showGotItTooltip(modifiedFiles) myState.clear() val server = myServer server?.send<Any>(-1, RELOAD_PAGE_MESSAGE.retainedDuplicate(), null) } } } val affectedClients = myState.collectAffectedPages(modifiedFiles) return if (affectedClients.isEmpty()) null else object : AsyncFileListener.ChangeApplier { override fun afterVfsChange() { showGotItTooltip(modifiedFiles) for ((requestedPage, affectedFiles) in affectedClients) { if (affectedFiles.isEmpty()) { LOGGER.debug("Reloading page for $requestedPage") for (client in requestedPage.clients) { client.webSocket.send(RELOAD_PAGE_MESSAGE.retainedDuplicate()) } } else { for ((clientIndex, client) in requestedPage.clients.withIndex()) { val messageId = myState.getNextMessageId() myState.linkedFilesRequested(messageId, affectedFiles) val message = UPDATE_LINK_WS_REQUEST_PREFIX + messageId for (affectedFile in affectedFiles) { if (clientIndex == 0) LOGGER.debug("Reload file ${affectedFile.name} for $requestedPage") client.webSocket.send(Unpooled.copiedBuffer(message, Charsets.UTF_8)) } JobScheduler.getScheduler().schedule( { if (!myState.isAllLinkedFilesReloaded(messageId)) { LOGGER.debug("Some files weren't reloaded, reload whole $requestedPage for client") client.webSocket.send(RELOAD_PAGE_MESSAGE.retainedDuplicate()) } }, 1, TimeUnit.SECONDS) } } } } } } private fun clientConnected(client: WebSocketClient, referrer: String, reloadMode: ReloadMode) { myState.clientConnected(client, referrer, reloadMode) } private fun clientDisconnected(client: WebSocketClient) { myState.clientDisconnected(client) } private fun showGotItTooltip(modifiedFiles: List<VirtualFile>) { val gotItTooltip = GotItTooltip(SERVER_RELOAD_TOOLTIP_ID, BuiltInServerBundle.message("reload.on.save.got.it.content"), myServer!!) if (!gotItTooltip.canShow() || WebPreviewFileEditor.isPreviewOpened()) return if (WebBrowserManager.BROWSER_RELOAD_MODE_DEFAULT !== ReloadMode.RELOAD_ON_SAVE) { Logger.getInstance(WebServerPageConnectionService::class.java).error( "Default value for " + BuiltInServerBundle.message("reload.on.save.got.it.title") + " has changed, tooltip is outdated.") return } if (WebBrowserManager.getInstance().webServerReloadMode !== ReloadMode.RELOAD_ON_SAVE) { // changed before gotIt was shown return } gotItTooltip .withHeader(BuiltInServerBundle.message("reload.on.save.got.it.title")) .withPosition(Balloon.Position.above) val editorComponent = IdeFocusManager.getGlobalInstance().focusOwner as? EditorComponentImpl ?: return val editorFile = FileDocumentManager.getInstance().getFile(editorComponent.editor.document) if (!modifiedFiles.contains(editorFile)) return gotItTooltip.withLink(CommonBundle.message("action.text.configure.ellipsis")) { ShowSettingsUtil.getInstance().showSettingsDialog( editorComponent.editor.project, { (it as? ConfigurableWrapper)?.id == "reference.settings.ide.settings.web.browsers" }, null) } gotItTooltip.show(editorComponent) { component, _ -> val editor = (component as? EditorComponentImpl)?.editor ?: return@show Point(0,0) val p = editor.visualPositionToXY(editor.caretModel.currentCaret.visualPosition) val v = component.visibleRect Point(p.x.coerceIn(v.x, v.x + v.width), p.y.coerceIn(v.y, v.y + v.height)) } } internal class WebServerPageRequestHandler : WebSocketHandshakeHandler() { override fun serverCreated(server: ClientManager) { val instance = instance instance.myServer = server instance.myRpcServer = JsonRpcServer(server) } override fun isSupported(request: FullHttpRequest): Boolean { return super.isSupported(request) && checkPrefix(request.uri(), RELOAD_WS_URL_PREFIX) } override fun getMessageServer(): MessageServer { return instance.myRpcServer!! } override fun connected(client: Client, parameters: Map<String, List<String>>?) { if (parameters == null || client !is WebSocketClient) return val reloadModeParam = parameters[RELOAD_MODE_URL_PARAMETER] ?: return if (reloadModeParam.size != 1) return val reloadMode = try { ReloadMode.valueOf(reloadModeParam[0]) } catch (_:Throwable) { null } ?: return val referrerParam = parameters[REFERRER_URL_PARAMETER] ?: return if (referrerParam.size != 1) return val referrer = referrerParam[0] instance.clientConnected(client, referrer, reloadMode) } override fun disconnected(client: Client) { if (client is WebSocketClient) { instance.clientDisconnected(client) } } } private class RequestedPagesState { private val myRequestedFilesWithoutReferrer: MutableSet<VirtualFile?> = HashSet() private val myRequestedPages: MutableMap<String, RequestedPage> = HashMap() /** * Start to listen for files changes on HTTP request with RELOAD_URL_PARAM, stop on last WS client disconnect */ private var myFileListenerDisposable: Disposable? = null private var myDocumentListenerDisposable: Disposable? = null private val myMessageId = AtomicInteger(0) private val myLinkedFilesToReload: MutableMap<Int, MutableSet<VirtualFile>> = HashMap() @Synchronized fun clear() { LOGGER.debug("Requested pages cleared") for (requestedPage in myRequestedPages.values) { requestedPage.clear() } myRequestedPages.clear() cleanupIfEmpty() } @Synchronized fun resourceRequested(request: FullHttpRequest, file: VirtualFile) { val referer = request.headers()[HttpHeaders.REFERER] var associatedPageFound = false try { val path = extractRequestedPagePath(referer) val page = myRequestedPages[path] page?.associatedFiles?.add(file) associatedPageFound = page != null val messageIds = QueryStringDecoder(request.uri()).parameters()[UPDATE_LINKS_ID_URL_PARAMETER] if (messageIds != null && messageIds.size == 1) { myLinkedFilesToReload[messageIds[0].toInt()]?.remove(file) } } catch (ignore: Throwable) { } if (!associatedPageFound) { myRequestedFilesWithoutReferrer.add(file) } } private fun extractRequestedPagePath(referer: String): String { return URI.create(referer).path } @Synchronized fun pageRequested(path: String, file: VirtualFile, reloadMode: ReloadMode) { LOGGER.assertTrue(myRequestedPages.isEmpty() == (myFileListenerDisposable == null), "isEmpty: ${myRequestedPages.isEmpty()}, disposable is null: ${myFileListenerDisposable == null}") if (myFileListenerDisposable == null) { val disposable = Disposer.newDisposable(ApplicationManager.getApplication(), "RequestedPagesState.myFileListenerDisposable") VirtualFileManager.getInstance().addAsyncFileListener(WebServerFileContentListener(), disposable) myFileListenerDisposable = disposable } if (reloadMode == ReloadMode.RELOAD_ON_CHANGE && myDocumentListenerDisposable == null) { val disposable = Disposer.newDisposable(ApplicationManager.getApplication(), "RequestedPagesState.myDocumentListenerDisposable") EditorFactory.getInstance().eventMulticaster.addDocumentListener(object : DocumentListener { override fun documentChanged(event: DocumentEvent) { val virtualFile = FileDocumentManager.getInstance().getFile(event.document) if (isTrackedFile(virtualFile)) { FileDocumentManager.getInstance().saveDocument(event.document) } } }, disposable) myDocumentListenerDisposable = disposable } LOGGER.debug("Page is requested for $path") val page = myRequestedPages.getOrPut(path) { RequestedPage(path) } page.associatedFiles.add(file) page.scheduleCleanup() } private fun isTrackedFile(virtualFile: VirtualFile?) = myRequestedFilesWithoutReferrer.contains(virtualFile) || myRequestedPages.values.any { it.associatedFiles.contains(virtualFile) && it.clients.any { c -> c.reloadMode == ReloadMode.RELOAD_ON_CHANGE } } @Synchronized fun clientConnected(client: WebSocketClient, referrer: String, reloadMode: ReloadMode) { LOGGER.debug("WebSocket client connected for $referrer") val requestedPage = myRequestedPages[extractRequestedPagePath(referrer)] if (requestedPage == null) { LOGGER.warn("referrer not found") return } requestedPage.clientConnected(client, reloadMode) } @Synchronized fun clientDisconnected(client: WebSocketClient) { var requestedPage: RequestedPage? = null for (page in myRequestedPages.values) { if (page.clients.removeIf { it.webSocket == client }) { requestedPage = page break } } LOGGER.debug("WebSocket client disconnected for $requestedPage") requestedPage?.scheduleCleanup() } private fun cleanupIfEmpty() { if (myRequestedPages.isEmpty()) { myRequestedFilesWithoutReferrer.clear() if (myFileListenerDisposable != null) { Disposer.dispose(Objects.requireNonNull(myFileListenerDisposable)!!) myFileListenerDisposable = null } if (myDocumentListenerDisposable != null) { Disposer.dispose(Objects.requireNonNull(myDocumentListenerDisposable)!!) myDocumentListenerDisposable = null } } } @Synchronized fun isRequestedFileWithoutReferrerModified(files: List<VirtualFile?>): Boolean { for (file in files) { if (myRequestedFilesWithoutReferrer.contains(file)) return true } return false } /** * @return For each affected page either a list of linked files to reload, or reload the whole page if list is empty */ @Synchronized fun collectAffectedPages(files: List<VirtualFile>): Map<RequestedPage, List<VirtualFile>> { val result = HashMap<RequestedPage, List<VirtualFile>>() for (modifiedFile in files) { for (requestedPage in myRequestedPages.values) { if (requestedPage.associatedFiles.contains(modifiedFile)) { if (StringUtil.equalsIgnoreCase(modifiedFile.extension, "css")) { if (!result.containsKey(requestedPage)) { result[requestedPage] = mutableListOf(modifiedFile) } else if (result[requestedPage]!!.isNotEmpty()) { (result[requestedPage] as MutableList).add(modifiedFile) } // else other resource was requested, so reload whole page } else { result[requestedPage] = emptyList() } } } } return result } fun getNextMessageId(): Int { return myMessageId.incrementAndGet() } @Synchronized fun linkedFilesRequested(messageId: Int, affectedFiles: List<VirtualFile>) { myLinkedFilesToReload[messageId] = HashSet(affectedFiles) } @Synchronized fun isAllLinkedFilesReloaded(messageId: Int): Boolean { val isEmpty = myLinkedFilesToReload[messageId]?.isEmpty() ?: true myLinkedFilesToReload.remove(messageId) return isEmpty } @get:Synchronized val isEmpty: Boolean get() = myRequestedPages.isEmpty() @Synchronized fun removeRequestedPageIfEmpty(requestedPage: RequestedPage) { LOGGER.assertTrue(myRequestedPages[requestedPage.url] == requestedPage) if (requestedPage.clients.isEmpty()) { requestedPage.clear() myRequestedPages.remove(requestedPage.url) cleanupIfEmpty() } } inner class RequestedPage(val url: String) { val clients: MutableCollection<RequestedPageClient> = ArrayList() val associatedFiles: MutableSet<VirtualFile> = HashSet() var waitForClient: SingleAlarm = SingleAlarm(Runnable { removeRequestedPageIfEmpty(this) }, TimeUnit.SECONDS.toMillis(30).toInt(), ) fun clear() { Disposer.dispose(waitForClient) } fun scheduleCleanup() { waitForClient.cancelAndRequest() } fun clientConnected(client: WebSocketClient, reloadMode: ReloadMode) { clients.add(RequestedPageClient(client, reloadMode)) waitForClient.cancel() } override fun toString(): String { return "page (url=...${url.takeLast(10)}, ${clients.size} client(s)}" } } class RequestedPageClient(val webSocket: WebSocketClient, val reloadMode: ReloadMode) { } } companion object { const val RELOAD_URL_PARAM = "_ij_reload" const val SERVER_RELOAD_TOOLTIP_ID = "builtin.web.server.reload.on.save" private const val RELOAD_WS_REQUEST = "reload" private const val UPDATE_LINK_WS_REQUEST_PREFIX = "update-css " private const val RELOAD_WS_URL_PREFIX = "jb-server-page" private const val RELOAD_MODE_URL_PARAMETER = "reloadMode" private const val REFERRER_URL_PARAMETER = "referrer" private const val UPDATE_LINKS_ID_URL_PARAMETER = "jbUpdateLinksId" val instance: WebServerPageConnectionService get() = ApplicationManager.getApplication().getService(WebServerPageConnectionService::class.java) private val LOGGER = Logger.getInstance(WebServerPageConnectionService::class.java) } }
apache-2.0
1ee0f08950ccd2264190ab89d25341d5
39.308765
140
0.68632
4.572655
false
false
false
false
jotomo/AndroidAPS
danar/src/main/java/info/nightscout/androidaps/danaRKorean/comm/MsgInitConnStatusBolus_k.kt
1
1992
package info.nightscout.androidaps.danaRKorean.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danar.R import info.nightscout.androidaps.danar.comm.MessageBase import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification class MsgInitConnStatusBolus_k( injector: HasAndroidInjector ) : MessageBase(injector) { init { SetCommand(0x0302) aapsLogger.debug(LTag.PUMPCOMM, "New message") } override fun handleMessage(bytes: ByteArray) { if (bytes.size - 10 < 13) { return } val bolusConfig = intFromBuff(bytes, 0, 1) danaPump.isExtendedBolusEnabled = bolusConfig and 0x01 != 0 danaPump.bolusStep = intFromBuff(bytes, 1, 1) / 100.0 danaPump.maxBolus = intFromBuff(bytes, 2, 2) / 100.0 //int bolusRate = intFromBuff(bytes, 4, 8); val deliveryStatus = intFromBuff(bytes, 12, 1) aapsLogger.debug(LTag.PUMPCOMM, "Is Extended bolus enabled: " + danaPump.isExtendedBolusEnabled) aapsLogger.debug(LTag.PUMPCOMM, "Bolus increment: " + danaPump.bolusStep) aapsLogger.debug(LTag.PUMPCOMM, "Bolus max: " + danaPump.maxBolus) aapsLogger.debug(LTag.PUMPCOMM, "Delivery status: $deliveryStatus") if (!danaPump.isExtendedBolusEnabled) { val notification = Notification(Notification.EXTENDED_BOLUS_DISABLED, resourceHelper.gs(R.string.danar_enableextendedbolus), Notification.URGENT) rxBus.send(EventNewNotification(notification)) } else { rxBus.send(EventDismissNotification(Notification.EXTENDED_BOLUS_DISABLED)) } // This is last message of initial sequence activePlugin.activePump.finishHandshaking() } }
agpl-3.0
832dd19048326f57c2070a8e7f028d55
45.348837
157
0.7249
4.476404
false
false
false
false
jotomo/AndroidAPS
danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_CIR_CF_Array.kt
1
5429
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_CIR_CF_Array( injector: HasAndroidInjector ) : DanaRS_Packet(injector) { @Inject lateinit var danaPump: DanaPump init { opCode = BleEncryption.DANAR_PACKET__OPCODE_BOLUS__GET_CIR_CF_ARRAY aapsLogger.debug(LTag.PUMPCOMM, "New message") } override fun handleMessage(data: ByteArray) { var dataIndex = DATA_START var dataSize = 1 val language = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 danaPump.units = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 2 danaPump.morningCIR = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 2 val cir02 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 2 danaPump.afternoonCIR = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 2 val cir04 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 2 danaPump.eveningCIR = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 2 val cir06 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 2 danaPump.nightCIR = byteArrayToInt(getBytes(data, dataIndex, dataSize)) val cf02: Double val cf04: Double val cf06: Double if (danaPump.units == DanaPump.UNITS_MGDL) { dataIndex += dataSize dataSize = 2 danaPump.morningCF = byteArrayToInt(getBytes(data, dataIndex, dataSize)).toDouble() dataIndex += dataSize dataSize = 2 cf02 = byteArrayToInt(getBytes(data, dataIndex, dataSize)).toDouble() dataIndex += dataSize dataSize = 2 danaPump.afternoonCF = byteArrayToInt(getBytes(data, dataIndex, dataSize)).toDouble() dataIndex += dataSize dataSize = 2 cf04 = byteArrayToInt(getBytes(data, dataIndex, dataSize)).toDouble() dataIndex += dataSize dataSize = 2 danaPump.eveningCF = byteArrayToInt(getBytes(data, dataIndex, dataSize)).toDouble() dataIndex += dataSize dataSize = 2 cf06 = byteArrayToInt(getBytes(data, dataIndex, dataSize)).toDouble() dataIndex += dataSize dataSize = 2 danaPump.nightCF = byteArrayToInt(getBytes(data, dataIndex, dataSize)).toDouble() } else { dataIndex += dataSize dataSize = 2 danaPump.morningCF = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 dataIndex += dataSize dataSize = 2 cf02 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 dataIndex += dataSize dataSize = 2 danaPump.afternoonCF = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 dataIndex += dataSize dataSize = 2 cf04 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 dataIndex += dataSize dataSize = 2 danaPump.eveningCF = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 dataIndex += dataSize dataSize = 2 cf06 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 dataIndex += dataSize dataSize = 2 danaPump.nightCF = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 } if (danaPump.units < 0 || danaPump.units > 1) failed = true aapsLogger.debug(LTag.PUMPCOMM, "Language: $language") aapsLogger.debug(LTag.PUMPCOMM, "Pump units: " + if (danaPump.units == DanaPump.UNITS_MGDL) "MGDL" else "MMOL") aapsLogger.debug(LTag.PUMPCOMM, "Current pump morning CIR: " + danaPump.morningCIR) aapsLogger.debug(LTag.PUMPCOMM, "Current pump morning CF: " + danaPump.morningCF) aapsLogger.debug(LTag.PUMPCOMM, "Current pump afternoon CIR: " + danaPump.afternoonCIR) aapsLogger.debug(LTag.PUMPCOMM, "Current pump afternoon CF: " + danaPump.afternoonCF) aapsLogger.debug(LTag.PUMPCOMM, "Current pump evening CIR: " + danaPump.eveningCIR) aapsLogger.debug(LTag.PUMPCOMM, "Current pump evening CF: " + danaPump.eveningCF) aapsLogger.debug(LTag.PUMPCOMM, "Current pump night CIR: " + danaPump.nightCIR) aapsLogger.debug(LTag.PUMPCOMM, "Current pump night CF: " + danaPump.nightCF) aapsLogger.debug(LTag.PUMPCOMM, "cir02: $cir02") aapsLogger.debug(LTag.PUMPCOMM, "cir04: $cir04") aapsLogger.debug(LTag.PUMPCOMM, "cir06: $cir06") aapsLogger.debug(LTag.PUMPCOMM, "cf02: $cf02") aapsLogger.debug(LTag.PUMPCOMM, "cf04: $cf04") aapsLogger.debug(LTag.PUMPCOMM, "cf06: $cf06") } override fun getFriendlyName(): String { return "BOLUS__GET_CIR_CF_ARRAY" } }
agpl-3.0
49a678a3d7e183138f28892f82b74bff
45.016949
119
0.640449
4.616497
false
false
false
false
Raizlabs/DBFlow
processor/src/main/kotlin/com/dbflow5/processor/utils/ElementUtility.kt
1
2809
package com.dbflow5.processor.utils import com.dbflow5.annotation.ColumnIgnore import com.dbflow5.processor.ProcessorManager import com.squareup.javapoet.ClassName import javax.lang.model.element.Element import javax.lang.model.element.Modifier import javax.lang.model.element.TypeElement import javax.lang.model.type.TypeMirror /** * Description: */ object ElementUtility { /** * @return real full-set of elements, including ones from super-class. */ fun getAllElements(element: TypeElement, manager: ProcessorManager): List<Element> { val elements = manager.elements.getAllMembers(element).toMutableList() var superMirror: TypeMirror? var typeElement: TypeElement? = element while (typeElement?.superclass.let { superMirror = it; it != null }) { typeElement = manager.typeUtils.asElement(superMirror) as TypeElement? typeElement?.let { val superElements = manager.elements.getAllMembers(typeElement) superElements.forEach { if (!elements.contains(it)) elements += it } } } return elements } fun isInSamePackage(manager: ProcessorManager, elementToCheck: Element, original: Element): Boolean { return manager.elements.getPackageOf(elementToCheck).toString() == manager.elements.getPackageOf(original).toString() } fun isPackagePrivate(element: Element): Boolean { return !element.modifiers.contains(Modifier.PUBLIC) && !element.modifiers.contains(Modifier.PRIVATE) && !element.modifiers.contains(Modifier.STATIC) } fun isValidAllFields(allFields: Boolean, element: Element): Boolean { return allFields && element.kind.isField && !element.modifiers.contains(Modifier.STATIC) && !element.modifiers.contains(Modifier.FINAL) && element.annotation<ColumnIgnore>() == null } /** * Attempts to retrieve a [ClassName] from the [elementClassname] Fully-qualified name. If it * does not exist yet via [ClassName.get], we manually create the [ClassName] object to reference * later at compile time validation. */ fun getClassName(elementClassname: String, manager: ProcessorManager): ClassName? { val typeElement: TypeElement? = manager.elements.getTypeElement(elementClassname) return if (typeElement != null) { ClassName.get(typeElement) } else { val names = elementClassname.split(".") if (names.isNotEmpty()) { // attempt to take last part as class name val className = names[names.size - 1] ClassName.get(elementClassname.replace(".$className", ""), className) } else { null } } } }
mit
9faae455f08adc16e6238b9c334fc411
39.710145
125
0.664293
4.752961
false
false
false
false
kivensolo/UiUsingListView
module-Common/src/main/java/com/kingz/module/common/fragments/CommonPageFragment.kt
1
1322
package com.kingz.module.common.fragments import androidx.recyclerview.widget.RecyclerView import com.kingz.module.common.R import com.kingz.module.common.base.BaseFragment /** * author:KingZ * date:2020/2/22 * description:公共页面的Fragment */ open class CommonPageFragment: BaseFragment(){ // private var fabButton: FloatingActionButton? = null lateinit var mRecyclerView:RecyclerView companion object{ const val mContentLayoutResTag:String = "contentLayoutRes" // fun newInstance(content: View): CommonPageFragment { // val fragment = CommonPageFragment() // val args = Bundle() // args.putInt(mContentLayoutResTag, contentLayoutRes) // fragment.arguments = args // contentView = WeakReference(content) // return fragment // } } override fun getLayoutId(): Int { return R.layout.fragment_common_page } override fun onCreateViewReady() { super.onCreateViewReady() initRecyclerView() } open fun initRecyclerView(){ mRecyclerView = rootView!!.findViewById(R.id.recycler_view) as RecyclerView } override fun onViewCreated() { showLoadingView() } open fun showLoadingView(){ loadStatusView?.showEmpty() } }
gpl-2.0
1d8d5287fafd3fb13ad06d87c64cc413
24.627451
83
0.663093
4.664286
false
false
false
false
siosio/intellij-community
plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/view/XCoroutineView.kt
1
11184
// 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.debugger.coroutine.view import com.intellij.debugger.engine.SuspendContextImpl import com.intellij.ide.CommonActionsManager import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl import com.intellij.openapi.project.Project import com.intellij.openapi.ui.ComboBox import com.intellij.ui.CaptionPanel import com.intellij.ui.ComboboxSpeedSearch import com.intellij.ui.border.CustomLineBorder import com.intellij.ui.components.panels.Wrapper import com.intellij.util.SingleAlarm import com.intellij.xdebugger.XDebugSession import com.intellij.xdebugger.frame.* import com.intellij.xdebugger.impl.actions.XDebuggerActions import com.intellij.xdebugger.impl.ui.DebuggerUIUtil import com.intellij.xdebugger.impl.ui.tree.XDebuggerTreePanel import com.intellij.xdebugger.impl.ui.tree.XDebuggerTreeRestorer import com.intellij.xdebugger.impl.ui.tree.XDebuggerTreeState import com.intellij.xdebugger.impl.ui.tree.nodes.XValueContainerNode import com.sun.jdi.request.EventRequest import org.jetbrains.kotlin.idea.debugger.coroutine.CoroutineDebuggerContentInfo import org.jetbrains.kotlin.idea.debugger.coroutine.CoroutineDebuggerContentInfo.Companion.XCOROUTINE_POPUP_ACTION_GROUP import org.jetbrains.kotlin.idea.debugger.coroutine.KotlinDebuggerCoroutinesBundle import org.jetbrains.kotlin.idea.debugger.coroutine.VersionedImplementationProvider import org.jetbrains.kotlin.idea.debugger.coroutine.data.CoroutineInfoData import org.jetbrains.kotlin.idea.debugger.coroutine.data.CoroutineStackFrameItem import org.jetbrains.kotlin.idea.debugger.coroutine.data.CreationCoroutineStackFrameItem import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.CoroutineDebugProbesProxy import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.ManagerThreadExecutor import org.jetbrains.kotlin.idea.debugger.coroutine.util.* import java.awt.BorderLayout import javax.swing.JPanel class XCoroutineView(val project: Project, val session: XDebugSession) : Disposable, XDebugSessionListenerProvider, CreateContentParamsProvider { val log by logger private val versionedImplementationProvider = VersionedImplementationProvider() private val mainPanel = JPanel(BorderLayout()) val someCombobox = ComboBox<String>() val panel = XDebuggerTreePanel(project, session.debugProcess.editorsProvider, this, null, XCOROUTINE_POPUP_ACTION_GROUP, null) val alarm = SingleAlarm({ resetRoot() }, VIEW_CLEAR_DELAY, this) val renderer = SimpleColoredTextIconPresentationRenderer() val managerThreadExecutor = ManagerThreadExecutor(session) private var treeState: XDebuggerTreeState? = null private var restorer: XDebuggerTreeRestorer? = null private var selectedNodeListener: XDebuggerTreeSelectedNodeListener? = null companion object { private const val VIEW_CLEAR_DELAY = 100 //ms } init { someCombobox.renderer = versionedImplementationProvider.comboboxListCellRenderer() someCombobox.addItem(null) val myToolbar = createToolbar() val myThreadsPanel = Wrapper() myThreadsPanel.border = CustomLineBorder(CaptionPanel.CNT_ACTIVE_BORDER_COLOR, 0, 0, 1, 0) myThreadsPanel.add(myToolbar?.component, BorderLayout.EAST) myThreadsPanel.add(someCombobox, BorderLayout.CENTER) mainPanel.add(panel.mainPanel, BorderLayout.CENTER) selectedNodeListener = XDebuggerTreeSelectedNodeListener(session, panel.tree) selectedNodeListener?.installOn() } private fun createToolbar(): ActionToolbarImpl? { val framesGroup = DefaultActionGroup() val actionsManager = CommonActionsManager.getInstance() framesGroup .addAll(ActionManager.getInstance().getAction(XDebuggerActions.FRAMES_TOP_TOOLBAR_GROUP)) val toolbar = ActionManager.getInstance().createActionToolbar( ActionPlaces.DEBUGGER_TOOLBAR, framesGroup, true ) as ActionToolbarImpl toolbar.setReservePlaceAutoPopupIcon(false) return toolbar } fun saveState() { DebuggerUIUtil.invokeLater { if (panel.tree.root !is EmptyNode) { treeState = XDebuggerTreeState.saveState(panel.tree) } } } fun resetRoot() { DebuggerUIUtil.invokeLater { panel.tree.setRoot(EmptyNode(), false) } } fun renewRoot(suspendContext: SuspendContextImpl) { panel.tree.setRoot(XCoroutinesRootNode(suspendContext), false) if (treeState != null) { restorer?.dispose() restorer = treeState?.restoreState(panel.tree) } } override fun dispose() { if (restorer != null) { restorer?.dispose() restorer = null } } override fun debugSessionListener(session: XDebugSession) = CoroutineViewDebugSessionListener(session, this) override fun createContentParams(): CreateContentParams = CreateContentParams( CoroutineDebuggerContentInfo.XCOROUTINE_THREADS_CONTENT, mainPanel, KotlinDebuggerCoroutinesBundle.message("coroutine.view.title"), null, panel.tree ) @Suppress("RedundantInnerClassModifier") inner class EmptyNode : XValueContainerNode<XValueContainer>(panel.tree, null, true, object : XValueContainer() {}) inner class XCoroutinesRootNode(suspendContext: SuspendContextImpl) : XValueContainerNode<CoroutineTopGroupContainer>( panel.tree, null, false, CoroutineTopGroupContainer(suspendContext) ) inner class CoroutineTopGroupContainer(val suspendContext: SuspendContextImpl) : XValueContainer() { override fun computeChildren(node: XCompositeNode) { val children = XValueChildrenList() children.add(CoroutineGroupContainer(suspendContext)) node.addChildren(children, true) } } inner class CoroutineGroupContainer(val suspendContext: SuspendContextImpl) : RendererContainer(renderer.renderGroup(KotlinDebuggerCoroutinesBundle.message("coroutine.view.node.root"))) { override fun computeChildren(node: XCompositeNode) { if (suspendContext.suspendPolicy == EventRequest.SUSPEND_ALL) { managerThreadExecutor.on(suspendContext).invoke { val debugProbesProxy = CoroutineDebugProbesProxy(suspendContext) val emptyDispatcherName = KotlinDebuggerCoroutinesBundle.message("coroutine.view.dispatcher.empty") val coroutineCache = debugProbesProxy.dumpCoroutines() if (coroutineCache.isOk()) { val children = XValueChildrenList() val groups = coroutineCache.cache.groupBy { it.key.dispatcher } for (dispatcher in groups.keys) { children.add(CoroutineContainer(suspendContext, dispatcher ?: emptyDispatcherName, groups[dispatcher])) } if (children.size() > 0) node.addChildren(children, true) else node.addChildren(XValueChildrenList.singleton(InfoNode("coroutine.view.fetching.not_found")), true) } else { val errorNode = ErrorNode("coroutine.view.fetching.error") node.addChildren(XValueChildrenList.singleton(errorNode), true) } } } else { node.addChildren( XValueChildrenList.singleton(ErrorNode("to.enable.information.breakpoint.suspend.policy.should.be.set.to.all.threads")), true, ) } } } inner class CoroutineContainer( val suspendContext: SuspendContextImpl, val groupName: String, val coroutines: List<CoroutineInfoData>? ) : RendererContainer(renderer.renderGroup(groupName)) { override fun computeChildren(node: XCompositeNode) { val children = XValueChildrenList() if (coroutines != null) for (coroutineInfo in coroutines) { children.add(FramesContainer(coroutineInfo, suspendContext)) } if (children.size() > 0) node.addChildren(children, true) else node.addChildren(XValueChildrenList.singleton(InfoNode("coroutine.view.fetching.not_found")), true) } } inner class InfoNode(val error: String) : RendererContainer(renderer.renderInfoNode(error)) inner class ErrorNode(val error: String) : RendererContainer(renderer.renderErrorNode(error)) inner class FramesContainer( private val infoData: CoroutineInfoData, private val suspendContext: SuspendContextImpl ) : RendererContainer(renderer.render(infoData)) { override fun computeChildren(node: XCompositeNode) { managerThreadExecutor.on(suspendContext).invoke { val children = XValueChildrenList() val doubleFrameList = CoroutineFrameBuilder.build(infoData, suspendContext) doubleFrameList?.frames?.forEach { children.add(CoroutineFrameValue(it)) } doubleFrameList?.creationFrames?.let { children.add(CreationFramesContainer(infoData, it)) } node.addChildren(children, true) } } } inner class CreationFramesContainer( private val infoData: CoroutineInfoData, private val creationFrames: List<CreationCoroutineStackFrameItem> ) : RendererContainer(renderer.renderCreationNode(infoData)) { override fun computeChildren(node: XCompositeNode) { val children = XValueChildrenList() creationFrames.forEach { children.add(CoroutineFrameValue(it)) } node.addChildren(children, true) } } inner class CoroutineFrameValue(val frameItem: CoroutineStackFrameItem) : XNamedValue(frameItem.uniqueId()) { override fun computePresentation(node: XValueNode, place: XValuePlace) = applyRenderer(node, renderer.render(frameItem.location)) } private fun applyRenderer(node: XValueNode, presentation: SimpleColoredTextIcon) = node.setPresentation(presentation.icon, presentation.valuePresentation(), presentation.hasChildren) open inner class RendererContainer(val presentation: SimpleColoredTextIcon) : XNamedValue(presentation.simpleString()) { override fun computePresentation(node: XValueNode, place: XValuePlace) = applyRenderer(node, presentation) } }
apache-2.0
5103edb88a2adfa8ac6dea02f6cdf343
44.096774
191
0.697961
5.204281
false
false
false
false
siosio/intellij-community
platform/platform-impl/src/com/intellij/openapi/fileEditor/LayoutActionsFloatingToolbar.kt
1
2428
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.fileEditor import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl import com.intellij.openapi.editor.toolbar.floating.ToolbarVisibilityController import com.intellij.openapi.util.Disposer import com.intellij.ui.JBColor import java.awt.* import javax.swing.JComponent internal class LayoutActionsFloatingToolbar( parentComponent: JComponent, actionGroup: ActionGroup ) : ActionToolbarImpl(ActionPlaces.CONTEXT_TOOLBAR, actionGroup, true), Disposable { val visibilityController = ToolbarVisibilityController(false, parentComponent, this, this) init { Disposer.register(this, visibilityController) targetComponent = parentComponent setReservePlaceAutoPopupIcon(false) setMinimumButtonSize(Dimension(22, 22)) setSkipWindowAdjustments(true) isOpaque = false layoutPolicy = NOWRAP_LAYOUT_POLICY } override fun paintComponent(g: Graphics) { val graphics = g.create() try { if (graphics is Graphics2D) { val alpha = visibilityController.opacity * BACKGROUND_ALPHA if (alpha == 0.0f) { updateActionsImmediately() } graphics.composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha) graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) } graphics.color = BACKGROUND graphics.fillRoundRect(0, 0, bounds.width, bounds.height, 6, 6) super.paintComponent(graphics) } finally { graphics.dispose() } } override fun paintChildren(g: Graphics) { val graphics = g.create() try { if (graphics is Graphics2D) { val alpha = visibilityController.opacity * BACKGROUND_ALPHA graphics.composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha) } super.paintChildren(graphics) } finally { graphics.dispose() } } override fun dispose() = Unit companion object { private const val BACKGROUND_ALPHA = 0.75f private val BACKGROUND = JBColor.namedColor("Toolbar.Floating.background", JBColor(0xEDEDED, 0x454A4D)) } }
apache-2.0
1b9a8179cb8e34d40d323d94bc698048
33.197183
158
0.738056
4.513011
false
false
false
false
jwren/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/injection/MarkdownCodeFenceUtils.kt
1
5768
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.injection import com.intellij.lang.ASTNode import com.intellij.lang.injection.InjectedLanguageManager import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.templateLanguages.OuterLanguageElement import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.elementType import com.intellij.psi.util.siblings import org.intellij.plugins.markdown.lang.MarkdownTokenTypeSets import org.intellij.plugins.markdown.lang.MarkdownTokenTypes import org.intellij.plugins.markdown.lang.psi.MarkdownAstUtils.parents import org.intellij.plugins.markdown.lang.psi.impl.MarkdownCodeFence import org.intellij.plugins.markdown.lang.psi.impl.MarkdownCodeFenceImpl import org.intellij.plugins.markdown.util.MarkdownPsiUtil import org.intellij.plugins.markdown.util.hasType /** * Utility functions used to work with Markdown Code Fences */ object MarkdownCodeFenceUtils { /** Check if [node] is of CODE_FENCE type */ fun isCodeFence(node: ASTNode) = node.hasType(MarkdownTokenTypeSets.CODE_FENCE) /** Check if [node] inside CODE_FENCE */ fun inCodeFence(node: ASTNode) = node.parents(withSelf = false).any { it.hasType(MarkdownTokenTypeSets.CODE_FENCE) } /** * Consider using [MarkdownCodeFence.obtainFenceContent] since it caches its result. * * Get content of code fence as list of [PsiElement] * * @param withWhitespaces defines if whitespaces (including blockquote chars `>`) should be * included in returned list. Otherwise, only new-line would be added. * * @return non-empty list of elements or null */ @JvmStatic @Deprecated("Use getContent(MarkdownCodeFence) instead.") fun getContent(host: MarkdownCodeFenceImpl, withWhitespaces: Boolean): List<PsiElement>? { val children = host.firstChild?.siblings(forward = true, withSelf = true) ?: return null var elements = children.filter { (it !is OuterLanguageElement && (it.node.elementType == MarkdownTokenTypes.CODE_FENCE_CONTENT || (MarkdownPsiUtil.WhiteSpaces.isNewLine(it)) //WHITE_SPACES may also include `>` || (withWhitespaces && MarkdownTokenTypeSets.WHITE_SPACES.contains(it.elementType)) ) ) }.toList() //drop new line right after code fence lang definition if (elements.isNotEmpty() && MarkdownPsiUtil.WhiteSpaces.isNewLine(elements.first())) { elements = elements.drop(1) } //drop new right before code fence end if (elements.isNotEmpty() && MarkdownPsiUtil.WhiteSpaces.isNewLine(elements.last())) { elements = elements.dropLast(1) } return elements.takeIf { it.isNotEmpty() } } /** * Consider using [MarkdownCodeFence.obtainFenceContent], since it caches its result. */ @JvmStatic fun getContent(host: MarkdownCodeFence, withWhitespaces: Boolean): List<PsiElement>? { @Suppress("DEPRECATION") return getContent(host as MarkdownCodeFenceImpl, withWhitespaces) } /** * Check that code fence is reasonably formatted to accept injections * * Basically, it means that it has start and end code fence and at least * one line (even empty) of text. */ @JvmStatic @Deprecated("Use isAbleToAcceptInjections(MarkdownCodeFence) instead.") fun isAbleToAcceptInjections(host: MarkdownCodeFenceImpl): Boolean { if (host.children.all { !it.hasType(MarkdownTokenTypes.CODE_FENCE_END) } || host.children.all { !it.hasType(MarkdownTokenTypes.CODE_FENCE_START) }) { return false } val newlines = host.children.count { MarkdownPsiUtil.WhiteSpaces.isNewLine(it) } return newlines >= 2 } @JvmStatic fun isAbleToAcceptInjections(host: MarkdownCodeFence): Boolean { @Suppress("DEPRECATION") return isAbleToAcceptInjections(host as MarkdownCodeFenceImpl) } /** * Get valid empty range (in terms of Injection) for this code fence. * * Note, that this function should be used only if [getContent] * returns null */ @JvmStatic @Deprecated("Use getEmptyRange(MarkdownCodeFence) instead.") fun getEmptyRange(host: MarkdownCodeFenceImpl): TextRange { val start = host.children.find { it.hasType(MarkdownTokenTypes.FENCE_LANG) } ?: host.children.find { it.hasType(MarkdownTokenTypes.CODE_FENCE_START) } return TextRange.from(start!!.startOffsetInParent + start.textLength + 1, 0) } fun getEmptyRange(host: MarkdownCodeFence): TextRange { @Suppress("DEPRECATION") return getEmptyRange(host as MarkdownCodeFenceImpl) } /** * Get code fence if [element] is part of it. * * Would also work for injected elements. */ fun getCodeFence(element: PsiElement): MarkdownCodeFence? { return InjectedLanguageManager.getInstance(element.project).getInjectionHost(element) as? MarkdownCodeFence? ?: PsiTreeUtil.getParentOfType(element, MarkdownCodeFence::class.java) } /** * Get indent for this code fence. * * If code-fence is blockquoted indent may include `>` char. * Note that indent should be used only for non top-level fences, * top-level fences should use indentation from formatter. */ @JvmStatic fun getIndent(element: MarkdownCodeFence): String? { val document = PsiDocumentManager.getInstance(element.project).getDocument(element.containingFile) ?: return null val offset = element.textOffset val lineStartOffset = document.getLineStartOffset(document.getLineNumber(offset)) return document.getText(TextRange.create(lineStartOffset, offset)).replace("[^> ]".toRegex(), " ") } }
apache-2.0
8ea51676b3c517061ade00bfd65de104
39.342657
140
0.73665
4.440339
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertStringTemplateToBuildStringIntention.kt
2
2302
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.psi.* class ConvertStringTemplateToBuildStringIntention : SelfTargetingIntention<KtStringTemplateExpression>( KtStringTemplateExpression::class.java, KotlinBundle.lazyMessage("convert.string.template.to.build.string"), ), LowPriorityAction { override fun isApplicableTo(element: KtStringTemplateExpression, caretOffset: Int): Boolean { return !element.text.startsWith("\"\"\"") && !element.mustBeConstant() } override fun applyTo(element: KtStringTemplateExpression, editor: Editor?) { val entries: MutableList<MutableList<KtStringTemplateEntry>> = mutableListOf() var lastEntry: KtStringTemplateEntry? = null element.entries.forEachIndexed { index, entry -> if (index == 0 || entry is KtStringTemplateEntryWithExpression || lastEntry is KtStringTemplateEntryWithExpression) { entries.add(mutableListOf(entry)) } else { entries.last().add(entry) } lastEntry = entry } val buildStringCall = KtPsiFactory(element).buildExpression { appendFixedText("kotlin.text.buildString {\n") entries.forEach { val singleEntry = it.singleOrNull() appendFixedText("append(") if (singleEntry is KtStringTemplateEntryWithExpression) { appendExpression(singleEntry.expression) } else { appendFixedText("\"") it.forEach { entry -> appendNonFormattedText(entry.text) } appendFixedText("\"") } appendFixedText(")\n") } appendFixedText("}") } val replaced = element.replaced(buildStringCall) ShortenReferences.DEFAULT.process(replaced) } }
apache-2.0
86ca476baacb71dee09e3088e764c6d3
45.06
158
0.666377
5.600973
false
false
false
false
nrizzio/Signal-Android
contacts/lib/src/main/java/org/signal/contacts/SystemContactsRepository.kt
1
36403
package org.signal.contacts import android.accounts.Account import android.accounts.AccountManager import android.content.ContentProviderOperation import android.content.ContentResolver import android.content.Context import android.content.OperationApplicationException import android.database.Cursor import android.net.Uri import android.os.RemoteException import android.provider.BaseColumns import android.provider.ContactsContract import org.signal.core.util.SqlUtil import org.signal.core.util.logging.Log import org.signal.core.util.requireInt import org.signal.core.util.requireLong import org.signal.core.util.requireNonNullString import org.signal.core.util.requireString import java.io.Closeable import java.util.Objects /** * A way to retrieve and update data in the Android system contacts. * * Contacts in Android are miserable, but they're reasonably well-documented here: * https://developer.android.com/guide/topics/providers/contacts-provider * * But here's a summary of how contacts are stored. * * There's three main entities: * - Contacts * - RawContacts * - ContactData * * Each Contact can have multiple RawContacts associated with it, and each RawContact can have multiple ContactDatas associated with it. * * ┌───────Contact────────┐ * │ │ │ * ▼ ▼ ▼ * RawContact RawContact RawContact * │ │ │ * ├─►Data ├─►Data ├─►Data * │ │ │ * ├─►Data ├─►Data ├─►Data * │ │ │ * └─►Data └─►Data └─►Data * * (Shortened ContactData -> Data for space) * * How are they linked together? * - Each RawContact has a [ContactsContract.RawContacts.CONTACT_ID] that links to a [ContactsContract.Contacts._ID] * - Each ContactData has a [ContactsContract.Data.RAW_CONTACT_ID] column that links to a [ContactsContract.RawContacts._ID] * - Each ContactData has a [ContactsContract.Data.CONTACT_ID] column that links to a [ContactsContract.Contacts._ID] * - Each ContactData has a [ContactsContract.Data.LOOKUP_KEY] column that links to a [ContactsContract.Contacts.LOOKUP_KEY] * - The lookup key is a way to link back to a Contact in a more stable way. Apparently linking using the CONTACT_ID can lead to unstable results if a sync * is happening or data is otherwise corrupted. * * What type of stuff are stored in each? * - Contact only really has metadata about the contact. Basically the stuff you see at the top of the contact entry in the contacts app, like: * - Photo * - Display name (*not* structured name) * - Whether or not it's starred * - RawContact also only really has metadata, largely about which account it's bound to * - ContactData is where all the actual contact details are, stuff like: * - Phone * - Email * - Structured name * - Address * - ContactData has a [ContactsContract.Data.MIMETYPE] that will tell you what kind of data is it. Common ones are [ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE] * and [ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE] * - You can imagine that it's tricky to come up with a schema that can store arbitrary contact data -- that's why a lot of the columns in ContactData are just * generic things, like [ContactsContract.Data.DATA1]. Thankfully aliases have been provided for common types, like [ContactsContract.CommonDataKinds.Phone.NUMBER], * which is an alias for [ContactsContract.Data.DATA1]. * * */ object SystemContactsRepository { private val TAG = Log.tag(SystemContactsRepository::class.java) private const val FIELD_DISPLAY_PHONE = ContactsContract.RawContacts.SYNC1 private const val FIELD_TAG = ContactsContract.Data.SYNC2 private const val FIELD_SUPPORTS_VOICE = ContactsContract.RawContacts.SYNC4 /** * Gets and returns an iterator over data for all contacts, containing both phone number data and structured name data. * * In order to get all of this in one query, we have to query all of the ContactData items with the appropriate mimetypes, and then group it together by * lookup key. */ @JvmStatic fun getAllSystemContacts(context: Context, e164Formatter: (String) -> String): ContactIterator { val uri = ContactsContract.Data.CONTENT_URI val projection = arrayOf( ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.LABEL, ContactsContract.CommonDataKinds.Phone.PHOTO_URI, ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY, ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME ) val where = "${ContactsContract.Data.MIMETYPE} IN (?, ?)" val args = SqlUtil.buildArgs(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE) val orderBy = "${ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY} ASC, ${ContactsContract.Data.MIMETYPE} DESC, ${ContactsContract.CommonDataKinds.Phone._ID} DESC" val cursor: Cursor = context.contentResolver.query(uri, projection, where, args, orderBy) ?: return EmptyContactIterator() return CursorContactIterator(cursor, e164Formatter) } @JvmStatic fun getContactDetailsByQueries(context: Context, queries: List<String>, e164Formatter: (String) -> String): ContactIterator { val lookupKeys: MutableSet<String> = mutableSetOf() for (query in queries) { val lookupKeyUri: Uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_FILTER_URI, Uri.encode(query)) context.contentResolver.query(lookupKeyUri, arrayOf(ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY), null, null, null).use { cursor -> while (cursor != null && cursor.moveToNext()) { val lookup: String? = cursor.requireString(ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY) if (lookup != null) { lookupKeys += lookup } } } } if (lookupKeys.isEmpty()) { return EmptyContactIterator() } val uri = ContactsContract.Data.CONTENT_URI val projection = arrayOf( ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.LABEL, ContactsContract.CommonDataKinds.Phone.PHOTO_URI, ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY, ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME ) val lookupPlaceholder = lookupKeys.map { "?" }.joinToString(separator = ",") val where = "${ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY} IN ($lookupPlaceholder) AND ${ContactsContract.Data.MIMETYPE} IN (?, ?)" val args = lookupKeys.toTypedArray() + SqlUtil.buildArgs(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE) val orderBy = "${ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY} ASC, ${ContactsContract.Data.MIMETYPE} DESC, ${ContactsContract.CommonDataKinds.Phone._ID} DESC" val cursor: Cursor = context.contentResolver.query(uri, projection, where, args, orderBy) ?: return EmptyContactIterator() return CursorContactIterator(cursor, e164Formatter) } /** * Retrieves all unique display numbers in the system contacts. (By display, we mean not-E164-formatted) */ @JvmStatic fun getAllDisplayNumbers(context: Context): Set<String> { val results: MutableSet<String> = mutableSetOf() context.contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, arrayOf(ContactsContract.CommonDataKinds.Phone.NUMBER), null, null, null).use { cursor -> while (cursor != null && cursor.moveToNext()) { val formattedPhone: String? = cursor.requireString(ContactsContract.CommonDataKinds.Phone.NUMBER) if (formattedPhone != null && formattedPhone.isNotEmpty()) { results.add(formattedPhone) } } } return results } /** * Retrieves a system account for the provided applicationId, creating one if necessary. */ @JvmStatic fun getOrCreateSystemAccount(context: Context, applicationId: String, accountDisplayName: String): Account? { val accountManager: AccountManager = AccountManager.get(context) val accounts: Array<Account> = accountManager.getAccountsByType(applicationId) var account: Account? = if (accounts.isNotEmpty()) accounts[0] else null if (account == null) { try { Log.i(TAG, "Attempting to create a new account...") val newAccount = Account(accountDisplayName, applicationId) if (accountManager.addAccountExplicitly(newAccount, null, null)) { Log.i(TAG, "Successfully created a new account.") ContentResolver.setIsSyncable(newAccount, ContactsContract.AUTHORITY, 1) account = newAccount } else { Log.w(TAG, "Failed to create a new account!") } } catch (e: SecurityException) { Log.w(TAG, "Failed to add an account.", e) } } if (account != null && !ContentResolver.getSyncAutomatically(account, ContactsContract.AUTHORITY)) { Log.i(TAG, "Updated account to sync automatically.") ContentResolver.setSyncAutomatically(account, ContactsContract.AUTHORITY, true) } return account } /** * Deletes all raw contacts the specified account that are flagged as deleted. */ @JvmStatic @Synchronized fun removeDeletedRawContactsForAccount(context: Context, account: Account) { val currentContactsUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon() .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, account.name) .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, account.type) .appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true") .build() val projection = arrayOf(BaseColumns._ID, FIELD_DISPLAY_PHONE) // TODO Could we write this as a single delete(DELETED = true)? context.contentResolver.query(currentContactsUri, projection, "${ContactsContract.RawContacts.DELETED} = ?", SqlUtil.buildArgs(1), null)?.use { cursor -> while (cursor.moveToNext()) { val rawContactId = cursor.requireLong(BaseColumns._ID) Log.i(TAG, "Deleting raw contact: ${cursor.requireString(FIELD_DISPLAY_PHONE)}, $rawContactId") context.contentResolver.delete(currentContactsUri, "${ContactsContract.RawContacts._ID} = ?", SqlUtil.buildArgs(rawContactId)) } } } /** * Adds links to message and call using your app to the system contacts. * [config] Your configuration object. * [targetE164s] A list of E164s whose contact entries you would like to add links to. * [removeIfMissing] If true, links will be removed from all contacts not in the [targetE164s]. */ @JvmStatic @Synchronized @Throws(RemoteException::class, OperationApplicationException::class) fun addMessageAndCallLinksToContacts( context: Context, config: ContactLinkConfiguration, targetE164s: Set<String>, removeIfMissing: Boolean ) { val operations: ArrayList<ContentProviderOperation> = ArrayList() val currentLinkedContacts: Map<String, LinkedContactDetails> = getLinkedContactsByE164(context, config.account, config.e164Formatter) val targetChunks: List<List<String>> = targetE164s.chunked(50).toList() for (targetChunk in targetChunks) { for (target in targetChunk) { if (!currentLinkedContacts.containsKey(target)) { val systemContactInfo: SystemContactInfo? = getSystemContactInfo(context, target, config.e164Formatter) if (systemContactInfo != null) { Log.i(TAG, "Adding number: $target") operations += buildAddRawContactOperations( operationIndex = operations.size, linkConfig = config, systemContactInfo = systemContactInfo ) } } } if (operations.isNotEmpty()) { context.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations) operations.clear() } } for ((e164, details) in currentLinkedContacts) { if (!targetE164s.contains(e164)) { if (removeIfMissing) { Log.i(TAG, "Removing number: $e164") removeLinkedContact(operations, config.account, details.id) } } else if (!Objects.equals(details.rawDisplayName, details.aggregateDisplayName)) { Log.i(TAG, "Updating display name: $e164") operations += buildUpdateDisplayNameOperations(details.aggregateDisplayName, details.id, details.displayNameSource) } } if (operations.isNotEmpty()) { operations .chunked(50) .forEach { batch -> context.contentResolver.applyBatch(ContactsContract.AUTHORITY, ArrayList(batch)) } } } @JvmStatic fun getNameDetails(context: Context, contactId: Long): NameDetails? { val projection = arrayOf( ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, ContactsContract.CommonDataKinds.StructuredName.PREFIX, ContactsContract.CommonDataKinds.StructuredName.SUFFIX, ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME ) val selection = "${ContactsContract.Data.CONTACT_ID} = ? AND ${ContactsContract.Data.MIMETYPE} = ?" val args = SqlUtil.buildArgs(contactId, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE) return context.contentResolver.query(ContactsContract.Data.CONTENT_URI, projection, selection, args, null)?.use { cursor -> if (cursor.moveToFirst()) { NameDetails( displayName = cursor.requireString(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME), givenName = cursor.requireString(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME), familyName = cursor.requireString(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME), prefix = cursor.requireString(ContactsContract.CommonDataKinds.StructuredName.PREFIX), suffix = cursor.requireString(ContactsContract.CommonDataKinds.StructuredName.SUFFIX), middleName = cursor.requireString(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME) ) } else { null } } } @JvmStatic fun getOrganizationName(context: Context, contactId: Long): String? { val projection = arrayOf(ContactsContract.CommonDataKinds.Organization.COMPANY) val selection = "${ContactsContract.Data.CONTACT_ID} = ? AND ${ContactsContract.Data.MIMETYPE} = ?" val args = SqlUtil.buildArgs(contactId, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE) context.contentResolver.query(ContactsContract.Data.CONTENT_URI, projection, selection, args, null)?.use { cursor -> if (cursor.moveToFirst()) { return cursor.getString(0) } } return null } @JvmStatic fun getPhoneDetails(context: Context, contactId: Long): List<PhoneDetails> { val projection = arrayOf( ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.LABEL ) val selection = "${ContactsContract.Data.CONTACT_ID} = ? AND ${ContactsContract.Data.MIMETYPE} = ?" val args = SqlUtil.buildArgs(contactId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE) val phoneDetails: MutableList<PhoneDetails> = mutableListOf() context.contentResolver.query(ContactsContract.Data.CONTENT_URI, projection, selection, args, null)?.use { cursor -> while (cursor.moveToNext()) { phoneDetails += PhoneDetails( number = cursor.requireString(ContactsContract.CommonDataKinds.Phone.NUMBER), type = cursor.requireInt(ContactsContract.CommonDataKinds.Phone.TYPE), label = cursor.requireString(ContactsContract.CommonDataKinds.Phone.LABEL) ) } } return phoneDetails } @JvmStatic fun getEmailDetails(context: Context, contactId: Long): List<EmailDetails> { val projection = arrayOf( ContactsContract.CommonDataKinds.Email.ADDRESS, ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.LABEL ) val selection = "${ContactsContract.Data.CONTACT_ID} = ? AND ${ContactsContract.Data.MIMETYPE} = ?" val args = SqlUtil.buildArgs(contactId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE) val emailDetails: MutableList<EmailDetails> = mutableListOf() context.contentResolver.query(ContactsContract.Data.CONTENT_URI, projection, selection, args, null)?.use { cursor -> while (cursor.moveToNext()) { emailDetails += EmailDetails( address = cursor.requireString(ContactsContract.CommonDataKinds.Email.ADDRESS), type = cursor.requireInt(ContactsContract.CommonDataKinds.Email.TYPE), label = cursor.requireString(ContactsContract.CommonDataKinds.Email.LABEL) ) } } return emailDetails } @JvmStatic fun getPostalAddressDetails(context: Context, contactId: Long): List<PostalAddressDetails> { val projection = arrayOf( ContactsContract.CommonDataKinds.StructuredPostal.TYPE, ContactsContract.CommonDataKinds.StructuredPostal.LABEL, ContactsContract.CommonDataKinds.StructuredPostal.STREET, ContactsContract.CommonDataKinds.StructuredPostal.POBOX, ContactsContract.CommonDataKinds.StructuredPostal.NEIGHBORHOOD, ContactsContract.CommonDataKinds.StructuredPostal.CITY, ContactsContract.CommonDataKinds.StructuredPostal.REGION, ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY ) val selection = "${ContactsContract.Data.CONTACT_ID} = ? AND ${ContactsContract.Data.MIMETYPE} = ?" val args = SqlUtil.buildArgs(contactId, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE) val postalDetails: MutableList<PostalAddressDetails> = mutableListOf() context.contentResolver.query(ContactsContract.Data.CONTENT_URI, projection, selection, args, null)?.use { cursor -> while (cursor.moveToNext()) { postalDetails += PostalAddressDetails( type = cursor.requireInt(ContactsContract.CommonDataKinds.StructuredPostal.TYPE), label = cursor.requireString(ContactsContract.CommonDataKinds.StructuredPostal.LABEL), street = cursor.requireString(ContactsContract.CommonDataKinds.StructuredPostal.STREET), poBox = cursor.requireString(ContactsContract.CommonDataKinds.StructuredPostal.POBOX), neighborhood = cursor.requireString(ContactsContract.CommonDataKinds.StructuredPostal.NEIGHBORHOOD), city = cursor.requireString(ContactsContract.CommonDataKinds.StructuredPostal.CITY), region = cursor.requireString(ContactsContract.CommonDataKinds.StructuredPostal.REGION), postal = cursor.requireString(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE), country = cursor.requireString(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY) ) } } return postalDetails } @JvmStatic fun getAvatarUri(context: Context, contactId: Long): Uri? { val projection = arrayOf(ContactsContract.CommonDataKinds.Photo.PHOTO_URI) val selection = "${ContactsContract.Data.CONTACT_ID} = ? AND ${ContactsContract.Data.MIMETYPE} = ?" val args = SqlUtil.buildArgs(contactId, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE) context.contentResolver.query(ContactsContract.Data.CONTENT_URI, projection, selection, args, null)?.use { cursor -> if (cursor.moveToFirst()) { val uri = cursor.getString(0) if (uri != null) { return Uri.parse(uri) } } } return null } private fun buildUpdateDisplayNameOperations( displayName: String?, rawContactId: Long, displayNameSource: Int ): ContentProviderOperation { val dataUri = ContactsContract.Data.CONTENT_URI.buildUpon() .appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true") .build() return if (displayNameSource != ContactsContract.DisplayNameSources.STRUCTURED_NAME) { ContentProviderOperation.newInsert(dataUri) .withValue(ContactsContract.CommonDataKinds.StructuredName.RAW_CONTACT_ID, rawContactId) .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE) .build() } else { ContentProviderOperation.newUpdate(dataUri) .withSelection("${ContactsContract.CommonDataKinds.StructuredName.RAW_CONTACT_ID} = ? AND ${ContactsContract.Data.MIMETYPE} = ?", SqlUtil.buildArgs(rawContactId.toString(), ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)) .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE) .build() } } private fun buildAddRawContactOperations( operationIndex: Int, linkConfig: ContactLinkConfiguration, systemContactInfo: SystemContactInfo ): List<ContentProviderOperation> { val dataUri = ContactsContract.Data.CONTENT_URI.buildUpon() .appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true") .build() return listOf( // RawContact entry ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI) .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, linkConfig.account.name) .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, linkConfig.account.type) .withValue(FIELD_DISPLAY_PHONE, systemContactInfo.displayPhone) .withValue(FIELD_SUPPORTS_VOICE, true.toString()) .build(), // Data entry for name ContentProviderOperation.newInsert(dataUri) .withValueBackReference(ContactsContract.CommonDataKinds.StructuredName.RAW_CONTACT_ID, operationIndex) .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, systemContactInfo.displayName) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE) .build(), // Data entry for number (Note: This may not be necessary) ContentProviderOperation.newInsert(dataUri) .withValueBackReference(ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID, operationIndex) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, systemContactInfo.displayPhone) .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, systemContactInfo.type) .withValue(FIELD_TAG, linkConfig.syncTag) .build(), // Data entry for sending a message ContentProviderOperation.newInsert(dataUri) .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, operationIndex) .withValue(ContactsContract.Data.MIMETYPE, linkConfig.messageMimetype) .withValue(ContactsContract.Data.DATA1, systemContactInfo.displayPhone) .withValue(ContactsContract.Data.DATA2, linkConfig.appName) .withValue(ContactsContract.Data.DATA3, linkConfig.messagePrompt(systemContactInfo.displayPhone)) .withYieldAllowed(true) .build(), // Data entry for making a call ContentProviderOperation.newInsert(dataUri) .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, operationIndex) .withValue(ContactsContract.Data.MIMETYPE, linkConfig.callMimetype) .withValue(ContactsContract.Data.DATA1, systemContactInfo.displayPhone) .withValue(ContactsContract.Data.DATA2, linkConfig.appName) .withValue(ContactsContract.Data.DATA3, linkConfig.callPrompt(systemContactInfo.displayPhone)) .withYieldAllowed(true) .build(), // Ensures that this RawContact entry is shown next to another RawContact entry we found for this contact ContentProviderOperation.newUpdate(ContactsContract.AggregationExceptions.CONTENT_URI) .withValue(ContactsContract.AggregationExceptions.RAW_CONTACT_ID1, systemContactInfo.siblingRawContactId) .withValueBackReference(ContactsContract.AggregationExceptions.RAW_CONTACT_ID2, operationIndex) .withValue(ContactsContract.AggregationExceptions.TYPE, ContactsContract.AggregationExceptions.TYPE_KEEP_TOGETHER) .build() ) } private fun removeLinkedContact(operations: MutableList<ContentProviderOperation>, account: Account, rowId: Long) { operations.add( ContentProviderOperation.newDelete( ContactsContract.RawContacts.CONTENT_URI.buildUpon() .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, account.name) .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, account.type) .appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true") .build() ) .withYieldAllowed(true) .withSelection("${BaseColumns._ID} = ?", SqlUtil.buildArgs(rowId)) .build() ) } private fun getLinkedContactsByE164(context: Context, account: Account, e164Formatter: (String) -> String): Map<String, LinkedContactDetails> { val currentContactsUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon() .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, account.name) .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, account.type).build() val projection = arrayOf( BaseColumns._ID, FIELD_DISPLAY_PHONE, FIELD_SUPPORTS_VOICE, ContactsContract.RawContacts.CONTACT_ID, ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY, ContactsContract.RawContacts.DISPLAY_NAME_SOURCE ) val contactsDetails: MutableMap<String, LinkedContactDetails> = HashMap() context.contentResolver.query(currentContactsUri, projection, null, null, null)?.use { cursor -> while (cursor.moveToNext()) { val displayPhone = cursor.requireString(FIELD_DISPLAY_PHONE) if (displayPhone != null) { val e164 = e164Formatter(displayPhone) contactsDetails[e164] = LinkedContactDetails( id = cursor.requireLong(BaseColumns._ID), supportsVoice = cursor.requireString(FIELD_SUPPORTS_VOICE), rawDisplayName = cursor.requireString(ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY), aggregateDisplayName = getDisplayName(context, cursor.requireLong(ContactsContract.RawContacts.CONTACT_ID)), displayNameSource = cursor.requireInt(ContactsContract.RawContacts.DISPLAY_NAME_SOURCE) ) } } } return contactsDetails } private fun getSystemContactInfo(context: Context, e164: String, e164Formatter: (String) -> String): SystemContactInfo? { ContactsContract.RawContactsEntity.RAW_CONTACT_ID val uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(e164)) val projection = arrayOf( ContactsContract.PhoneLookup.NUMBER, ContactsContract.PhoneLookup._ID, ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup.TYPE, ) context.contentResolver.query(uri, projection, null, null, null)?.use { contactCursor -> while (contactCursor.moveToNext()) { val systemNumber: String? = contactCursor.requireString(ContactsContract.PhoneLookup.NUMBER) if (systemNumber != null && e164Formatter(systemNumber) == e164) { val phoneLookupId = contactCursor.requireLong(ContactsContract.PhoneLookup._ID) context.contentResolver.query(ContactsContract.RawContacts.CONTENT_URI, arrayOf(ContactsContract.RawContacts._ID), "${ContactsContract.RawContacts.CONTACT_ID} = ? ", SqlUtil.buildArgs(phoneLookupId), null)?.use { idCursor -> if (idCursor.moveToNext()) { return SystemContactInfo( displayName = contactCursor.requireString(ContactsContract.PhoneLookup.DISPLAY_NAME), displayPhone = systemNumber, siblingRawContactId = idCursor.requireLong(ContactsContract.RawContacts._ID), type = contactCursor.requireInt(ContactsContract.PhoneLookup.TYPE) ) } } } } } return null } private fun getDisplayName(context: Context, contactId: Long): String? { val projection = arrayOf(ContactsContract.Contacts.DISPLAY_NAME) val selection = "${ContactsContract.Contacts._ID} = ?" val args = SqlUtil.buildArgs(contactId) context.contentResolver.query(ContactsContract.Contacts.CONTENT_URI, projection, selection, args, null)?.use { cursor -> if (cursor.moveToFirst()) { return cursor.getString(0) } } return null } interface ContactIterator : Iterator<ContactDetails>, Closeable { @Throws override fun close() { } } private class EmptyContactIterator : ContactIterator { override fun close() {} override fun hasNext(): Boolean = false override fun next(): ContactDetails = throw NoSuchElementException() } /** * Remember cursor rows are ordered by the following params: * 1. Contact Lookup Key ASC * 1. Mimetype ASC * 1. id DESC * * The lookup key is a fixed value that allows you to verify two rows in the database actually * belong to the same contact, since the contact uri can be unstable (if a sync fails, say.) * * We order by id explicitly here for the same contact sync failure error, which could result in * multiple structured name rows for the same user. By ordering by id DESC, we ensure that the * latest name is first in the cursor. * * What this results in is a cursor that looks like: * * Alice phone 2 * Alice phone 1 * Alice structured name 2 * Alice structured name 1 * Bob phone 1 * ... etc. * * The general idea of how this is implemented: * - Assume you're already on the correct row at the start of [next]. * - Store the lookup key from the first row. * - Read all phone entries for that lookup key and store them. * - Read the first name entry for that lookup key and store it. * - Skip all other rows for that lookup key. This will ensure that you're on the correct row for the next call to [next] */ private class CursorContactIterator( private val cursor: Cursor, private val e164Formatter: (String) -> String ) : ContactIterator { init { cursor.moveToFirst() } override fun hasNext(): Boolean { return !cursor.isAfterLast && cursor.position >= 0 } override fun next(): ContactDetails { if (cursor.isAfterLast || cursor.position < 0) { throw NoSuchElementException() } val lookupKey: String = cursor.getLookupKey() val phoneDetails: List<ContactPhoneDetails> = readAllPhones(cursor, lookupKey) val structuredName: StructuredName? = readStructuredName(cursor, lookupKey) while (!cursor.isAfterLast && cursor.position >= 0 && cursor.getLookupKey() == lookupKey) { cursor.moveToNext() } return ContactDetails( givenName = structuredName?.givenName, familyName = structuredName?.familyName, numbers = phoneDetails ) } override fun close() { cursor.close() } fun readAllPhones(cursor: Cursor, lookupKey: String): List<ContactPhoneDetails> { val phoneDetails: MutableList<ContactPhoneDetails> = mutableListOf() while (!cursor.isAfterLast && lookupKey == cursor.getLookupKey() && cursor.isPhoneMimeType()) { val displayNumber: String? = cursor.requireString(ContactsContract.CommonDataKinds.Phone.NUMBER) if (displayNumber != null && displayNumber.isNotEmpty()) { phoneDetails += ContactPhoneDetails( contactUri = ContactsContract.Contacts.getLookupUri(cursor.requireLong(ContactsContract.CommonDataKinds.Phone._ID), lookupKey), displayName = cursor.requireString(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME), photoUri = cursor.requireString(ContactsContract.CommonDataKinds.Phone.PHOTO_URI), number = e164Formatter(displayNumber), type = cursor.requireInt(ContactsContract.CommonDataKinds.Phone.TYPE), label = cursor.requireString(ContactsContract.CommonDataKinds.Phone.LABEL), ) } else { Log.w(TAG, "Skipping phone entry with invalid number!") } cursor.moveToNext() } // You may get duplicates of the same phone number with different types. // This dedupes by taking the entry with the lowest phone type. return phoneDetails .groupBy { it.number } .mapValues { entry -> entry.value.minByOrNull { it.type }!! } .values .toList() } fun readStructuredName(cursor: Cursor, lookupKey: String): StructuredName? { return if (!cursor.isAfterLast && cursor.getLookupKey() == lookupKey && cursor.isNameMimeType()) { StructuredName( givenName = cursor.requireString(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME), familyName = cursor.requireString(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME) ) } else { null } } fun Cursor.getLookupKey(): String { return requireNonNullString(ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY) } fun Cursor.isPhoneMimeType(): Boolean { return requireString(ContactsContract.Data.MIMETYPE) == ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE } fun Cursor.isNameMimeType(): Boolean { return requireString(ContactsContract.Data.MIMETYPE) == ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE } fun firstNonEmpty(s1: String?, s2: String): String { return if (s1 != null && s1.isNotEmpty()) s1 else s2 } } data class ContactDetails( val givenName: String?, val familyName: String?, val numbers: List<ContactPhoneDetails> ) data class ContactPhoneDetails( val contactUri: Uri, val displayName: String?, val photoUri: String?, val number: String, val type: Int, val label: String? ) data class NameDetails( val displayName: String?, val givenName: String?, val familyName: String?, val prefix: String?, val suffix: String?, val middleName: String? ) data class PhoneDetails( val number: String?, val type: Int, val label: String? ) data class EmailDetails( val address: String?, val type: Int, val label: String? ) data class PostalAddressDetails( val type: Int, val label: String?, val street: String?, val poBox: String?, val neighborhood: String?, val city: String?, val region: String?, val postal: String?, val country: String? ) private data class LinkedContactDetails( val id: Long, val supportsVoice: String?, val rawDisplayName: String?, val aggregateDisplayName: String?, val displayNameSource: Int ) private data class SystemContactInfo( val displayName: String?, val displayPhone: String, val siblingRawContactId: Long, val type: Int ) private data class StructuredName(val givenName: String?, val familyName: String?) }
gpl-3.0
40716c4c88a72a511f1d6102fb2c1d68
42.507194
248
0.717955
4.711726
false
false
false
false
GunoH/intellij-community
plugins/kotlin/code-insight/line-markers/src/org/jetbrains/kotlin/idea/codeInsight/lineMarkers/KotlinRecursiveCallLineMarkerProvider.kt
1
6438
// 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.codeInsight.lineMarkers import com.intellij.codeInsight.daemon.LineMarkerInfo import com.intellij.codeInsight.daemon.LineMarkerProvider import com.intellij.codeInsight.daemon.MergeableLineMarkerInfo import com.intellij.icons.AllIcons import com.intellij.openapi.editor.markup.GutterIconRenderer import com.intellij.openapi.util.NlsSafe import com.intellij.psi.PsiElement import com.intellij.psi.SmartPsiElementPointer import com.intellij.refactoring.suggested.createSmartPointer import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.calls.KtExplicitReceiverValue import org.jetbrains.kotlin.analysis.api.calls.KtImplicitReceiverValue import org.jetbrains.kotlin.analysis.api.calls.KtSmartCastedReceiverValue import org.jetbrains.kotlin.analysis.api.symbols.* import org.jetbrains.kotlin.idea.base.codeInsight.CallTarget import org.jetbrains.kotlin.idea.base.codeInsight.KotlinCallProcessor import org.jetbrains.kotlin.idea.base.codeInsight.process import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.isAncestor import org.jetbrains.kotlin.psi.psiUtil.parents internal class KotlinRecursiveCallLineMarkerProvider : LineMarkerProvider { override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<*>? = null override fun collectSlowLineMarkers(elements: MutableList<out PsiElement>, result: MutableCollection<in LineMarkerInfo<*>>) { KotlinCallProcessor.process(elements) { target -> val symbol = target.symbol val targetDeclaration = target.symbol.psi as? KtDeclaration ?: return@process if (symbol.origin == KtSymbolOrigin.SOURCE_MEMBER_GENERATED || !targetDeclaration.isAncestor(target.caller)) { return@process } if (isRecursiveCall(target, targetDeclaration)) { @NlsSafe val declarationName = when (symbol) { is KtVariableLikeSymbol -> symbol.name.asString() is KtFunctionSymbol -> symbol.name.asString() + "()" is KtPropertyGetterSymbol -> "get()" is KtPropertySetterSymbol -> "set()" is KtConstructorSymbol -> "constructor()" else -> return@process } val message = KotlinLineMarkersBundle.message("line.markers.recursive.call.description") result += RecursiveCallLineMarkerInfo(target.anchorLeaf, message, declarationName, targetDeclaration.createSmartPointer()) } } } private fun KtAnalysisSession.isRecursiveCall(target: CallTarget, targetDeclaration: PsiElement): Boolean { for (parent in target.caller.parents) { when (parent) { targetDeclaration -> return checkDispatchReceiver(target) is KtPropertyAccessor -> {} // Skip, handle in 'KtProperty' is KtProperty -> if (!parent.isLocal) return false is KtDestructuringDeclaration -> {} // Skip, destructuring declaration is not a scoping declaration is KtFunctionLiteral -> {} // Count calls inside lambdas is KtNamedFunction -> if (parent.nameIdentifier != null) return false // Count calls inside anonymous functions is KtObjectDeclaration -> if (!parent.isObjectLiteral()) return false is KtDeclaration -> return false } } return false } private fun KtAnalysisSession.checkDispatchReceiver(target: CallTarget): Boolean { var dispatchReceiver = target.partiallyAppliedSymbol.dispatchReceiver ?: return true while (dispatchReceiver is KtSmartCastedReceiverValue) { dispatchReceiver = dispatchReceiver.original } val containingClass = target.symbol.getContainingSymbol() as? KtClassOrObjectSymbol ?: return true if (dispatchReceiver is KtExplicitReceiverValue) { if (dispatchReceiver.isSafeNavigation) { return false } return when (val expression = KtPsiUtil.deparenthesize(dispatchReceiver.expression)) { is KtThisExpression -> expression.instanceReference.mainReference.resolveToSymbol() == containingClass is KtExpression -> when (val receiverSymbol = expression.mainReference?.resolveToSymbol()) { is KtFunctionSymbol -> { receiverSymbol.isOperator && receiverSymbol.name.asString() == "invoke" && containingClass.classKind.isObject && receiverSymbol.getContainingSymbol() == containingClass } is KtClassOrObjectSymbol -> { receiverSymbol.classKind.isObject && receiverSymbol == containingClass } else -> false } else -> false } } if (dispatchReceiver is KtImplicitReceiverValue) { return dispatchReceiver.symbol == containingClass } return false } private class RecursiveCallLineMarkerInfo( anchor: PsiElement, message: String, @NlsSafe private val declarationName: String, targetElementPointer: SmartPsiElementPointer<PsiElement>?, ) : MergeableLineMarkerInfo<PsiElement>( /* element = */ anchor, /* textRange = */ anchor.textRange, /* icon = */ AllIcons.Gutter.RecursiveMethod, /* tooltipProvider = */ { message }, /* navHandler = */ targetElementPointer?.let(::SimpleNavigationHandler), /* alignment = */ GutterIconRenderer.Alignment.RIGHT, /* accessibleNameProvider = */ { message } ) { override fun createGutterRenderer() = LineMarkerGutterIconRenderer(this) override fun getElementPresentation(element: PsiElement) = declarationName override fun canMergeWith(info: MergeableLineMarkerInfo<*>) = info is RecursiveCallLineMarkerInfo override fun getCommonIcon(infos: List<MergeableLineMarkerInfo<*>>) = infos.firstNotNullOf { it.icon } } }
apache-2.0
0fc96048be31689ebcd591f8ab20ca71
48.530769
138
0.669307
5.768817
false
false
false
false
vovagrechka/fucking-everything
alraune/alraune/src/main/java/alraune/wasing-rps.kt
1
6526
package alraune import alraune.operations.* import vgrechka.* import wasing.Drawing import wasing.waConfig import java.io.File import java.io.FileInputStream import java.io.InputStreamReader class WasingRP_SaveDrawing(val drawingURLPath: String, val html: String, val simulateError: SimulateError?): Dancer<Any> { enum class SimulateError {HTTP_500, NonNullErrorString} class Poop(val error: String) class Candy override fun dance(): Any { // clog("[${simpleClassName(this)}] drawingURLPath = $drawingURLPath; html = $html") exhaustive=when (simulateError) { SimulateError.HTTP_500 -> bitch("Simulating 500") SimulateError.NonNullErrorString -> return Poop("What? Save drawing? Fuck you...") null -> {} } // val document = Jsoup.parse(html) // for (el in document.select("*")) // el.removeAttr("id") // for (el in document.select(".${BTFConst.Wasing.CSSClass.removeWhenSaving}")) // el.remove() // document.outputSettings().prettyPrint(true).indentAmount(4) // val fuckedHTML = document.body().child(0).outerHtml() val fuckedHTML = html wasing.Drawing.fromURLPath(drawingURLPath).writeHTML(html) return Candy() } } class WasingRP_MakeVersion(val p: Params) : Dancer<Any> { class Poop(val error: String) class Candy(val newURL: String) class Params { var drawingURLPath by place<String>() var html by place<String>() var crop: Crop? = null var changeFirstPathSegment: String? = null var removeSourceVersion: Boolean? = null } class Crop { var left by place<Double>() var top by place<Double>() var width by place<Double>() var height by place<Double>() } override fun dance(): Any { clog("drawingURLPath", p.drawingURLPath) val currentDrawing = wasing.Drawing.fromURLPath(p.drawingURLPath) var path = currentDrawing.pathBeforeVersion p.changeFirstPathSegment?.let {subst-> val segments = path.split("/") check(segments.size == 2) // TODO:vgrechka ..... path = subst + "/" + segments[1] } val dirWithVersions = File(waConfig.dataDir + "/" + path) if (!dirWithVersions.exists()) check(dirWithVersions.mkdirs()) else check(dirWithVersions.isDirectory) clog("dirWithVersions", dirWithVersions) val versions = mutableListOf<String>() for (f in dirWithVersions.listFiles()) { Regex("${Drawing.versionPrefix}(.*)").matchEntire(f.name)?.let { versions += it.groupValues[1] } } clog("versions", versions.joinToString(", ")) var maxNumericVersion: Int? = null for (version in versions) { try { val n = version.toInt() if (maxNumericVersion == null || n > maxNumericVersion) maxNumericVersion = n } catch (e: NumberFormatException) {} } val newDrawing = Drawing(path, ((maxNumericVersion ?: 0) + 1).toString()) clog("currentDrawing.dir()", currentDrawing.dir()) clog("newDrawing.dir()", newDrawing.dir()) alraune.operations.copyDirContentToAnotherDir(currentDrawing.dir(), newDrawing.dir()) val crop = p.crop if (crop != null) { // clog("crop", freakingToStringKotlin(crop)) runProcessAndWait(cmdPieces = l( "convert", "drawing.jpg", "-crop", "${crop.width}x${crop.height}+${crop.left}+${crop.top}", "drawing.jpg"), workingDirectory = newDrawing.dir()) .bitchIfBadExit() } newDrawing.writeHTML(p.html) if (p.removeSourceVersion == true) { alraune.operations.rmRf(currentDrawing.dir()) } return Candy(newDrawing.editDrawingHref()) // return Poop("Idi nah") } } class WasingRP_JumpToReference(val ref: Ref): Dancer<Any> { // TODO:vgrechka Investigate ways of efficient search (look how IDEA or Eclipse do this) class Poop(val error: String) class Candy class Ref { var kind by place<Kind>() var projectName by place<String?>() var searchString by place<String>() enum class Kind {IDEAProject} } val noisy = false val searchFileExts = setOf("kt", "java", "txt", "ts") val ignoreDirs = setOf(".git", "node_modules", "build", "out") val visitedDirs = mutableSetOf<File>() override fun dance(): Any { // return Poop("I don't want to work, OK?") if (noisy) clog(freakingToStringKotlin(ref)) return when (ref.kind) { Ref.Kind.IDEAProject -> { val projectName = ref.projectName!! val dirs = when (projectName) { "alraune" -> run { val root = "/home/into/pro/fe/alraune" l("$root/alraune/src/main/java", // Look here first root).map(::File) } else -> wtf("projectName = $projectName") } val r = findInDirs(dirs) ?: return Poop("I can't find your shit") IdeaBackdoorClient().openFile(projectName, path = r.path, line = r.line) Candy() } } } class R1(val path: String, val line: Int) fun findInDirs(dirs: List<File>): R1? { if (noisy) clog("dirs", dirs) for (dir in dirs) { check(dir.isDirectory) if (dir in visitedDirs) continue else visitedDirs += dir val children = dir.listFiles() for (file in children.filter {it.isFile && it.extension in searchFileExts}) { if (noisy) clog("Looking in ${file.path}") InputStreamReader(FileInputStream(file), Charsets.UTF_8).use { it.useLines { it.forEachIndexed {i, s -> if (s.contains(ref.searchString)) return R1(path = file.path, line = i + 1) } } } } findInDirs(children.filter {it.isDirectory && it.name !in ignoreDirs}) ?.let{return it} } return null } }
apache-2.0
a6393ad4a5706ff52d73edd10a4e9903
32.813472
122
0.556543
4.341983
false
false
false
false
GunoH/intellij-community
platform/collaboration-tools/src/com/intellij/collaboration/auth/ui/CompactAccountsPanelFactory.kt
2
3562
// 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.collaboration.auth.ui import com.intellij.collaboration.auth.Account import com.intellij.collaboration.auth.ServerAccount import com.intellij.collaboration.ui.CollaborationToolsUIUtil import com.intellij.collaboration.ui.icon.IconsProvider import com.intellij.collaboration.ui.items import com.intellij.ui.ClickListener import com.intellij.ui.ClientProperty import com.intellij.util.ui.UIUtil import com.intellij.util.ui.cloneDialog.AccountMenuItem import com.intellij.util.ui.cloneDialog.AccountMenuPopupStep import com.intellij.util.ui.cloneDialog.AccountsMenuListPopup import java.awt.Component import java.awt.event.MouseEvent import javax.swing.* class CompactAccountsPanelFactory<A : Account>( private val accountsListModel: ListModel<A> ) { fun create(detailsProvider: LoadingAccountsDetailsProvider<A, *>, listAvatarSize: Int, popupConfig: PopupConfig<A>): JComponent { val iconRenderer = IconCellRenderer(detailsProvider, listAvatarSize) @Suppress("UndesirableClassUsage") val accountsList = JList(accountsListModel).apply { cellRenderer = iconRenderer ClientProperty.put(this, UIUtil.NOT_IN_HIERARCHY_COMPONENTS, listOf(iconRenderer)) selectionMode = ListSelectionModel.SINGLE_SELECTION visibleRowCount = 1 layoutOrientation = JList.HORIZONTAL_WRAP } PopupMenuListener(accountsListModel, detailsProvider, popupConfig).installOn(accountsList) return accountsList } private class IconCellRenderer<A : Account>( private val iconsProvider: IconsProvider<A>, private val avatarSize: Int ) : ListCellRenderer<A>, JLabel() { override fun getListCellRendererComponent(list: JList<out A>?, value: A, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component { icon = iconsProvider.getIcon(value, avatarSize) return this } } interface PopupConfig<A : Account> { val avatarSize: Int fun createActions(): Collection<AccountMenuItem.Action> } private class PopupMenuListener<A : Account>( private val model: ListModel<A>, private val detailsProvider: LoadingAccountsDetailsProvider<A, *>, private val popupConfig: PopupConfig<A> ) : ClickListener() { override fun onClick(event: MouseEvent, clickCount: Int): Boolean { val parentComponent = event.source if (parentComponent !is JComponent) return false showPopupMenu(parentComponent) return true } private fun showPopupMenu(parentComponent: JComponent) { val menuItems = mutableListOf<AccountMenuItem>() for ((index, account) in model.items.withIndex()) { val accountTitle = detailsProvider.getDetails(account)?.name ?: account.name val serverInfo = if (account is ServerAccount) CollaborationToolsUIUtil.cleanupUrl(account.server.toString()) else "" val avatar = detailsProvider.getIcon(account, popupConfig.avatarSize) val showSeparatorAbove = index != 0 menuItems += AccountMenuItem.Account(accountTitle, serverInfo, avatar, emptyList(), showSeparatorAbove) } menuItems += popupConfig.createActions() AccountsMenuListPopup(null, AccountMenuPopupStep(menuItems)).showUnderneathOf(parentComponent) } } }
apache-2.0
6e09b84584da3dc1cbed76d0e0c880c6
37.728261
125
0.715048
4.892857
false
true
false
false
Cognifide/gradle-aem-plugin
src/main/kotlin/com/cognifide/gradle/aem/common/instance/local/BackupManager.kt
1
9898
package com.cognifide.gradle.aem.common.instance.local import com.cognifide.gradle.aem.common.instance.LocalInstance import com.cognifide.gradle.aem.common.instance.LocalInstanceException import com.cognifide.gradle.aem.common.instance.LocalInstanceManager import com.cognifide.gradle.aem.common.instance.names import com.cognifide.gradle.common.file.FileException import com.cognifide.gradle.common.file.transfer.FileEntry import com.cognifide.gradle.common.utils.Formats import com.cognifide.gradle.common.utils.onEachApply import com.cognifide.gradle.common.zip.ZipFile import java.io.File class BackupManager(private val manager: LocalInstanceManager) { private val aem = manager.aem private val common = aem.common private val logger = aem.logger /** * URL to remote directory in which backup files are stored. */ val uploadUrl = aem.obj.string { aem.prop.string("localInstance.backup.uploadUrl")?.let { set(it) } } /** * URL to remote backup file. */ val downloadUrl = aem.obj.string { aem.prop.string("localInstance.backup.downloadUrl")?.let { set(it) } } /** * Backup file from any source (local & remote sources). */ val any: File? get() = resolve(localSources + remoteSources)?.file /** * Backup file specified explicitly. */ val localFile = aem.obj.file { aem.prop.file("localInstance.backup.localFile")?.let { set(it) } } /** * Directory storing locally created backup files. */ val localDir = aem.obj.dir { convention(manager.rootDir.dir("$OUTPUT_DIR/${BackupType.LOCAL.dirName}")) aem.prop.file("localInstance.backup.localDir")?.let { set(it) } } /** * Determines the number of local backup ZIP files stored. * After creating new backups, old ones are auto-removed. */ val localCount = aem.obj.int { convention(3) aem.prop.int("localInstance.backup.localCount")?.let { set(it) } } /** * Backup file from local source. */ val local: File? get() = resolve(localSources)?.file /** * Directory storing downloaded remote backup files. */ val remoteDir = aem.obj.dir { convention(manager.rootDir.dir("$OUTPUT_DIR/${BackupType.REMOTE.dirName}")) aem.prop.file("localInstance.backup.remoteDir")?.let { set(it) } } /** * Backup file from remote source. */ val remote: File? get() = resolve(remoteSources)?.file /** * File suffix indicating instance backup file. */ val suffix = aem.obj.string { convention(SUFFIX_DEFAULT) aem.prop.string("localInstance.backup.suffix")?.let { set(it) } } /** * Defines backup file naming rule. * Must be in sync with selector rule. */ fun namer(provider: () -> String) { this.namer = provider } private var namer: () -> String = { val parts = mutableListOf<String>().apply { add(aem.project.rootProject.name) add(Formats.dateFileName()) val version = aem.project.version.toString() if (version.isNotBlank() && version != "unspecified") { add(version) } } "${parts.joinToString("-")}${suffix.get()}" } /** * Get newly created file basing on namer rule. */ val namedFile: File get() = localDir.get().asFile.resolve(namer()) /** * Defines backup source selection rule. * * By default takes desired backup by name (if provided) or takes most recent backup. * Also by default, file names are sorted lexically / descending. If same name on local & remote source found, local has precedence. * Still, this callback allows to customize order to be used. */ fun selector(selector: Collection<BackupSource>.() -> BackupSource?) { this.selector = selector } private var selector: Collection<BackupSource>.() -> BackupSource? = { val name = aem.prop.string("localInstance.backup.name") ?: "" when { name.isNotBlank() -> firstOrNull { it.fileEntry.name == name } localFileSource != null -> firstOrNull { it == localFileSource } else -> firstOrNull() } } private fun resolve(sources: List<BackupSource>): BackupSource? = sources .filter { it.fileEntry.name.endsWith(suffix.get()) } .sortedWith(compareByDescending<BackupSource> { it.fileEntry.name }.thenBy { it.type.ordinal }) .run { selector(this) } private val localSources: List<BackupSource> get() = listOfNotNull(localFileSource) + localDirSources private val localFileSource: BackupSource? get() = localFile.orNull?.asFile?.let { BackupSource(BackupType.LOCAL, FileEntry.of(it)) { it } } private val localDirSources: List<BackupSource> get() = (localDir.get().asFile.listFiles { _, name -> name.endsWith(suffix.get()) } ?: arrayOf()).map { file -> BackupSource(BackupType.LOCAL, FileEntry.of(file)) { file } } private val remoteSources: List<BackupSource> get() = when { !downloadUrl.orNull.isNullOrBlank() -> listOfNotNull(remoteDownloadSource) !uploadUrl.orNull.isNullOrBlank() -> remoteUploadSources else -> listOf() } private val remoteDownloadSource: BackupSource? get() { val dirUrl = downloadUrl.get().substringBeforeLast("/") val name = downloadUrl.get().substringAfterLast("/") val fileEntry = try { common.fileTransfer.stat(dirUrl, name) // 'stat' may be unsupported } catch (e: FileException) { logger.info("Cannot check instance backup file status at URL '$dirUrl/$name'! Cause: ${e.message}") logger.debug("Actual error", e) FileEntry(name) } return if (fileEntry != null) { BackupSource(BackupType.REMOTE, fileEntry) { remoteDir.get().asFile.resolve(name).apply { common.fileTransfer.downloadFrom(dirUrl, name, this) } } } else { logger.info("Instance backup at URL '$dirUrl/$name' is not available.") null } } private val remoteUploadSources: List<BackupSource> get() { val fileEntries = common.fileTransfer.list(uploadUrl.get()) if (fileEntries.isEmpty()) { logger.info("No instance backups available at URL '${uploadUrl.get()}'.") } return fileEntries.map { file -> BackupSource(BackupType.REMOTE, file) { remoteDir.get().asFile.resolve(file.name).apply { common.fileTransfer.downloadFrom(uploadUrl.get(), name, this) } } } } fun create(instances: Collection<LocalInstance>) = namedFile.apply { create(this, instances) } fun create(file: File, instances: Collection<LocalInstance>) { val uncreated = instances.filter { !it.created } if (uncreated.isNotEmpty()) { throw LocalInstanceException("Cannot create local instance backup, because there are instances not yet created: ${uncreated.names}") } val running = instances.filter { it.status.running } if (running.isNotEmpty()) { throw LocalInstanceException("Cannot create local instance backup, because there are instances still running: ${running.names}") } val zip = ZipFile(file) common.progress(instances.size) { instances.onEachApply { increment("Backing up instance '$name'") { common.progress { updater { update("Adding files to '${file.name}' (${Formats.fileSize(file)})") } zip.addDir(dir) } } } } } fun upload(backupZip: File, verbose: Boolean): Boolean { val dirUrl = uploadUrl.orNull if (dirUrl.isNullOrBlank()) { val message = "Skipped uploading local instance backup as of URL is not defined." if (verbose) { throw LocalInstanceException(message) } else { logger.info(message) return false } } logger.info("Uploading local instance(s) backup file '$backupZip' to URL '$dirUrl'") common.fileTransfer.uploadTo(dirUrl, backupZip) return true } fun restore(backupZip: File, rootDir: File, instances: Collection<LocalInstance>) { logger.info("Restoring instances from backup ZIP '$backupZip' to directory '$rootDir'") rootDir.mkdirs() common.progress(instances.size) { instances.onEachApply { increment("Restoring instance '$name'") { ZipFile(backupZip).unpackDir(id, rootDir) } } } } fun clean() { val preservedMax = localCount.get() if (preservedMax <= 0) { logger.info("Backups cleaning is disabled!") return } val cleanable = localSources.toMutableList() var preserved = 0 while (cleanable.isNotEmpty() && preserved < preservedMax) { val recent = resolve(cleanable) ?: break cleanable.remove(recent) preserved++ } if (cleanable.isEmpty()) { logger.info("No backups to clean!") } else { cleanable.forEach { source -> logger.info("Cleaning backup file ${source.file}") source.file.delete() } } } companion object { const val OUTPUT_DIR = "backup" const val SUFFIX_DEFAULT = ".backup.zip" } }
apache-2.0
02955531d82505a8ff6b81fda724bdb5
33.975265
144
0.597798
4.521699
false
false
false
false
cqjjjzr/LCSELocalizationTools
LCSEPackageUtility/src/main/kotlin/charlie/lcsetools/pkgutil/LCSEPackageMain.kt
1
5645
package charlie.lcsetools.pkgutil import org.apache.commons.cli.* import java.io.File import java.nio.channels.FileChannel import java.nio.file.Paths import kotlin.system.exitProcess val VERSION = "rv4" val opts = Options().apply { addOption("h", "help", false, "显示帮助") addOptionGroup(OptionGroup().apply { addOption(Option("u", "unpack", false, "解包。")) addOption(Option("r", "patch", false, "封包(需与-e配合使用)。")) isRequired = true }) addOption(Option("s", "process-snx", false, "是否处理SNX格式数据")) addOption(Option("p", "process-png", false, "是否处理PNG格式数据")) addOption(Option("b", "process-bmp", false, "是否处理BMP格式数据")) addOption(Option("w", "process-wav", false, "是否处理WAV格式数据")) addOption(Option("o", "process-ogg", false, "是否处理OGG格式数据")) addOption(Option("l", "list", true, "指定.lst清单文件").apply { isRequired = true; argName = "lst-file" }) addOption(Option("a", "package", true, "指定lcsebody数据包文件").apply { isRequired = true; argName = "package-file" }) addOption(Option("d", "out-dir", true, "指定输出目录").apply { argName = "out-dir" }) addOption(Option("e", "patch-dir", true, "指定用以替换数据包中文件的文件所在目录") .apply { argName = "patch-dir" }) addOption(Option("k", "key", true, "指定.lst清单文件的的加密key,格式为16进制两位数字")) addOption(Option("K", "key-snx", true, "指定SNX文件的的加密key,格式为16进制两位数字")) } fun main(vararg args: String) { println("LC-ScriptEngine资源包封包处理实用工具 $VERSION\n\tBy Charlie Jiang\n\n") try { DefaultParser().parse(opts, args).apply { if (options.isEmpty() || hasOption('h') || (hasOption('r') && !hasOption('e')) || (hasOption('u') && hasOption('e'))) { printUsageAndBoom() } if (hasOption('k')) keyIndex = getOptionValue('k').toInt(16).expandByteToInt() if (hasOption('K')) keySNX = getOptionValue('K').toInt(16).expandByteToInt() FileChannel.open(Paths.get(getOptionValue('l').removeSurrounding("\""))).use { it.map(FileChannel.MapMode.READ_ONLY, 0, it.size()).let { listBuffer -> FileChannel.open(Paths.get(getOptionValue('a').removeSurrounding("\""))).use { packageChannel -> val outDirectory = if (hasOption('d')) Paths.get(getOptionValue('d').removeSurrounding("\"").removeSuffix("\"")) else if (hasOption('u')) Paths.get(".", "extracted") else Paths.get(".", "patched") if (hasOption('u')) { LCSEIndexList.readFromBuffer(listBuffer) .entries .filter { it.type != LCSEResourceType.SCRIPT || hasOption('s') } .filter { it.type != LCSEResourceType.PNG_PICTURE || hasOption('p') } .filter { it.type != LCSEResourceType.BMP_PICTURE || hasOption('b') } .filter { it.type != LCSEResourceType.WAVE_AUDIO || hasOption('w') } .filter { it.type != LCSEResourceType.OGG_AUDIO || hasOption('o') } .forEach { it.extractFromChannelToFile(packageChannel, outDirectory) print("提取:${it.fullFilename} \r") } } else if (hasOption('r')) { val patches = File(getOptionValue('e').removeSurrounding("\"")).walkTopDown() .filter { it.isFile } .map { try { LCSEPatch(it.toPath()) } catch(e: Exception) { null } } .filterNotNull() .filter { it.type != LCSEResourceType.SCRIPT || hasOption('s') } .filter { it.type != LCSEResourceType.PNG_PICTURE || hasOption('p') } .filter { it.type != LCSEResourceType.BMP_PICTURE || hasOption('b') } .filter { it.type != LCSEResourceType.WAVE_AUDIO || hasOption('w') } .filter { it.type != LCSEResourceType.OGG_AUDIO || hasOption('o') } .asIterable() LCSEIndexList .readFromBuffer(listBuffer) .writePatchedPackage( patches, packageChannel, outDirectory.resolve(Paths.get(getOptionValue('l').removeSurrounding("\"")).fileName), outDirectory.resolve(Paths.get(getOptionValue('a').removeSurrounding("\"")).fileName)) } } } } } } catch(e: ParseException) { e.printStackTrace() printUsageAndBoom() } println("\n完成。") } fun printUsageAndBoom(): Nothing { HelpFormatter().printHelp("java -jar LCSEPackage.jar <-u/r/h> <-l xxx> <-a xxx> [其他开关/参数]", opts) exitProcess(0) }
apache-2.0
15fe6f49d371fd2fa570a77d932de397
52.32
130
0.495779
4.366093
false
false
false
false
pajato/Argus
app/src/main/java/com/pajato/argus/RecyclerViewHolderManager.kt
1
7259
package com.pajato.argus import android.annotation.SuppressLint import android.content.ContentValues import android.graphics.Color import android.support.v4.content.ContextCompat import android.support.v7.app.AlertDialog import android.support.v7.widget.AppCompatImageView import android.view.View import android.widget.TextView import com.pajato.argus.event.* import io.reactivex.disposables.Disposable import kotlinx.android.synthetic.main.dialog_content.view.* import kotlinx.android.synthetic.main.non_empty_list_content_main.* import kotlinx.android.synthetic.main.tv_layout.view.* import kotlinx.android.synthetic.main.video_content.view.* import kotlinx.android.synthetic.main.video_layout.view.* import java.lang.Integer.parseInt object RecyclerViewHolderManager : Event.EventListener { private lateinit var activity: MainActivity private var subs: List<Disposable> = emptyList() /** Subscribe to events and obtain the instance of the MainActivity. */ fun init(activity: MainActivity) { this.activity = activity subs = listOf(RxBus.subscribeToEventType(DeleteEvent::class.java, this), RxBus.subscribeToEventType(LocationEvent::class.java, this), RxBus.subscribeToEventType(WatchedEvent::class.java, this), RxBus.subscribeToEventType(SeasonEvent::class.java, this), RxBus.subscribeToEventType(EpisodeEvent::class.java, this)) } /** Handle events differently depending on their class. */ override fun accept(event: Event) { when (event) { is DeleteEvent -> handleDeleteEvent(event) is LocationEvent -> handleLocationEvent(event) is WatchedEvent -> handleWatchedEvent(event) is SeasonEvent -> handleSeasonEvent(event) is EpisodeEvent -> handleEpisodeEvent(event) } } /** Delete events remove the video from the layout and remove it from the database. */ private fun handleDeleteEvent(event: DeleteEvent) { val position = event.getData() val v = (activity.listItems.adapter as ListAdapter).removeItem(position) deleteVideo(v, activity) } /** Season events update a particular episodic video's current season. */ private fun handleSeasonEvent(event: SeasonEvent) { val position = event.getData() val layout = activity.listItems.findViewHolderForAdapterPosition(position).itemView val title = layout.titleText.text.toString() val textView = layout.seasonText val field = "season" if (event.increment) { incrementSeasonOrEpisode(textView, title) } else { updateSeasonOrEpisode(layout, textView, field, field) } } /** Episode events update a particular episodic video's current episode. */ private fun handleEpisodeEvent(event: EpisodeEvent) { val position = event.getData() val layout = activity.listItems.findViewHolderForAdapterPosition(position).itemView val title = layout.titleText.text.toString() val textView = layout.episodeText val field = "episode" val message = "$field of season " + layout.seasonText.text.toString() if (event.increment) { incrementSeasonOrEpisode(textView, title) } else { updateSeasonOrEpisode(layout, textView, field, message) } } /** Location Events update the layout according to the new location, and update the database. */ private fun handleLocationEvent(event: LocationEvent) { val position = event.getData() val layout = activity.listItems.findViewHolderForAdapterPosition(position).itemView val locationWatched: String = event.getLocation() layout.locationText?.text = locationWatched // Get the video's full information from the layout and update its entry in the database. val contentValues = ContentValues() contentValues.put(DatabaseEntry.COLUMN_NAME_LOCATION_WATCHED, locationWatched) updateVideoValues(layout.titleText.text.toString(), contentValues, activity) } /** Watched Events should update the database. and then update the layout. */ private fun handleWatchedEvent(event: WatchedEvent) { val position = event.getData() val layout = activity.listItems.findViewHolderForLayoutPosition(position).itemView val contentValues = ContentValues() contentValues.put(DatabaseEntry.COLUMN_NAME_DATE_WATCHED, event.getDateWatched()) updateVideoValues(layout.titleText.text.toString(), contentValues, activity) layout.dateText?.text = event.getDateWatched() layout.findViewById<AppCompatImageView>(R.id.viewedEye)?.visibility = View.VISIBLE layout.findViewById<AppCompatImageView>(R.id.viewedEye)?.setColorFilter(Color.GRAY) layout.findViewById<AppCompatImageView>(R.id.dateButton) .setColorFilter(ContextCompat.getColor(layout.context, R.color.colorAccent)) } /** Increment the season or episode value by one, then update the database. */ private fun incrementSeasonOrEpisode(textView: TextView, title: String) { var number = parseInt(textView.text.toString()) number += 1 textView.text = number.toString() val contentValues = ContentValues() val c = if (textView.id == R.id.seasonText) DatabaseEntry.COLUMN_NAME_SEASON else DatabaseEntry.COLUMN_NAME_EPISODE contentValues.put(c, number) updateVideoValues(title, contentValues, activity) } /** Set the season or episode value to a value as entered in an alert by the user.*/ @SuppressLint("InflateParams") private fun updateSeasonOrEpisode(layout: View, textView: TextView, field: String, message: String) { // Construct an alert and prepare relevant information for our custom layout. val builder = AlertDialog.Builder(layout.context) val title = layout.titleText.text.toString() val alertTitle = title.capitalize() + " " + field.capitalize() val alertMessage = "Set the $message of $title that you have most recently watched." // In spite of the lint warning, this is the recommended way to add a custom view to an alert builder. val content = activity.layoutInflater.inflate(R.layout.dialog_content, null) content.alertTitle.text = alertTitle content.alertMessage.text = alertMessage builder.setView(content) .setNegativeButton("Cancel") { dialog, _ -> dialog.cancel() } .setPositiveButton("OK") { _, _ -> val value = content.alertInput.text.toString() textView.text = value val contentValues = ContentValues() val c = if (textView.id == R.id.seasonText) DatabaseEntry.COLUMN_NAME_SEASON else DatabaseEntry.COLUMN_NAME_EPISODE contentValues.put(c, parseInt(value)) updateVideoValues(title, contentValues, activity) } builder.show() } /** Unsubscribe from events. */ fun destroy() { subs.forEachIndexed { _, disposable -> disposable.dispose() } subs = emptyList() } }
gpl-3.0
eae3c256d6b60aadffe21587d1add2bf
44.943038
135
0.688525
4.766251
false
false
false
false
nicolas-raoul/apps-android-commons
app/src/main/java/fr/free/nrw/commons/upload/categories/CategoriesPresenter.kt
3
3659
package fr.free.nrw.commons.upload.categories import android.text.TextUtils import fr.free.nrw.commons.R import fr.free.nrw.commons.category.CategoryItem import fr.free.nrw.commons.di.CommonsApplicationModule import fr.free.nrw.commons.repository.UploadRepository import fr.free.nrw.commons.upload.depicts.proxy import io.reactivex.Scheduler import io.reactivex.disposables.CompositeDisposable import io.reactivex.subjects.PublishSubject import timber.log.Timber import javax.inject.Inject import javax.inject.Named import javax.inject.Singleton /** * The presenter class for UploadCategoriesFragment */ @Singleton class CategoriesPresenter @Inject constructor( private val repository: UploadRepository, @param:Named(CommonsApplicationModule.IO_THREAD) private val ioScheduler: Scheduler, @param:Named(CommonsApplicationModule.MAIN_THREAD) private val mainThreadScheduler: Scheduler ) : CategoriesContract.UserActionListener { companion object { private val DUMMY: CategoriesContract.View = proxy() } var view = DUMMY private val compositeDisposable = CompositeDisposable() private val searchTerms = PublishSubject.create<String>() override fun onAttachView(view: CategoriesContract.View) { this.view = view compositeDisposable.add( searchTerms .observeOn(mainThreadScheduler) .doOnNext { view.showProgress(true) view.showError(null) view.setCategories(null) } .switchMap(::searchResults) .map { repository.selectedCategories + it } .map { it.distinctBy { categoryItem -> categoryItem.name } } .observeOn(mainThreadScheduler) .subscribe( { view.setCategories(it) view.showProgress(false) if (it.isEmpty()) { view.showError(R.string.no_categories_found) } }, Timber::e ) ) } private fun searchResults(term: String) = repository.searchAll(term, getImageTitleList(), repository.selectedDepictions) .subscribeOn(ioScheduler) .map { it.filterNot { categoryItem -> repository.containsYear(categoryItem.name) } } override fun onDetachView() { view = DUMMY compositeDisposable.clear() } /** * asks the repository to fetch categories for the query * @param query */ override fun searchForCategories(query: String) { searchTerms.onNext(query) } /** * Returns image title list from UploadItem * @return */ private fun getImageTitleList(): List<String> { return repository.uploads .map { it.uploadMediaDetails[0].captionText } .filterNot { TextUtils.isEmpty(it) } } /** * Verifies the number of categories selected, prompts the user if none selected */ override fun verifyCategories() { val selectedCategories = repository.selectedCategories if (selectedCategories.isNotEmpty()) { repository.setSelectedCategories(selectedCategories.map { it.name }) view.goToNextScreen() } else { view.showNoCategorySelected() } } /** * ask repository to handle category clicked * * @param categoryItem */ override fun onCategoryItemClicked(categoryItem: CategoryItem) { repository.onCategoryClicked(categoryItem) } }
apache-2.0
1a0cd9cd331a03ca4cd9e6eee62691f2
31.963964
97
0.634326
5.067867
false
false
false
false
TachiWeb/TachiWeb-Server
TachiServer/src/main/java/xyz/nulldev/ts/cache/AsyncDiskLFUCache.kt
1
7921
package xyz.nulldev.ts.cache import com.github.benmanes.caffeine.cache.Caffeine import com.google.common.base.Throwables import de.huxhorn.sulky.ulid.ULID import kotlinx.coroutines.* import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.consumeEach import kotlinx.coroutines.channels.sendBlocking import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import mu.KotlinLogging import org.apache.commons.codec.digest.DigestUtils import java.io.File import java.nio.file.Files import java.nio.file.StandardCopyOption private const val TMP_FILE_EXT = "tmp" /** * Fast, completely asynchronous disk LFU cache implementation * * TODO VertX integration * * @author nulldev */ class AsyncDiskLFUCache(val folder: File, val sizeLimit: Long, ioScope: CoroutineScope = GlobalScope + Dispatchers.IO) : AutoCloseable { private val channel = Channel<CacheEvent>(1000) private val internalCache = Caffeine.newBuilder() .maximumWeight(sizeLimit) .removalListener { _: String?, value: CacheEntry?, _ -> // Queue cache entry for background eviction if (value != null) channel.sendBlocking(CacheEvent.Evict(value)) } .weigher { _: String, value: CacheEntry -> value.size.toInt() } .build<String, CacheEntry>() private val inProgressWrites = HashMap<String, ULID.Value>() private val inProgressWritesMutex = Mutex(false) private val thisThreadULIDGenerator = ThreadLocal.withInitial { ULID() } private sealed class CacheEvent { data class Commit(val oldFile: File, val hashedKey: String, val ourId: ULID.Value) : CacheEvent() data class Evict(val cacheEntry: CacheEntry) : CacheEvent() data class Cancel(val oldFile: File) : CacheEvent() data class Init(val folderSnapshot: List<File>) : CacheEvent() } init { // Launch background manager ioScope.launch { channel.consumeEach { entry -> when (entry) { is CacheEvent.Commit -> { val newEntryFile = File(folder, "${entry.hashedKey}.${entry.ourId}") Files.move(entry.oldFile.toPath(), newEntryFile.toPath(), StandardCopyOption.REPLACE_EXISTING) internalCache.put(entry.hashedKey, CacheEntry(newEntryFile)) } is CacheEvent.Evict -> { entry.cacheEntry.deleting = true entry.cacheEntry.notifyMutex.lock() // Wait for all readers to die entry.cacheEntry.file.delete() } is CacheEvent.Cancel -> { entry.oldFile.delete() } is CacheEvent.Init -> { // Load last state folder.listFiles()?.forEach { // Delete half-written files if (it.name.endsWith(".$TMP_FILE_EXT")) { it.delete() } else { // Load valid entries into cache val (hashedKey, _) = it.name.split(".") internalCache.put(hashedKey, CacheEntry(it)) } } } } } } // Background init cache folder.listFiles()?.let { channel.sendBlocking(CacheEvent.Init(it.toList())) } // Ensure folder exists folder.mkdirs() } private class CacheEntry(val file: File) { val size = file.length() @Volatile var readers = 0 @Volatile var deleting = false val notifyMutex = Mutex(false) } suspend fun get(key: String): Handle? { val hashedKey = hashKey(key) val entry = internalCache.getIfPresent(hashedKey) ?: return null entry.notifyMutex.tryLock() entry.readers++ if (entry.deleting) { if (--entry.readers == 0) entry.notifyMutex.unlock() return get(hashedKey) // Entry is being deleted, try again for another entry } return Handle(entry.file) { if (--entry.readers == 0) entry.notifyMutex.unlock() } } suspend fun put(key: String): EditHandle { val hashedKey = hashKey(key) val ourId = thisThreadULIDGenerator.get().nextValue() inProgressWritesMutex.withLock { inProgressWrites[hashedKey] = ourId } val tmpFile = File(folder, "$ourId.$TMP_FILE_EXT") return EditHandle(tmpFile, onCommit = { inProgressWritesMutex.lock() if (inProgressWrites[hashedKey] != ourId) { inProgressWritesMutex.unlock() // Background cancel channel.send(CacheEvent.Cancel(tmpFile)) } else { // Commit inProgressWrites.remove(hashedKey) inProgressWritesMutex.unlock() // Background commit channel.send(CacheEvent.Commit(tmpFile, hashedKey, ourId)) } }, onCancel = { inProgressWritesMutex.lock() if (inProgressWrites[hashedKey] == ourId) { inProgressWrites.remove(hashedKey) inProgressWritesMutex.unlock() } // Background cancel channel.send(CacheEvent.Cancel(tmpFile)) }) } suspend fun remove(key: String) { internalCache.invalidate(hashKey(key)) } private fun hashKey(key: String) = DigestUtils.sha256Hex(key) override fun close() { channel.close() } class EditHandle internal constructor(val file: File, private val onCommit: suspend () -> Unit, private val onCancel: suspend () -> Unit) { private val creationStackTrace = Exception() var closed = false suspend fun commit() { require(!closed) closed = true onCommit() } suspend fun cancel() { require(!closed) closed = true onCancel() } protected fun finalize() { if (!closed) { KotlinLogging.logger { }.warn { "==> LEAKED ${this::class.qualifiedName}, printing creation stacktrace:\n${Throwables.getStackTraceAsString(creationStackTrace)}" } runBlocking { onCancel() } } } } class Handle internal constructor(val file: File, val onClose: suspend () -> Unit) { private val creationStackTrace = Exception() var closed = false suspend fun close() { require(!closed) closed = true onClose() } suspend fun <T> use(block: suspend (File) -> T): T { try { return block(file) } finally { if (!closed) close() } } suspend fun <T> useBlocking(block: (File) -> T): T { try { return block(file) } finally { if (!closed) close() } } protected fun finalize() { if (!closed) { KotlinLogging.logger { }.warn { "==> LEAKED ${this::class.qualifiedName}, printing creation stacktrace:\n${Throwables.getStackTraceAsString(creationStackTrace)}" } runBlocking { onClose() } } } } }
apache-2.0
88e4c87b2680633af45866cbf73e2443
32.281513
149
0.532509
5.120233
false
false
false
false
excref/kotblog
blog/service/core/src/main/kotlin/com/excref/kotblog/blog/service/blog/domain/Blog.kt
1
549
package com.excref.kotblog.blog.service.blog.domain import com.excref.kotblog.blog.service.common.UuidAwareDomain import com.excref.kotblog.blog.service.user.domain.User import javax.persistence.* /** * @author Arthur Asatryan * @since 6/10/17 7:17 PM */ @Entity data class Blog constructor( @Column(name = "name", nullable = false, unique = true) val name: String, @ManyToOne(optional = false, fetch = FetchType.LAZY) @JoinColumn(name = "user_id", nullable = false) val user: User ) : UuidAwareDomain()
apache-2.0
59b4949f0d1dd72367842eb667fe47d3
27.947368
63
0.693989
3.611842
false
false
false
false
glorantq/KalanyosiRamszesz
src/glorantq/ramszesz/commands/BanCommand.kt
1
2711
package glorantq.ramszesz.commands import glorantq.ramszesz.utils.BotUtils import glorantq.ramszesz.config.ConfigFile import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent import sx.blah.discord.handle.obj.IUser import sx.blah.discord.util.EmbedBuilder /** * Created by glora on 2017. 07. 23.. */ class BanCommand : ICommand { override val commandName: String get() = "ban" override val description: String get() = "Ban a user from the server" override val permission: Permission get() = Permission.ADMIN override val extendedHelp: String get() = "Ban a user from the server. Mention a user and optionally specify a reason" override val usage: String get() = "@Mention [Reason]" override val botPermissions: Int get() = 0x4 override fun execute(event: MessageReceivedEvent, args: List<String>) { val embed: EmbedBuilder = BotUtils.embed("Ban", event.author) if(!BotUtils.hasPermissions(4, event.author, event.guild)) { embed.withDescription("You don't have permissions to ban users!") BotUtils.sendMessage(embed.build(), event.channel) return } val mentions: List<IUser> = event.message.mentions if (mentions.isEmpty()) { BotUtils.sendUsageEmbed("You need to mention a user!", "Ban", event.author, event, this) return } val nameLength: Int = mentions[0].name.split(" ").size val reason: StringBuilder = StringBuilder() if (args.size > nameLength) { for(part: String in args.subList(nameLength, args.size)) { reason.append(part) reason.append(" ") } } val reasonString: String = reason.toString().trim() try { event.guild.banUser(mentions[0], reasonString) if(reasonString.isEmpty()) { embed.withDescription("The user `@${mentions[0].name}` has been banned from the server by ${event.author.mention()}") } else { embed.withDescription("The user `@${mentions[0].name}` has been banned from the server by ${event.author.mention()} for: `$reasonString`") } val config: ConfigFile = BotUtils.getGuildConfig(event) if(config.logModerations) { event.guild.getChannelByID(config.modLogChannel).sendMessage(embed.build()) } } catch (e: Exception) { embed.withDescription("Failed to ban user!") embed.appendField(e::class.simpleName, e.message, false) } BotUtils.sendMessage(embed.build(), event.channel) } }
gpl-3.0
3cc09aba7e5a079fc0669b4dfcf3b2a7
38.304348
154
0.625231
4.473597
false
true
false
false