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
dnkolegov/klox
src/main/kotlin/com/craftinginterpreters/klox/Parser.kt
1
3388
package com.craftinginterpreters.klox import com.craftinginterpreters.klox.TokenType.* class Parser(private val tokens: List<Token>) { inner class ParseError : RuntimeException() private var current = 0 private fun peek(): Token = tokens[current] private fun isAtEnd(): Boolean = peek().type == EOF private fun previous(): Token = tokens[current - 1] private fun advance(): Token { if (!isAtEnd()) current++ return previous() } private fun check(type: TokenType): Boolean = !isAtEnd() && peek().type == type private fun match(vararg types: TokenType): Boolean { for (type in types) { if (check(type)) { advance() return true } } return false } private fun expression(): Expr = equality() private fun equality(): Expr { var expr = comparison() while(match(BANG_EQUAL, EQUAL_EQUAL)) { val operator = previous() val right = comparison() expr = Expr.Binary(expr, operator, right) } return expr } private fun comparison(): Expr { var expr = addition() while(match(GREATER_EQUAL, GREATER, LESS, LESS_EQUAL)) { val operator = previous() val right = addition() expr = Expr.Binary(expr, operator, right) } return expr } private fun addition(): Expr { var expr = multiplication() while(match(MINUS, PLUS)) { val operator = previous() val right = multiplication() expr = Expr.Binary(expr, operator, right) } return expr } private fun multiplication(): Expr { var expr = unary() while(match(STAR, SLASH)) { val operator = previous() val right = unary() expr = Expr.Binary(expr, operator, right) } return expr } private fun unary(): Expr { if (match(BANG, MINUS)) { return Expr.Unary(previous(), unary()) } return primary() } private fun primary(): Expr { return when { match(FALSE) -> Expr.Literal(false) match(TRUE) -> Expr.Literal(true) match(NIL) -> Expr.Literal(null) match(NUMBER, STRING) -> Expr.Literal(previous().literal) match(LEFT_PAREN) -> { consume(RIGHT_PAREN, "Expect ')' after expression") Expr.Grouping(expression()) } else -> throw error(peek(), "Expect expression."); } } private fun consume(type: TokenType, message: String):Token { if (check(type)) { return advance() } throw error(peek(), message) } private fun error(token: Token, message: String): ParseError { Lox.error(token, message) return ParseError() } private fun synchronize() { advance() while (!isAtEnd()) { if (previous().type === SEMICOLON) return when (peek().type) { CLASS, FUN, VAR, FOR, IF, WHILE, PRINT, RETURN -> return } advance() } } fun parse(): Expr? { return try { expression() } catch (e: ParseError){ null } } }
mit
c114c6cb5ade88a717a43577d4a59c94
22.866197
83
0.521547
4.68603
false
false
false
false
proxer/ProxerAndroid
src/main/kotlin/me/proxer/app/forum/TopicFragment.kt
1
3919
package me.proxer.app.forum import android.os.Bundle import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import androidx.core.os.bundleOf import androidx.lifecycle.Observer import androidx.recyclerview.widget.LinearLayoutManager import com.mikepenz.iconics.utils.IconicsMenuInflaterUtil import com.uber.autodispose.android.lifecycle.scope import com.uber.autodispose.autoDisposable import me.proxer.app.GlideApp import me.proxer.app.R import me.proxer.app.base.PagedContentFragment import me.proxer.app.profile.ProfileActivity import me.proxer.app.util.extension.toPrefixedUrlOrNull import me.proxer.app.util.extension.unsafeLazy import me.proxer.library.enums.Device import me.proxer.library.util.ProxerUrls import me.proxer.library.util.ProxerUtils import org.koin.androidx.viewmodel.ext.android.viewModel import org.koin.core.parameter.parametersOf import kotlin.properties.Delegates /** * @author Ruben Gees */ class TopicFragment : PagedContentFragment<ParsedPost>() { companion object { fun newInstance() = TopicFragment().apply { arguments = bundleOf() } } override val isSwipeToRefreshEnabled = false override val hostingActivity: TopicActivity get() = activity as TopicActivity override val viewModel by viewModel<TopicViewModel> { parametersOf(id, resources) } override val layoutManager by unsafeLazy { LinearLayoutManager(context) } override var innerAdapter by Delegates.notNull<PostAdapter>() private val id: String get() = hostingActivity.id private var topic: String? get() = hostingActivity.topic set(value) { hostingActivity.topic = value } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) innerAdapter = PostAdapter() innerAdapter.profileClickSubject .autoDisposable(this.scope()) .subscribe { (view, post) -> ProfileActivity.navigateTo( requireActivity(), post.userId, post.username, post.image, if (view.drawable != null && post.image.isNotBlank()) view else null ) } setHasOptionsMenu(true) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) innerAdapter.glide = GlideApp.with(this) viewModel.metaData.observe( viewLifecycleOwner, Observer { it?.let { topic = it.subject } } ) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { IconicsMenuInflaterUtil.inflate(inflater, requireContext(), R.menu.fragment_topic, menu, true) super.onCreateOptionsMenu(menu, inflater) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.show_in_browser -> { val url = (activity?.intent?.dataString ?: "").toPrefixedUrlOrNull() if (url != null) { val mobileUrl = url.newBuilder() .setQueryParameter("device", ProxerUtils.getSafeApiEnumName(Device.MOBILE)) .build() showPage(mobileUrl, forceBrowser = true, skipCheck = true) } else { viewModel.metaData.value?.categoryId?.also { categoryId -> showPage( ProxerUrls.forumWeb(categoryId, id, Device.MOBILE), forceBrowser = true, skipCheck = true ) } } } } return super.onOptionsItemSelected(item) } }
gpl-3.0
e85118412390651471130dcee3f872c2
31.122951
102
0.630008
5.102865
false
false
false
false
shyiko/ktlint
ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/SpacingBetweenDeclarationsWithAnnotationsRule.kt
1
1981
package com.pinterest.ktlint.ruleset.experimental import com.pinterest.ktlint.core.Rule import com.pinterest.ktlint.core.ast.ElementType.MODIFIER_LIST import com.pinterest.ktlint.core.ast.children import org.jetbrains.kotlin.com.intellij.lang.ASTNode import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement import org.jetbrains.kotlin.psi.KtAnnotationEntry import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments /** * @see https://youtrack.jetbrains.com/issue/KT-35106 */ class SpacingBetweenDeclarationsWithAnnotationsRule : Rule("spacing-between-declarations-with-annotations") { override fun visit( node: ASTNode, autoCorrect: Boolean, emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit ) { if (node.elementType == MODIFIER_LIST && node.hasAnnotationsAsChildren()) { val declaration = node.psi.parent as? KtDeclaration val prevDeclaration = declaration?.getPrevSiblingIgnoringWhitespaceAndComments(withItself = false) as? KtDeclaration val prevWhiteSpace = declaration?.prevSibling as? PsiWhiteSpace if (declaration != null && prevDeclaration != null && prevWhiteSpace?.text?.count { it == '\n' } == 1) { emit( node.startOffset, "Declarations and declarations with annotations should have an empty space between.", true ) if (autoCorrect) { val indent = prevWhiteSpace.text.substringAfter('\n') (prevWhiteSpace.node as LeafPsiElement).rawReplaceWithText("\n\n$indent") } } } } private fun ASTNode.hasAnnotationsAsChildren(): Boolean = children().find { it.psi is KtAnnotationEntry } != null }
mit
76788b207f3c4fe87862a1ea36214cfb
45.069767
117
0.680464
4.867322
false
false
false
false
nguyenhoanglam/ImagePicker
imagepicker/src/main/java/com/nguyenhoanglam/imagepicker/helper/ToastHelper.kt
1
704
/* * Copyright (C) 2021 Image Picker * Author: Nguyen Hoang Lam <[email protected]> */ package com.nguyenhoanglam.imagepicker.helper import android.annotation.SuppressLint import android.content.Context import android.widget.Toast class ToastHelper { companion object { var toast: Toast? = null @SuppressLint("ShowToast") fun show(context: Context, text: String, duration: Int = Toast.LENGTH_SHORT) { if (toast == null) { toast = Toast.makeText(context.applicationContext, text, duration) } else { toast?.cancel() toast?.setText(text) } toast?.show() } } }
apache-2.0
fd54eafc434b21961fc939d9bb365d6c
25.111111
86
0.603693
4.141176
false
false
false
false
Tomlezen/RxCommons
lib/src/main/java/com/tlz/rxcommons/RxPreferences.kt
1
3211
package com.tlz.rxcommons import android.annotation.SuppressLint import android.content.SharedPreferences import io.reactivex.BackpressureStrategy import io.reactivex.Flowable import io.reactivex.FlowableOnSubscribe import io.reactivex.android.MainThreadDisposable /** * Created by LeiShao. * Data 2017/5/24. * Time 15:14. * Email [email protected]. */ class RxPreferences(val sharedPreferences: SharedPreferences) { private val preferenceFlowable: Flowable<String> init { preferenceFlowable = Flowable.create(FlowableOnSubscribe<String> { e -> val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, key -> e.onNext(key) } sharedPreferences.registerOnSharedPreferenceChangeListener(listener) e.setDisposable(object : MainThreadDisposable() { override fun onDispose() { sharedPreferences.unregisterOnSharedPreferenceChangeListener(listener) } }) }, BackpressureStrategy.LATEST).share() } fun <T> get(key: String, defValue: T): T = with(sharedPreferences) { val res: Any = when (defValue) { is Int -> getInt(key, defValue) is Float -> getFloat(key, defValue) is Long -> getLong(key, defValue) is String -> getString(key, defValue) is Boolean -> getBoolean(key, defValue) else -> throw IllegalArgumentException("This type cant be saved") } res as T } @SuppressLint("CommitPrefEdits") fun <T> put(key: String, value: T) = with(sharedPreferences.edit()) { when (value) { is Int -> putInt(key, value) is Float -> putFloat(key, value) is Long -> putLong(key, value) is String -> putString(key, value) is Boolean -> putBoolean(key, value) else -> throw IllegalArgumentException("This type can be saved") }.apply() } private fun observe(key: String, emitOnStart: Boolean): Flowable<String> { return preferenceFlowable .startWith(Flowable.just(key, key) .filter { emitOnStart }) .filter { s -> key == s } } fun observeBoolean(key: String, defValue: Boolean, emitOnStart: Boolean): Flowable<Boolean> { return observe(key, emitOnStart) .map { sharedPreferences.getBoolean(key, defValue) } } fun observeString(key: String, defValue: String, emitOnStart: Boolean): Flowable<String> { return observe(key, emitOnStart) .map { sharedPreferences.getString(key, defValue) } } fun observeInt(key: String, defValue: Int, emitOnStart: Boolean): Flowable<Int> { return observe(key, emitOnStart) .map { sharedPreferences.getInt(key, defValue) } } fun observeLong(key: String, defValue: Long, emitOnStart: Boolean): Flowable<Long> { return observe(key, emitOnStart) .map { sharedPreferences.getLong(key, defValue) } } fun observeFloat(key: String, defValue: Float, emitOnStart: Boolean): Flowable<Float> { return observe(key, emitOnStart) .map { sharedPreferences.getFloat(key, defValue) } } fun observeStringSet(key: String, defValue: Set<String>, emitOnStart: Boolean): Flowable<Set<String>> { return observe(key, emitOnStart) .map { sharedPreferences.getStringSet(key, defValue) } } }
apache-2.0
9f5ad88f1128c55883b727706302fb4e
32.458333
99
0.690751
4.264276
false
false
false
false
VladRassokhin/intellij-hcl
src/kotlin/org/intellij/plugins/hcl/psi/HCLHeredocContentManipulator.kt
1
7768
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.intellij.plugins.hcl.psi import com.intellij.lang.ASTNode import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.AbstractElementManipulator import com.intellij.psi.impl.source.tree.LeafElement import com.intellij.psi.impl.source.tree.TreeElement import com.intellij.psi.tree.TokenSet import com.intellij.util.IncorrectOperationException import org.intellij.plugins.hcl.HCLElementTypes import org.intellij.plugins.hcl.psi.impl.HCLHeredocContentMixin import org.intellij.plugins.hcl.psi.impl.HCLPsiImplUtils class HCLHeredocContentManipulator : AbstractElementManipulator<HCLHeredocContent>() { // There two major cases: // 1. all content replaced with actual diff very small (full heredoc injection): // 1.1 One line modified // 1.2 One line added // 1.3 One line removed // 2. one line content (probably not all) replaced with any diff (HIL injection) // This cases should work quite fast @Throws(IncorrectOperationException::class) override fun handleContentChange(element: HCLHeredocContent, range: TextRange, newContent: String): HCLHeredocContent { if (range.length == 0 && element.linesCount == 0) { // Replace empty with something return replaceStupidly(element, newContent) } ////////// // Calculate affected elements (strings) (based on offsets) var offset = 0 val lines = HCLPsiImplUtils.getLinesWithEOL(element) val ranges = lines.map { val r: TextRange = TextRange.from(offset, it.length) offset += it.length r } val startString: Int val endString: Int val linesToChange = ranges.indices.filter { ranges[it].intersects(range) } assert(linesToChange.isNotEmpty()) startString = linesToChange.first() endString = linesToChange.last() val node = element.node as TreeElement val prefixStartString = lines[startString].substring(0, range.startOffset - ranges[startString].startOffset) val suffixEndString = lines[endString].substring(range.endOffset - ranges[endString].startOffset) ////////// // Prepare new lines content val newText = prefixStartString + newContent + suffixEndString val newLines: List<Pair<String, Boolean>> = getReplacementLines(newText) ////////// // Replace nodes if (newLines.isNotEmpty() && !newLines.last().second && !(element.textLength == range.endOffset && !newText.endsWith("\n"))) { throw IllegalStateException("Last line should have line separator. New text: '$newText'\nNew lines:$newLines") } val stopNode: ASTNode? = lookupLine(node, endString)?.let { nextLine(it) } var iter: ASTNode? = lookupLine(node, startString) for ((line, _) in newLines) { if (iter != null && iter != stopNode) { // Replace existing lines val next = nextLine(iter) if (iter.isHD_EOL) { // Line was empty. if (line.isEmpty()) { // Left intact } else { // Add HD_LINE before 'iter' (HD_EOL) node.addLeaf(HCLElementTypes.HD_LINE, line, iter) } } else { assert(iter.elementType == HCLElementTypes.HD_LINE) if (line.isEmpty()) { // Remove HD_LINE; HD_EOL would be preserved node.removeChild(iter) } else { if (iter.text != line) { // Replace node text (iter as LeafElement).replaceWithText(line) } } } iter = next } else { // Add new lines to end if (iter == null) { val lcn = element.node.lastChildNode if (lcn != null) { if (lcn.isHD_EOL) { node.addLeaf(HCLElementTypes.HD_EOL, "\n", lcn) node.addLeaf(HCLElementTypes.HD_LINE, line, lcn) } else assert(false) } else { node.addLeaf(HCLElementTypes.HD_LINE, line, lcn) node.addLeaf(HCLElementTypes.HD_EOL, "\n", lcn) } } else if (stopNode != null) { val sNP = stopNode.treePrev if (sNP == null) { node.addLeaf(HCLElementTypes.HD_LINE, line, stopNode) node.addLeaf(HCLElementTypes.HD_EOL, "\n", stopNode) } else { assert(sNP.isHD_EOL) node.addLeaf(HCLElementTypes.HD_EOL, "\n", sNP) node.addLeaf(HCLElementTypes.HD_LINE, line, sNP) } } else assert(false) } } // Remove extra lines if (iter != null && iter != stopNode) { val iTP = iter.treePrev if (iTP != null && iTP.isHD_EOL) { if (stopNode == null) { node.removeRange(iTP, node.lastChildNode) } else { node.removeRange(iTP, stopNode.treePrev) } } else { node.removeRange(iter, stopNode) } } assert(node.lastChildNode?.isHD_EOL ?: true) check(element) return element } private fun check(element: HCLHeredocContent) { val node = element.node val lines = node.getChildren(TokenSet.create(HCLElementTypes.HD_LINE)) for (line in lines) { assert(line.treeNext.isHD_EOL) { "Line HD_LINE (${line.text}) should be terminated with HD_EOL" } } } companion object { fun getReplacementLines(newText: String): List<Pair<String, Boolean>> { if (newText == "") (return emptyList()) // TODO: Convert line separators to \n ? return StringUtil.splitByLinesKeepSeparators(newText).toList().map { it.removeSuffix("\n") to it.endsWith("\n") } } private fun lookupLine(node: TreeElement, n: Int): ASTNode? { var cn: ASTNode? = node.firstChildNode var counter = 0 while (cn != null) { if (counter == n) return cn if (cn.elementType == HCLElementTypes.HD_EOL) counter++ cn = cn.treeNext } return null } private fun nextLine(node: ASTNode): ASTNode? { if (node.isHD_EOL) { return node.treeNext } else { return node.treeNext?.treeNext } } } override fun handleContentChange(element: HCLHeredocContent, newContent: String): HCLHeredocContent { if (element is HCLHeredocContentMixin) { return handleContentChange(element, TextRange.from(0, element.textLength), newContent) } return replaceStupidly(element, newContent) } fun replaceStupidly(element: HCLHeredocContent, newContent: String): HCLHeredocContent { // Do simple full replacement val newLines = getReplacementLines(newContent) val node = element.node if (node.firstChildNode != null) { node.removeRange(node.firstChildNode, null) } for ((line, _) in newLines) { if (line.isNotEmpty()) node.addLeaf(HCLElementTypes.HD_LINE, line, null) node.addLeaf(HCLElementTypes.HD_EOL, "\n", null) } return element } override fun getRangeInElement(element: HCLHeredocContent): TextRange { if (element.textLength == 0) return TextRange.EMPTY_RANGE return TextRange.from(0, element.textLength - 1) } } val ASTNode.isHD_EOL: Boolean get() = this.elementType == HCLElementTypes.HD_EOL
apache-2.0
0e73bdf0729455d888e0f9ae2927a1bd
33.371681
130
0.645597
4.006189
false
false
false
false
carlphilipp/chicago-commutes
android-app/src/main/kotlin/fr/cph/chicago/core/adapter/BikeAdapter.kt
1
2304
/** * Copyright 2021 Carl-Philipp Harmant * * * 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 fr.cph.chicago.core.adapter import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.TextView import fr.cph.chicago.R import fr.cph.chicago.core.listener.BikeStationOnClickListener import fr.cph.chicago.core.model.BikeStation /** * Adapter that will handle bikes * * @author Carl-Philipp Harmant * @version 1 */ class BikeAdapter(private var bikeStations: List<BikeStation> = listOf()) : BaseAdapter() { override fun getCount(): Int { return bikeStations.size } override fun getItem(position: Int): Any { return bikeStations[position] } override fun getItemId(position: Int): Long { return position.toLong() } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? { var view = convertView val station = getItem(position) as BikeStation val holder: ViewHolder if (view == null) { val vi = parent.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater view = vi.inflate(R.layout.list_bike, parent, false) holder = ViewHolder(view.findViewById(R.id.station_name)) view.tag = holder } else { holder = view.tag as ViewHolder } holder.stationNameView.text = station.name view?.setOnClickListener(BikeStationOnClickListener(station)) return view } fun updateBikeStations(bikeStations: List<BikeStation>) { this.bikeStations = bikeStations } private class ViewHolder(val stationNameView: TextView) }
apache-2.0
762f99740e5853d0df7a1437285d4fb2
28.922078
103
0.700955
4.34717
false
false
false
false
danrien/projectBlue
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/shared/promises/extensions/FuturePromise.kt
2
2046
package com.lasthopesoftware.bluewater.shared.promises.extensions import com.namehillsoftware.handoff.promises.Promise import com.namehillsoftware.handoff.promises.propagation.CancellationProxy import org.joda.time.Duration import java.util.concurrent.* fun <Resolution> Promise<Resolution>.toFuture() = FuturePromise(this) class FuturePromise<Resolution>(promise: Promise<Resolution>) : Future<Resolution?> { private val defaultCancellationDuration = Duration.standardSeconds(30) private val cancellationProxy = CancellationProxy() private val promise: Promise<Unit> private var resolution: Resolution? = null private var rejection: Throwable? = null private var isCompleted = false override fun cancel(mayInterruptIfRunning: Boolean): Boolean { if (isCompleted) return false cancellationProxy.run() return true } override fun isCancelled(): Boolean { return cancellationProxy.isCancelled } override fun isDone(): Boolean { return isCompleted } @Throws(InterruptedException::class, ExecutionException::class, TimeoutException::class) override fun get(): Resolution? { val countDownLatch = CountDownLatch(1) promise.then { countDownLatch.countDown() } if (countDownLatch.await(defaultCancellationDuration.millis, TimeUnit.MILLISECONDS)) return getResolution() throw TimeoutException() } @Throws(InterruptedException::class, ExecutionException::class, TimeoutException::class) override fun get(timeout: Long, unit: TimeUnit): Resolution? { val countDownLatch = CountDownLatch(1) promise.then { countDownLatch.countDown() } if (countDownLatch.await(timeout, unit)) return getResolution() throw TimeoutException() } @Throws(ExecutionException::class) private fun getResolution(): Resolution? { rejection?.also { throw ExecutionException(rejection) } return resolution } init { cancellationProxy.doCancel(promise) this.promise = promise .then({ r: Resolution -> resolution = r isCompleted = true }, { e: Throwable? -> rejection = e isCompleted = true }) } }
lgpl-3.0
92ae1e05b2a9953b53a64637837e7e7f
30.476923
109
0.769306
4.236025
false
false
false
false
tgirard12/kotlin-talk
talk/src/main/kotlin/com/tgirard12/kotlintalk/10_Collection.kt
1
1140
package com.tgirard12.kotlintalk fun main(args: Array<String>) { // empty list val mutableList0 = mutableListOf<String>() println(mutableList0) // mutable val mutableList = mutableListOf("a", "b") println(mutableList) mutableList.add("c") mutableList += "d" // Operator overloading http://kotlinlang.org/docs/reference/operator-overloading.html println(mutableList) // create a read only list val readOnly = listOf("D", "E") println(readOnly) println(readOnly[0]) // readOnly.add // no add method // Question // Type check cast : like instance of println(readOnly is kotlin.collections.List<*>) println(readOnly is kotlin.collections.MutableList) println(readOnly is java.util.List<*>) println(mutableList is kotlin.collections.List<*>) println(mutableList is kotlin.collections.MutableList) println(mutableList is java.util.List<*>) // Map println(hashMapOf(1 to "one")) // operation on list println( readOnly.filter { it == "D" } .count()) println(readOnly.sumBy { it.length }) }
apache-2.0
09d1648c8f79feaf21cb7ffa3f4697cc
24.931818
116
0.649123
4.318182
false
false
false
false
nlefler/Glucloser
Glucloser/app/src/main/kotlin/com/nlefler/glucloser/a/dataSource/PlaceFactory.kt
1
5729
package com.nlefler.glucloser.a.dataSource import android.os.Bundle import android.util.Log import com.nlefler.glucloser.a.dataSource.jsonAdapter.PlaceJsonAdapter import com.nlefler.glucloser.a.db.DBManager import com.nlefler.glucloser.a.models.CheckInPushedData import com.nlefler.glucloser.a.models.Place import com.nlefler.glucloser.a.models.PlaceEntity import com.nlefler.glucloser.a.models.parcelable.PlaceParcelable import com.nlefler.nlfoursquare.Model.Venue.NLFoursquareVenue import com.squareup.moshi.JsonAdapter import com.squareup.moshi.Moshi import io.requery.kotlin.desc import io.requery.kotlin.eq import io.requery.query.Result import rx.Observable import java.util.* import javax.inject.Inject /** * Created by Nathan Lefler on 12/24/14. */ class PlaceFactory @Inject constructor(val dbManager: DBManager) { private val LOG_TAG = "PlaceFactory" fun placeForId(id: String): Observable<Result<PlaceEntity>> { if (id.isEmpty()) { return Observable.error(Exception("Invalid Id")) } return dbManager.data.select(PlaceEntity::class).where(Place::primaryId.eq(id)).get().toSelfObservable() } fun mostUsedPlaces(limit: Int = 10): Observable<Result<PlaceEntity>> { return dbManager.data.select(PlaceEntity::class).orderBy(Place::visitCount.desc()).limit(limit).get().toSelfObservable() } fun parcelableFromFoursquareVenue(venue: NLFoursquareVenue?): PlaceParcelable? { if (venue == null || !IsVenueValid(venue)) { Log.e(LOG_TAG, "Unable to create Place from 4sq venue") return null } val parcelable = PlaceParcelable() parcelable.name = venue.name parcelable.foursquareId = venue.id parcelable.latitude = venue.location.lat parcelable.longitude = venue.location.lng return parcelable } fun jsonAdapter(): JsonAdapter<PlaceEntity> { return Moshi.Builder() .add(PlaceJsonAdapter()) .build().adapter(PlaceEntity::class.java) } fun placeFromFoursquareVenue(venue: NLFoursquareVenue?): Observable<Place> { if (venue == null || !IsVenueValid(venue)) { val errorMessage = "Unable to create Place from 4sq venue" Log.e(LOG_TAG, errorMessage) return Observable.error(Exception(errorMessage)) } return placeForFoursquareId(venue.id).map { result -> var place = result.firstOrNull() if (place != null) { return@map place } place = PlaceEntity() place.foursquareId = venue.id place.name = venue.name place.latitude = venue.location.lat place.longitude = venue.location.lng place.visitCount = 0 return@map place } } fun parcelableFromPlace(place: Place): PlaceParcelable? { val parcelable = PlaceParcelable() parcelable.name = place.name parcelable.foursquareId = place.foursquareId parcelable.latitude = place.latitude parcelable.longitude = place.longitude return parcelable } fun placeFromParcelable(parcelable: PlaceParcelable): Place { val place = PlaceEntity() place.primaryId = parcelable.primaryId place.foursquareId = parcelable.foursquareId place.name = parcelable.name place.latitude = parcelable.latitude place.longitude = parcelable.longitude place.visitCount = parcelable.visitCount return place } fun arePlacesEqual(place1: Place?, place2: Place?): Boolean { if (place1 == null || place2 == null) { return false } val idOK = place1.foursquareId == place2.foursquareId val nameOK = place1.name == place2.name val latOK = place1.latitude == place2.latitude val lonOK = place1.longitude == place2.longitude return idOK && nameOK && latOK && lonOK } fun placeParcelableFromCheckInData(data: Bundle?): PlaceParcelable? { if (data == null) { Log.e(LOG_TAG, "Cannot create Place from check-in data, bundle null") return null } val checkInDataSerialized = data.getString("venueData") if (checkInDataSerialized == null || checkInDataSerialized.isEmpty()) { Log.e(LOG_TAG, "Cannot create Place from check-in data, parse bundle null") return null } val jsonAdapter = Moshi.Builder().build().adapter(CheckInPushedData::class.java) val checkInData = jsonAdapter.fromJson(checkInDataSerialized) if (checkInData == null) { Log.e(LOG_TAG, "Cannot create Place from check-in data, couldn't parse data") return null } val placeParcelable = PlaceParcelable() placeParcelable.foursquareId = checkInData.venueId placeParcelable.name = checkInData.venueName if (checkInData.venueLat != 0f) { placeParcelable.latitude = checkInData.venueLat } if (checkInData.venueLon != 0f) { placeParcelable.longitude = checkInData.venueLon } return placeParcelable } private fun placeForFoursquareId(id: String): Observable<Result<PlaceEntity>> { if (id.isEmpty()) { return Observable.error(Exception("Invalid Id")) } return dbManager.data.select(PlaceEntity::class).where(Place::foursquareId.eq(id)).get().toSelfObservable() } private fun IsVenueValid(venue: NLFoursquareVenue?): Boolean { return venue != null && venue.id != null && !venue.id.isEmpty() && venue.name != null && !venue.name.isEmpty() } }
gpl-2.0
ba4ba455c9e358f0a52609a751dd348e
35.031447
128
0.653692
4.269001
false
false
false
false
EyeBody/EyeBody
EyeBody2/app/src/main/java/com/example/android/eyebody/management/main/MainManagementFragment.kt
1
7560
package com.example.android.eyebody.management.main import android.content.Context.MODE_PRIVATE import android.content.Intent import android.os.Bundle import android.os.Parcelable import android.support.constraint.ConstraintLayout import android.support.v7.app.AppCompatActivity import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AbsListView import android.widget.ListView import com.example.android.eyebody.R import com.example.android.eyebody.management.BasePageFragment import kotlinx.android.synthetic.main.fragment_management_main.* /** * Created by YOON on 2017-11-11 */ class MainManagementFragment : BasePageFragment() { private val TAG = "mydbg_MainTabFrag" private var contents: ArrayList<MainManagementContent>? = null private var listviewGlobal: ListView? = null private var listviewStatus: Parcelable? = null val contentOriginHeight by lazy { activity.findViewById<ConstraintLayout>(R.id.managementWholeConstraint).height } val originButtonTop by lazy { addButton.top } val activateActionbar by lazy { activity .getSharedPreferences(getString(R.string.getSharedPreference_configuration_Only_Int),MODE_PRIVATE) .getInt(getString(R.string.sharedPreference_activateActionbar),0) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (arguments != null) { pageNumber = arguments.getInt(ARG_PAGE_NUMBER) } } override fun onPause() { super.onPause() listviewStatus = listviewGlobal?.onSaveInstanceState() } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { // TODO 재사용같은거 할 수 있나 (나중에 memory 밖으로 벗어날때??) val mView = inflater!!.inflate(R.layout.fragment_management_main, container, false) listviewGlobal = mView.findViewById(R.id.listview_main_management) val listview: ListView = listviewGlobal ?: return mView contents = MainManagementContent.getMainManagementContentArrayListForAdapterFromJson(context) if (contents != null) { listview.adapter = MainManagementAdapter(context, contents!!) //for log for (content in contents!!) Log.d(TAG, "content : ${content.isInProgress} , ${content.startDate}, ${content.desireDate}, ${content.startWeight}, ${content.desireWeight}, ${content.dateDataList}") } else { listview.adapter = MainManagementAdapter(context, arrayListOf()) } if (listviewStatus != null) { listview.onRestoreInstanceState(listviewStatus) } listview.setOnScrollListener(object : AbsListView.OnScrollListener { var oldUnitPositionY = 0 var oldVisibleItemPos = 0 var isUpScroll: Boolean? = null fun scrollCheck(){ val unitPositionY = -listview.getChildAt(0).top val visibleItemPos = listview.getPositionForView(listview.getChildAt(0)) if (oldVisibleItemPos < visibleItemPos) { isUpScroll = true } else if (oldVisibleItemPos > visibleItemPos) { isUpScroll = false } else { if (oldUnitPositionY < unitPositionY) { isUpScroll = true } else if (oldUnitPositionY > unitPositionY) { isUpScroll = false } } oldVisibleItemPos = visibleItemPos oldUnitPositionY = unitPositionY } override fun onScroll(view: AbsListView?, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) { if (listview.childCount >= 1) { scrollCheck() when (isUpScroll) { true -> { addButton.alpha -= 0.05f if (addButton.alpha < 0.3f) addButton.visibility = View.GONE if (addButton.alpha < 0) addButton.alpha = 0f } false -> { addButton.alpha += 0.1f if (addButton.alpha >= 0.3f) addButton.visibility = View.VISIBLE if (addButton.alpha > 1f) addButton.alpha = 1f } } if(activateActionbar==1) { val actionbar = (activity as AppCompatActivity).supportActionBar val content = activity.findViewById<ConstraintLayout>(R.id.managementWholeConstraint) if (actionbar != null) { content.top = actionbar.height - actionbar.hideOffset } when(isUpScroll){ true -> { if (actionbar != null) { actionbar.hideOffset += 15//(actionbar.height*0.05f).toInt() if (actionbar.hideOffset > actionbar.height) actionbar.hideOffset = actionbar.height content.top = actionbar.height - actionbar.hideOffset } } false -> { if (actionbar != null) { actionbar.hideOffset = 0// (actionbar.height*0.1f).toInt() if (actionbar.hideOffset < 0) actionbar.hideOffset = 0 content.top = actionbar.height - actionbar.hideOffset } } } } } } override fun onScrollStateChanged(view: AbsListView?, scrollState: Int) { } }) return mView } override fun onStart() { super.onStart() addButton.setOnClickListener { val mInt = Intent(context, NewMainContentActivity::class.java) startActivity(mInt) } } companion object { private val ARG_PAGE_NUMBER = "param1" /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param pn PageNumber (Int) * @return A new instance of fragment MainManagementFragment. */ fun newInstance(pn: Int): MainManagementFragment { val fragment = MainManagementFragment() val args = Bundle() args.putInt(ARG_PAGE_NUMBER, pn) fragment.arguments = args return fragment } } override fun setUserVisibleHint(isVisibleToUser: Boolean) { super.setUserVisibleHint(isVisibleToUser) if (isVisibleToUser) { /* fragment가 visible 해질 때 action을 부여하고 싶은 경우 */ } else { /* fragment가 visible 하지 않지만 load되어 있는 경우 */ } } }// Required empty public constructor
mit
9298aa3e666bb778f0f3657b04e0391c
38.52381
207
0.550602
5.320513
false
false
false
false
SUPERCILEX/Robot-Scouter
feature/scouts/src/main/java/com/supercilex/robotscouter/feature/scouts/viewholder/SpinnerViewHolder.kt
1
1717
package com.supercilex.robotscouter.feature.scouts.viewholder import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import com.supercilex.robotscouter.core.data.model.updateSelectedValueId import com.supercilex.robotscouter.core.model.Metric import com.supercilex.robotscouter.shared.scouting.MetricViewHolderBase import kotlinx.android.synthetic.main.scout_spinner.* internal class SpinnerViewHolder( itemView: View ) : MetricViewHolderBase<Metric.List, List<Metric.List.Item>>(itemView), AdapterView.OnItemSelectedListener { init { spinner.adapter = ArrayAdapter<String>( itemView.context, android.R.layout.simple_spinner_item ).apply { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) } spinner.setBackgroundResource( com.google.android.material.R.drawable.abc_spinner_mtrl_am_alpha) spinner.onItemSelectedListener = this } public override fun bind() { super.bind() updateAdapter() spinner.setSelection(metric.selectedValueId?.let { id -> metric.value.indexOfFirst { it.id == id } } ?: 0) } private fun updateAdapter() { @Suppress("UNCHECKED_CAST") // We know the metric type (spinner.adapter as ArrayAdapter<String>).apply { clear() addAll(metric.value.map { it.name }) } } override fun onItemSelected(parent: AdapterView<*>, view: View, itemPosition: Int, id: Long) { metric.updateSelectedValueId(metric.value[itemPosition].id) } override fun onNothingSelected(view: AdapterView<*>) = Unit }
gpl-3.0
ba5a25888897d24f5d7e6e7dcce22c80
34.770833
98
0.683751
4.590909
false
false
false
false
xfournet/intellij-community
platform/platform-impl/src/com/intellij/internal/statistic/eventLog/LogEventSerializer.kt
1
1442
/* * Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package com.intellij.internal.statistic.eventLog import com.google.common.reflect.TypeToken import com.google.gson.* import com.intellij.util.containers.hash.HashMap import java.lang.reflect.Type object LogEventSerializer { private val gson = GsonBuilder().registerTypeAdapter(LogEventAction::class.java, LogEventJsonDeserializer()).create() fun toString(session: Any): String { return gson.toJson(session) } fun fromString(line: String): LogEvent { return gson.fromJson(line, LogEvent::class.java) } } class LogEventJsonDeserializer : JsonDeserializer<LogEventAction> { @Throws(JsonParseException::class) override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): LogEventAction { val obj = json.asJsonObject val action = LogEventAction(obj.get("id").asString) if (obj.has("data")) { val dataObj = obj.getAsJsonObject("data") for ((key, value) in context.deserialize<HashMap<String, Any>>(dataObj, object : TypeToken<HashMap<String, Any>>() {}.type)) { if (value is Double && value % 1 == 0.0) { val intValue = Math.round(value).toInt() action.addData(key, intValue) } else { action.addData(key, value) } } } return action } }
apache-2.0
c7a19e23b8c6002170987918dcee115d
33.357143
140
0.697642
4.16763
false
false
false
false
Kotlin/dokka
runners/gradle-plugin/src/main/kotlin/org/jetbrains/dokka/gradle/kotlin/kotlinCompilationUtils.kt
1
1806
package org.jetbrains.dokka.gradle.kotlin import org.gradle.api.Project import org.jetbrains.dokka.gradle.kotlin import org.jetbrains.kotlin.gradle.dsl.KotlinCommonOptions import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension import org.jetbrains.kotlin.gradle.dsl.KotlinSingleTargetExtension import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet internal typealias KotlinCompilation = org.jetbrains.kotlin.gradle.plugin.KotlinCompilation<KotlinCommonOptions> internal fun Project.compilationsOf(sourceSet: KotlinSourceSet): List<KotlinCompilation> { //KT-45412 Make sure .kotlinSourceSets and .allKotlinSourceSets include the default source set return allCompilationsOf(sourceSet).filter { compilation -> sourceSet in compilation.kotlinSourceSets || sourceSet == compilation.defaultSourceSet } } internal fun Project.allCompilationsOf( sourceSet: KotlinSourceSet ): List<KotlinCompilation> { return when (val kotlin = kotlin) { is KotlinMultiplatformExtension -> allCompilationsOf(kotlin, sourceSet) is KotlinSingleTargetExtension<*> -> allCompilationsOf(kotlin, sourceSet) else -> emptyList() } } private fun allCompilationsOf( kotlin: KotlinMultiplatformExtension, sourceSet: KotlinSourceSet ): List<KotlinCompilation> { val allCompilations = kotlin.targets.flatMap { target -> target.compilations } return allCompilations.filter { compilation -> sourceSet in compilation.allKotlinSourceSets || sourceSet == compilation.defaultSourceSet } } private fun allCompilationsOf( kotlin: KotlinSingleTargetExtension<*>, sourceSet: KotlinSourceSet ): List<KotlinCompilation> { return kotlin.target.compilations.filter { compilation -> sourceSet in compilation.allKotlinSourceSets } }
apache-2.0
fca9897ebb6ed0f77ed081d3bf6ca8fb
39.133333
108
0.784053
4.961538
false
false
false
false
google/ksp
test-utils/testData/api/nullableTypes.kt
1
1347
/* * Copyright 2021 Google LLC * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ // WITH_RUNTIME // TEST PROCESSOR: NullableTypeProcessor // EXPECTED: // a: [], [@TA] // b: [SUSPEND], [@TA] // c: [], [@TA] // d: [SUSPEND], [@TA] // e: [], [@TA] // f: [], [@TA] // g: [], [@TA] // h: [], [@TA] // i: [], [@TA] // j: [], [@TA] // k: [], [@TA] // END @Target(AnnotationTarget.TYPE) annotation class TA val a: @TA (() -> Unit)? = {} val b: (@TA suspend () -> Unit)? = {} val c: @TA (() -> Unit) = {} val d: (@TA suspend () -> Unit) = {} val e: (@TA String)? // Parser doesn't allow `@TA (String)` val f: (@TA String)? = "" val g: (@TA String?) = "" val h: (@TA String?)? = "" val i: @TA String = "" val j: (@TA String) = "" val k: ((@TA String)?) = ""
apache-2.0
1758c1bbceff3c5a0ea9aa03b360ec73
26.489796
85
0.605791
3.237981
false
false
false
false
herbeth1u/VNDB-Android
app/src/main/java/com/booboot/vndbandroid/model/vndbandroid/Platform.kt
1
2221
package com.booboot.vndbandroid.model.vndbandroid import android.content.Context import androidx.annotation.ColorInt import androidx.annotation.ColorRes import com.booboot.vndbandroid.R import com.booboot.vndbandroid.model.vndb.Label data class Platform( val text: String = "", @ColorRes val color: Int = 0 ) { @ColorInt fun textColor(context: Context) = Label.textColor(context, color) @ColorInt fun backgroundColor(context: Context) = Label.backgroundColor(context, color) } val PLATFORMS = mapOf( "web" to Platform("Web", R.color.web), "win" to Platform("PC", R.color.pc), "dos" to Platform("DOS", R.color.dos), "lin" to Platform("Linux", R.color.linux), "mac" to Platform("Mac", R.color.mac), "ios" to Platform("iOS", R.color.ios), "and" to Platform("Android", R.color.android), "dvd" to Platform("DVD", R.color.dvd), "bdp" to Platform("Blu-ray", R.color.bluray), "fmt" to Platform("FM Towns", R.color.fmtowns), "gba" to Platform("GBA", R.color.gba), "gbc" to Platform("GBC", R.color.gbc), "msx" to Platform("MSX", R.color.msx), "nds" to Platform("DS", R.color.ds), "nes" to Platform("NES", R.color.nes), "p88" to Platform("PC-88", R.color.pc88), "p98" to Platform("PC-98", R.color.pc98), "pce" to Platform("PC Engine", R.color.pcengine), "pcf" to Platform("PC-FX", R.color.pcfx), "psp" to Platform("PSP", R.color.psp), "ps1" to Platform("PS1", R.color.ps1), "ps2" to Platform("PS2", R.color.ps2), "ps3" to Platform("PS3", R.color.ps3), "ps4" to Platform("PS4", R.color.ps4), "psv" to Platform("PS Vita", R.color.psvita), "drc" to Platform("Dreamcast", R.color.dreamcast), "sat" to Platform("Saturn", R.color.saturn), "sfc" to Platform("SNES", R.color.snes), "wii" to Platform("Wii", R.color.wii), "wiu" to Platform("Wii U", R.color.wiiu), "swi" to Platform("Switch", R.color.nswitch), "n3d" to Platform("3DS", R.color._3ds), "x68" to Platform("X68000", R.color.x68), "xb1" to Platform("Xbox", R.color.xbox), "xb3" to Platform("X360", R.color.xbox360), "xbo" to Platform("XOne", R.color.xboxone), "oth" to Platform("Other", R.color.other) )
gpl-3.0
82e63d2ded3686831982934bd9b3649a
37.293103
81
0.639352
2.873221
false
false
false
false
SamuelGjk/NHentai-android
app/src/main/kotlin/moe/feng/nhentai/util/extension/CommonExtensions.kt
3
788
package moe.feng.nhentai.util.extension import android.util.Log import kotlin.reflect.KFunction inline fun <reified OBJ, reified RESULT> OBJ.tryRun(method: OBJ.() -> RESULT): RESULT? = try { method(this) } catch (e: Exception) { e.printStackTrace() null } inline fun <reified METHOD: KFunction<RESULT>, reified RESULT> METHOD.tryCall(vararg args: Any?): RESULT? = try { this.call(*args) } catch (e: Exception) { e.printStackTrace() null } fun <T> T.printAsJson(): T = apply { Log.i("Debug", objectAsJson()) } private val BRACKETS = arrayOf("[", "]", "{", "}", "(", ")", ",", ".", "<", ">", "《", "》", "【", "】", "{", "}") fun String.firstWord(): String? = (0 until length).map { substring(it, it + 1) }.firstOrNull { it !in BRACKETS }
gpl-3.0
1b4ec467cafa70bf8c2688adbe458229
25.758621
88
0.603093
3.067194
false
false
false
false
tutao/tutanota
app-android/app/src/main/java/de/tutao/tutanota/alarms/AlarmNotificationEntity.kt
1
3579
package de.tutao.tutanota.alarms import androidx.room.Embedded import androidx.room.Entity import androidx.room.TypeConverter import androidx.room.TypeConverters import de.tutao.tutanota.* import de.tutao.tutanota.alarms.AlarmNotificationEntity.OperationTypeConverter import kotlinx.serialization.Serializable import java.util.* class RepeatRule( val frequency: RepeatPeriod, val interval: Int, val timeZone: TimeZone, val endValue: Long?, val endType: EndType, ) class AlarmInfo( val alarmIdentifier: String, val trigger: AlarmTrigger, ) /** * used for actual scheduling */ class AlarmNotification( val summary: String, val eventStart: Date, val eventEnd: Date, val alarmInfo: AlarmInfo, val repeatRule: RepeatRule?, val user: String, ) /** * this is passed over IPC or downloaded from the server */ @Serializable class EncryptedAlarmNotification( val operation: OperationType, val summary: String, val eventStart: String, val eventEnd: String, val alarmInfo: EncryptedAlarmInfo, val repeatRule: EncryptedRepeatRule?, val notificationSessionKeys: List<AlarmNotificationEntity.NotificationSessionKey>, val user: String, ) /** * stored in the database */ @Entity(primaryKeys = ["identifier"], tableName = "AlarmNotification") @TypeConverters(OperationTypeConverter::class) class AlarmNotificationEntity( val operation: OperationType?, val summary: String?, val eventStart: String?, val eventEnd: String?, @field:Embedded val alarmInfo: EncryptedAlarmInfo, @field:Embedded val repeatRule: EncryptedRepeatRule?, // in case of a delete operation there is no session key @field:Embedded(prefix = "key") val notificationSessionKey: NotificationSessionKey?, val user: String?, ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as AlarmNotificationEntity if (alarmInfo != other.alarmInfo) return false return true } override fun hashCode(): Int { return alarmInfo.hashCode() } @Serializable class NotificationSessionKey( @field:Embedded val pushIdentifier: IdTuple, val pushIdentifierSessionEncSessionKey: String, ) class OperationTypeConverter { @TypeConverter fun fromNumber(number: Int): OperationType { return OperationType.values()[number] } @TypeConverter fun numberToOperationType(operationType: OperationType): Int { return operationType.ordinal } } } fun EncryptedAlarmNotification.toEntity(): AlarmNotificationEntity { // Server aggregate still has an array but it is always a single element (they are filtered before we get them // here) require(notificationSessionKeys.size == 1) { "Invalid notificationSessionKeys, must have exactly one key, has ${notificationSessionKeys.size}" } val notificationSessionKey = notificationSessionKeys.first() return AlarmNotificationEntity( operation = operation, summary = summary, eventStart = eventStart, eventEnd = eventEnd, alarmInfo = alarmInfo, repeatRule = repeatRule, notificationSessionKey = notificationSessionKey, user = user, ) } fun AlarmNotificationEntity.decrypt(crypto: AndroidNativeCryptoFacade, sessionKey: ByteArray): AlarmNotification { return AlarmNotification( summary = crypto.decryptString(summary!!, sessionKey), eventStart = crypto.decryptDate(eventStart!!, sessionKey), eventEnd = crypto.decryptDate(eventEnd!!, sessionKey), alarmInfo = alarmInfo.decrypt(crypto, sessionKey), repeatRule = repeatRule?.decrypt(crypto, sessionKey), user = user!!, ) }
gpl-3.0
35a9c6920dc352d0cce5682527cf9dd1
26.121212
114
0.761945
3.898693
false
false
false
false
Vavassor/Tusky
app/src/main/java/com/keylesspalace/tusky/LoginActivity.kt
1
14797
/* Copyright 2017 Andrew Dawson * * This file is a part of Tusky. * * 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. * * Tusky 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 Tusky; if not, * see <http://www.gnu.org/licenses>. */ package com.keylesspalace.tusky import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.net.Uri import android.os.Bundle import androidx.browser.customtabs.CustomTabsIntent import android.text.method.LinkMovementMethod import android.util.Log import android.view.MenuItem import android.view.View import android.widget.EditText import android.widget.TextView import androidx.appcompat.app.AlertDialog import com.keylesspalace.tusky.di.Injectable import com.keylesspalace.tusky.entity.AccessToken import com.keylesspalace.tusky.entity.AppCredentials import com.keylesspalace.tusky.network.MastodonApi import com.keylesspalace.tusky.util.CustomTabsHelper import com.keylesspalace.tusky.util.ThemeUtils import kotlinx.android.synthetic.main.activity_login.* import okhttp3.HttpUrl import retrofit2.Call import retrofit2.Callback import retrofit2.Response import javax.inject.Inject class LoginActivity : BaseActivity(), Injectable { @Inject lateinit var mastodonApi: MastodonApi private lateinit var preferences: SharedPreferences private var domain: String = "" private var clientId: String? = null private var clientSecret: String? = null private val oauthRedirectUri: String get() { val scheme = getString(R.string.oauth_scheme) val host = BuildConfig.APPLICATION_ID return "$scheme://$host/" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) if (savedInstanceState != null) { domain = savedInstanceState.getString(DOMAIN)!! clientId = savedInstanceState.getString(CLIENT_ID) clientSecret = savedInstanceState.getString(CLIENT_SECRET) } preferences = getSharedPreferences( getString(R.string.preferences_file_key), Context.MODE_PRIVATE) loginButton.setOnClickListener { onButtonClick() } whatsAnInstanceTextView.setOnClickListener { val dialog = AlertDialog.Builder(this) .setMessage(R.string.dialog_whats_an_instance) .setPositiveButton(R.string.action_close, null) .show() val textView = dialog.findViewById<TextView>(android.R.id.message) textView?.movementMethod = LinkMovementMethod.getInstance() } if (isAdditionalLogin()) { setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowTitleEnabled(false) } else { toolbar.visibility = View.GONE } } override fun requiresLogin(): Boolean { return false } override fun finish() { super.finish() if(isAdditionalLogin()) { overridePendingTransition(R.anim.slide_from_left, R.anim.slide_to_right) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { onBackPressed() return true } return super.onOptionsItemSelected(item) } override fun onSaveInstanceState(outState: Bundle) { outState.putString(DOMAIN, domain) outState.putString(CLIENT_ID, clientId) outState.putString(CLIENT_SECRET, clientSecret) super.onSaveInstanceState(outState) } /** * Obtain the oauth client credentials for this app. This is only necessary the first time the * app is run on a given server instance. So, after the first authentication, they are * saved in SharedPreferences and every subsequent run they are simply fetched from there. */ private fun onButtonClick() { loginButton.isEnabled = false domain = canonicalizeDomain(domainEditText.text.toString()) try { HttpUrl.Builder().host(domain).scheme("https").build() } catch (e: IllegalArgumentException) { setLoading(false) domainTextInputLayout.error = getString(R.string.error_invalid_domain) return } val callback = object : Callback<AppCredentials> { override fun onResponse(call: Call<AppCredentials>, response: Response<AppCredentials>) { if (!response.isSuccessful) { loginButton.isEnabled = true domainTextInputLayout.error = getString(R.string.error_failed_app_registration) setLoading(false) Log.e(TAG, "App authentication failed. " + response.message()) return } val credentials = response.body() clientId = credentials!!.clientId clientSecret = credentials.clientSecret redirectUserToAuthorizeAndLogin(domainEditText) } override fun onFailure(call: Call<AppCredentials>, t: Throwable) { loginButton.isEnabled = true domainTextInputLayout.error = getString(R.string.error_failed_app_registration) setLoading(false) Log.e(TAG, Log.getStackTraceString(t)) } } mastodonApi .authenticateApp(domain, getString(R.string.app_name), oauthRedirectUri, OAUTH_SCOPES, getString(R.string.app_website)) .enqueue(callback) setLoading(true) } private fun redirectUserToAuthorizeAndLogin(editText: EditText) { /* To authorize this app and log in it's necessary to redirect to the domain given, * activity_login there, and the server will redirect back to the app with its response. */ val endpoint = MastodonApi.ENDPOINT_AUTHORIZE val redirectUri = oauthRedirectUri val parameters = HashMap<String, String>() parameters["client_id"] = clientId!! parameters["redirect_uri"] = redirectUri parameters["response_type"] = "code" parameters["scope"] = OAUTH_SCOPES val url = "https://" + domain + endpoint + "?" + toQueryString(parameters) val uri = Uri.parse(url) if (!openInCustomTab(uri, this)) { val viewIntent = Intent(Intent.ACTION_VIEW, uri) if (viewIntent.resolveActivity(packageManager) != null) { startActivity(viewIntent) } else { editText.error = getString(R.string.error_no_web_browser_found) setLoading(false) } } } override fun onStop() { super.onStop() preferences.edit() .putString("domain", domain) .putString("clientId", clientId) .putString("clientSecret", clientSecret) .apply() } override fun onStart() { super.onStart() /* Check if we are resuming during authorization by seeing if the intent contains the * redirect that was given to the server. If so, its response is here! */ val uri = intent.data val redirectUri = oauthRedirectUri if (uri != null && uri.toString().startsWith(redirectUri)) { // This should either have returned an authorization code or an error. val code = uri.getQueryParameter("code") val error = uri.getQueryParameter("error") domain = preferences.getString(DOMAIN, "")!! if (code != null && domain.isNotEmpty()) { /* During the redirect roundtrip this Activity usually dies, which wipes out the * instance variables, so they have to be recovered from where they were saved in * SharedPreferences. */ clientId = preferences.getString(CLIENT_ID, null) clientSecret = preferences.getString(CLIENT_SECRET, null) setLoading(true) /* Since authorization has succeeded, the final step to log in is to exchange * the authorization code for an access token. */ val callback = object : Callback<AccessToken> { override fun onResponse(call: Call<AccessToken>, response: Response<AccessToken>) { if (response.isSuccessful) { onLoginSuccess(response.body()!!.accessToken) } else { setLoading(false) domainTextInputLayout.error = getString(R.string.error_retrieving_oauth_token) Log.e(TAG, String.format("%s %s", getString(R.string.error_retrieving_oauth_token), response.message())) } } override fun onFailure(call: Call<AccessToken>, t: Throwable) { setLoading(false) domainTextInputLayout.error = getString(R.string.error_retrieving_oauth_token) Log.e(TAG, String.format("%s %s", getString(R.string.error_retrieving_oauth_token), t.message)) } } mastodonApi.fetchOAuthToken(domain, clientId, clientSecret, redirectUri, code, "authorization_code").enqueue(callback) } else if (error != null) { /* Authorization failed. Put the error response where the user can read it and they * can try again. */ setLoading(false) domainTextInputLayout.error = getString(R.string.error_authorization_denied) Log.e(TAG, String.format("%s %s", getString(R.string.error_authorization_denied), error)) } else { // This case means a junk response was received somehow. setLoading(false) domainTextInputLayout.error = getString(R.string.error_authorization_unknown) } } else { // first show or user cancelled login setLoading(false) } } private fun setLoading(loadingState: Boolean) { if (loadingState) { loginLoadingLayout.visibility = View.VISIBLE loginInputLayout.visibility = View.GONE } else { loginLoadingLayout.visibility = View.GONE loginInputLayout.visibility = View.VISIBLE loginButton.isEnabled = true } } private fun isAdditionalLogin(): Boolean { return intent.getBooleanExtra(LOGIN_MODE, false) } private fun onLoginSuccess(accessToken: String) { setLoading(true) accountManager.addAccount(accessToken, domain) val intent = Intent(this, MainActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK startActivity(intent) finish() overridePendingTransition(R.anim.explode, R.anim.explode) } companion object { private const val TAG = "LoginActivity" // logging tag private const val OAUTH_SCOPES = "read write follow" private const val LOGIN_MODE = "LOGIN_MODE" private const val DOMAIN = "domain" private const val CLIENT_ID = "clientId" private const val CLIENT_SECRET = "clientSecret" @JvmStatic fun getIntent(context: Context, mode: Boolean): Intent { val loginIntent = Intent(context, LoginActivity::class.java) loginIntent.putExtra(LOGIN_MODE, mode) return loginIntent } /** Make sure the user-entered text is just a fully-qualified domain name. */ private fun canonicalizeDomain(domain: String): String { // Strip any schemes out. var s = domain.replaceFirst("http://", "") s = s.replaceFirst("https://", "") // If a username was included (e.g. [email protected]), just take what's after the '@'. val at = s.lastIndexOf('@') if (at != -1) { s = s.substring(at + 1) } return s.trim { it <= ' ' } } /** * Chain together the key-value pairs into a query string, for either appending to a URL or * as the content of an HTTP request. */ private fun toQueryString(parameters: Map<String, String>): String { val s = StringBuilder() var between = "" for ((key, value) in parameters) { s.append(between) s.append(Uri.encode(key)) s.append("=") s.append(Uri.encode(value)) between = "&" } return s.toString() } private fun openInCustomTab(uri: Uri, context: Context): Boolean { val toolbarColor = ThemeUtils.getColorById(context, "custom_tab_toolbar") val builder = CustomTabsIntent.Builder() builder.setToolbarColor(toolbarColor) val customTabsIntent = builder.build() try { val packageName = CustomTabsHelper.getPackageNameToUse(context) /* If we cant find a package name, it means theres no browser that supports * Chrome Custom Tabs installed. So, we fallback to the webview */ if (packageName == null) { return false } else { customTabsIntent.intent.`package` = packageName customTabsIntent.launchUrl(context, uri) } } catch (e: ActivityNotFoundException) { Log.w(TAG, "Activity was not found for intent, " + customTabsIntent.toString()) return false } return true } } }
gpl-3.0
6ceb8fe87350e733710872da0994e9ae
38.884097
106
0.602419
5.182837
false
false
false
false
alashow/music-android
modules/common-ui-components/src/main/java/tm/alashow/ui/Lottie.kt
1
803
/* * Copyright (C) 2021, Alashov Berkeli * All rights reserved. */ package tm.alashow.ui import androidx.compose.material.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import com.airbnb.lottie.LottieProperty import com.airbnb.lottie.SimpleColorFilter import com.airbnb.lottie.compose.rememberLottieDynamicProperties import com.airbnb.lottie.compose.rememberLottieDynamicProperty @Composable fun colorFilterDynamicProperty(color: Color = MaterialTheme.colors.secondary) = rememberLottieDynamicProperties( rememberLottieDynamicProperty( property = LottieProperty.COLOR_FILTER, value = SimpleColorFilter(color.toArgb()), keyPath = arrayOf( "**", ) ), )
apache-2.0
982b468a8c09bb603adacc0842c76532
31.12
112
0.774595
4.387978
false
false
false
false
ebraminio/DroidPersianCalendar
PersianCalendar/src/main/java/com/byagowi/persiancalendar/ui/preferences/widgetnotification/WidgetNotificationFragment.kt
1
4221
package com.byagowi.persiancalendar.ui.preferences.widgetnotification import android.graphics.Color import android.os.Bundle import androidx.appcompat.app.AlertDialog import androidx.core.content.edit import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import com.byagowi.persiancalendar.* import com.byagowi.persiancalendar.utils.appPrefs import java.util.* // Don't use MainActivity here as it is used in WidgetConfigurationActivity also class WidgetNotificationFragment : PreferenceFragmentCompat() { override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) = addPreferencesFromResource(R.xml.preferences_widget_notification) override fun onPreferenceTreeClick(preference: Preference?): Boolean { val activity = activity ?: return false val sharedPreferences = activity.appPrefs if (preference?.key == PREF_SELECTED_WIDGET_TEXT_COLOR) { val colorPickerView = ColorPickerView(activity) colorPickerView.setColorsToPick( listOf(0xFFFFFFFFL, 0xFFE65100L, 0xFF00796bL, 0xFFFEF200L, 0xFF202020L) ) colorPickerView.setPickedColor( Color.parseColor( sharedPreferences.getString( PREF_SELECTED_WIDGET_TEXT_COLOR, DEFAULT_SELECTED_WIDGET_TEXT_COLOR ) ) ) colorPickerView.hideAlphaSeekBar() val padding = (activity.resources.displayMetrics.density * 10).toInt() colorPickerView.setPadding(padding, padding, padding, padding) AlertDialog.Builder(activity).apply { setTitle(R.string.widget_text_color) setView(colorPickerView) setPositiveButton(R.string.accept) { _, _ -> try { sharedPreferences.edit { putString( PREF_SELECTED_WIDGET_TEXT_COLOR, "#%06X".format( Locale.ENGLISH, 0xFFFFFF and colorPickerView.pickerColor ) ) } } catch (e: Exception) { e.printStackTrace() } } setNegativeButton(R.string.cancel, null) }.show() return true } if (preference?.key == PREF_SELECTED_WIDGET_BACKGROUND_COLOR) { val colorPickerView = ColorPickerView(activity) colorPickerView.setColorsToPick(listOf(0x00000000L, 0x50000000L, 0xFF000000L)) colorPickerView.setPickedColor( Color.parseColor( sharedPreferences.getString( PREF_SELECTED_WIDGET_BACKGROUND_COLOR, DEFAULT_SELECTED_WIDGET_BACKGROUND_COLOR ) ) ) val padding = (activity.resources.displayMetrics.density * 10).toInt() colorPickerView.setPadding(padding, padding, padding, padding) AlertDialog.Builder(activity).apply { setTitle(R.string.widget_background_color) setView(colorPickerView) setPositiveButton(R.string.accept) { _, _ -> try { sharedPreferences.edit { putString( PREF_SELECTED_WIDGET_BACKGROUND_COLOR, "#%08X".format( Locale.ENGLISH, 0xFFFFFFFF and colorPickerView.pickerColor.toLong() ) ) } } catch (e: Exception) { e.printStackTrace() } } setNegativeButton(R.string.cancel, null) }.show() return true } return super.onPreferenceTreeClick(preference) } }
gpl-3.0
d63659b265bc458e75cb3363007e6245
39.586538
90
0.532575
5.854369
false
false
false
false
JTechMe/JumpGo
app/src/main/java/com/jtechme/jumpgo/search/SuggestionsManager.kt
1
1816
package com.jtechme.jumpgo.search import com.jtechme.jumpgo.database.HistoryItem import com.jtechme.jumpgo.search.suggestions.BaiduSuggestionsModel import com.jtechme.jumpgo.search.suggestions.DuckSuggestionsModel import com.jtechme.jumpgo.search.suggestions.GoogleSuggestionsModel import android.app.Application import com.anthonycr.bonsai.Single import com.anthonycr.bonsai.SingleAction internal object SuggestionsManager { @JvmStatic @Volatile var isRequestInProgress: Boolean = false @JvmStatic fun createGoogleQueryObservable(query: String, application: Application) = Single.create(SingleAction<List<HistoryItem>> { subscriber -> isRequestInProgress = true val results = GoogleSuggestionsModel(application).fetchResults(query) subscriber.onItem(results) subscriber.onComplete() isRequestInProgress = false }) @JvmStatic fun createBaiduQueryObservable(query: String, application: Application) = Single.create(SingleAction<List<HistoryItem>> { subscriber -> isRequestInProgress = true val results = BaiduSuggestionsModel(application).fetchResults(query) subscriber.onItem(results) subscriber.onComplete() isRequestInProgress = false }) @JvmStatic fun createDuckQueryObservable(query: String, application: Application) = Single.create(SingleAction<List<HistoryItem>> { subscriber -> isRequestInProgress = true val results = DuckSuggestionsModel(application).fetchResults(query) subscriber.onItem(results) subscriber.onComplete() isRequestInProgress = false }) }
mpl-2.0
e93f123596ff6db40623ae24e101d1fb
38.478261
85
0.678965
5.710692
false
false
false
false
wleroux/fracturedskies
src/main/kotlin/com/fracturedskies/render/common/shaders/TextureArray.kt
1
1122
package com.fracturedskies.render.common.shaders import org.lwjgl.opengl.GL11.* import org.lwjgl.opengl.GL12.* import org.lwjgl.opengl.GL30.GL_TEXTURE_2D_ARRAY import org.lwjgl.opengl.GL42.glTexStorage3D import java.nio.ByteBuffer class TextureArray(width: Int, height: Int, depth: Int, pixels: ByteBuffer, internalFormat: Int = GL_RGBA16, format: Int = GL_RGBA, type: Int = GL_UNSIGNED_BYTE) { val id = glGenTextures() init { glBindTexture(GL_TEXTURE_2D_ARRAY, id) glTexStorage3D(GL_TEXTURE_2D_ARRAY, 1, internalFormat, width, height, depth) glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, 0, width, height, depth, format, type, pixels) glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) glBindTexture(GL_TEXTURE_2D_ARRAY, 0) } fun close() { glDeleteTextures(id) } override fun toString() = String.format("TextureArray[$id]") }
unlicense
cbd5b2cece41c7482447207d68202b04
37.689655
163
0.735294
3.142857
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/processor/play/UpdateWorldSkyProcessor.kt
1
1830
/* * 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.network.vanilla.packet.processor.play import org.lanternpowered.server.network.packet.Packet import org.lanternpowered.server.network.packet.CodecContext import org.lanternpowered.server.network.packet.PacketProcessor import org.lanternpowered.server.network.vanilla.packet.type.play.UpdateWorldSkyPacket import org.lanternpowered.server.network.vanilla.packet.type.play.internal.ChangeGameStatePacket object UpdateWorldSkyProcessor : PacketProcessor<UpdateWorldSkyPacket> { override fun process(context: CodecContext, packet: UpdateWorldSkyPacket, output: MutableList<Packet>) { var rain = packet.rainStrength var darkness = packet.darkness // Rain strength may not be greater then 1.5 // TODO: Check what limit may cause issues rain = rain.coerceAtMost(1.5f) // The maximum darkness value before strange things start to happen // Night vision changes the max from 6.0 to 4.0, we won't // check that for now so we will play safe. val f1 = 4f // The minimum value before the rain stops val f2 = 0.01f // The rain value may not be zero, otherwise will it cause math errors. if (rain < f2 && darkness > 0f) { rain = f2 } if (darkness > 0f) { darkness = (darkness / rain).coerceAtMost(f1 / rain) } output.add(ChangeGameStatePacket(7, rain)) output.add(ChangeGameStatePacket(8, darkness)) } }
mit
80bf27f2340a742b489a9160f2d234d1
37.93617
108
0.697268
4.048673
false
false
false
false
ChrisZhong/organization-model
chazm-model/src/main/kotlin/runtimemodels/chazm/model/parser/entity/ParseCapability.kt
2
1154
package runtimemodels.chazm.model.parser.entity import runtimemodels.chazm.api.entity.CapabilityId import runtimemodels.chazm.api.organization.Organization import runtimemodels.chazm.model.entity.EntityFactory import runtimemodels.chazm.model.entity.impl.DefaultCapabilityId import runtimemodels.chazm.model.parser.attribute import runtimemodels.chazm.model.parser.build import javax.inject.Inject import javax.inject.Singleton import javax.xml.namespace.QName import javax.xml.stream.events.StartElement @Singleton internal class ParseCapability @Inject constructor( private val entityFactory: EntityFactory ) { fun canParse(qName: QName): Boolean = CAPABILITY_ELEMENT == qName.localPart operator fun invoke(element: StartElement, organization: Organization, capabilities: MutableMap<String, CapabilityId>) { val id = DefaultCapabilityId(element attribute NAME_ATTRIBUTE) build(id, capabilities, element, entityFactory::build, organization::add) } companion object { private const val CAPABILITY_ELEMENT = "Capability" //$NON-NLS-1$ private const val NAME_ATTRIBUTE = "name" //$NON-NLS-1$ } }
apache-2.0
5a94df0f4cf0a3f861c6a239408dd475
38.793103
124
0.785962
4.387833
false
false
false
false
Deanveloper/Overcraft
src/main/java/com/deanveloper/overcraft/util/Cooldowns.kt
1
1370
package com.deanveloper.overcraft.util import com.deanveloper.kbukkit.runTaskLater import com.deanveloper.overcraft.Overcraft import com.deanveloper.overcraft.PLUGIN import org.bukkit.entity.Player import org.bukkit.scheduler.BukkitTask import java.util.* /** * @author Dean */ class Cooldowns { private val cooldowns = mutableMapOf<UUID, Pair<BukkitTask, () -> Unit>>() companion object { val DO_NOTHING: () -> Unit = {} } /** * Add a cooldown * * @param p The player to add the cooldown for * @param ticks The length of the cooldown in ticks * @param onRemove What to do when the cooldown expires */ fun addCooldown(p: Player, ticks: Long, onRemove: () -> Unit = DO_NOTHING) = addCooldown(p.uniqueId, ticks, onRemove) fun addCooldown(id: UUID, ticks: Long, onRemove: () -> Unit = DO_NOTHING) { cooldowns[id] = Pair(runTaskLater(PLUGIN, ticks, { remove(id) }), onRemove) } operator fun get(id: UUID) = id in cooldowns operator fun get(p: Player) = get(p.uniqueId) fun isOnCooldown(id: UUID) = get(id) fun isOnCooldown(p: Player) = get(p.uniqueId) fun remove(p: Player) = remove(p.uniqueId) fun remove(id: UUID) { val (task, onRemove) = cooldowns[id] ?: return cooldowns.remove(id) task.cancel() onRemove() } }
mit
333a3da88c3e4847fc4f7c775f298e8d
26.979592
121
0.645255
3.663102
false
false
false
false
RoverPlatform/rover-android
experiences/src/main/kotlin/io/rover/sdk/experiences/ui/RoverViewModel.kt
1
10001
package io.rover.sdk.experiences.ui import android.annotation.SuppressLint import android.graphics.Color import android.os.Parcelable import io.rover.sdk.core.data.NetworkResult import io.rover.sdk.core.data.domain.Experience import io.rover.sdk.core.data.graphql.GraphQlApiServiceInterface import io.rover.sdk.core.data.graphql.operations.FetchExperienceRequest import io.rover.sdk.core.streams.PublishSubject import io.rover.sdk.core.streams.Publishers import io.rover.sdk.core.streams.Scheduler import io.rover.sdk.core.streams.doOnSubscribe import io.rover.sdk.core.streams.flatMap import io.rover.sdk.core.streams.map import io.rover.sdk.core.streams.observeOn import io.rover.sdk.core.streams.share import io.rover.sdk.core.streams.shareAndReplay import io.rover.sdk.core.streams.subscribe import io.rover.sdk.experiences.ui.navigation.ExperienceExternalNavigationEvent import io.rover.sdk.experiences.ui.navigation.NavigationViewModelInterface import io.rover.sdk.experiences.ui.toolbar.ExperienceToolbarViewModelInterface import io.rover.sdk.experiences.ui.toolbar.ToolbarConfiguration import kotlinx.parcelize.Parcelize import org.reactivestreams.Publisher internal class RoverViewModel( private val experienceRequest: ExperienceRequest, private val graphQlApiService: GraphQlApiServiceInterface, private val mainThreadScheduler: Scheduler, private val resolveNavigationViewModel: (experience: Experience, icicle: Parcelable?) -> NavigationViewModelInterface, private val icicle: Parcelable? = null, private val experienceTransformer: ((Experience) -> Experience)? = null ) : RoverViewModelInterface { override val state: Parcelable get() { // this is a slightly strange arrangement: since (almost) all state is really within a // contained view model (that only becomes available synchronously) we effectively // assume we have only our icicle state when that nested view model is not available. return if (currentNavigationViewModel == null) { // getting saved early, starting over. icicle ?: State(null) } else { State( currentNavigationViewModel?.state ) } } override val actionBar: Publisher<ExperienceToolbarViewModelInterface> override val extraBrightBacklight: Publisher<Boolean> override val navigationViewModel: Publisher<NavigationViewModelInterface> override val events: Publisher<RoverViewModelInterface.Event> override val loadingState: Publisher<Boolean> override fun pressBack() { if (currentNavigationViewModel == null) { actionSource.onNext(Action.BackPressedBeforeExperienceReady) } else { currentNavigationViewModel?.pressBack() } } override fun fetchOrRefresh() { actionSource.onNext(Action.Fetch) } private val actionSource = PublishSubject<Action>() private val actions = actionSource.share() private fun fetchExperience(): Publisher<out NetworkResult<Experience>> = graphQlApiService.fetchExperience( when (experienceRequest) { is ExperienceRequest.ByUrl -> FetchExperienceRequest.ExperienceQueryIdentifier.ByUniversalLink( experienceRequest.url ) is ExperienceRequest.ById -> FetchExperienceRequest.ExperienceQueryIdentifier.ById(experienceRequest.experienceId, experienceRequest.useDraft) } ).observeOn(mainThreadScheduler) /** * Hold on to a reference to the navigation view model so that it can contribute to the Android * state restore parcelable. */ private var currentNavigationViewModel: NavigationViewModelInterface? = null init { // maybe for each type fork I should split out and delegate to subjects? val fetchAttempts = PublishSubject<NetworkResult<Experience>>() val toolBarSubject = PublishSubject<ExperienceToolbarViewModelInterface>() val loadingSubject = PublishSubject<Boolean>() val eventsSubject = PublishSubject<RoverViewModelInterface.Event>() actions.subscribe { action -> when (action!!) { Action.BackPressedBeforeExperienceReady -> { eventsSubject.onNext( RoverViewModelInterface.Event.NavigateTo( ExperienceExternalNavigationEvent.Exit() ) ) } Action.Fetch -> { fetchExperience() .doOnSubscribe { loadingSubject.onNext(true) // emit a temporary toolbar. toolBarSubject.onNext( object : ExperienceToolbarViewModelInterface { override val toolbarEvents: Publisher<ExperienceToolbarViewModelInterface.Event> get() = Publishers.empty() override val configuration: ToolbarConfiguration get() = ToolbarConfiguration( true, "", Color.BLUE, Color.BLUE, Color.BLUE, true, false, Color.BLUE ) override fun pressedBack() { actionSource.onNext(Action.BackPressedBeforeExperienceReady) } override fun pressedClose() { actionSource.onNext(Action.BackPressedBeforeExperienceReady) } } ) } .subscribe(fetchAttempts::onNext) } } } val experiences = PublishSubject<Experience>() fetchAttempts.subscribe { networkResult -> loadingSubject.onNext(false) when (networkResult) { is NetworkResult.Error -> { eventsSubject.onNext( RoverViewModelInterface.Event.DisplayError( networkResult.throwable.message ?: "Unknown" ) ) } is NetworkResult.Success -> { experiences.onNext(networkResult.response) } } } // yields an experience navigation view model. used by both our view and some of the // internal subscribers below. navigationViewModel = experiences.map { experience -> val transformedExperience = experienceTransformer?.invoke(experience) ?: experience resolveNavigationViewModel( transformedExperience, // allow it to restore from state if there is any. (state as State).navigationState ).apply { // store a reference to the view model in object scope so it can contribute to the // state parcelable. [email protected] = this } }.shareAndReplay(1) // filter out all the navigation view model events external navigation events. val navigateAwayEvents = navigationViewModel.flatMap { navigationViewModel -> navigationViewModel.externalNavigationEvents } // emit those navigation events to our view. navigateAwayEvents.subscribe { navigateAway -> eventsSubject.onNext( RoverViewModelInterface.Event.NavigateTo(navigateAway) ) } // pass through the backlight and toolbar updates. val backlightEvents = navigationViewModel.flatMap { navigationViewModel -> navigationViewModel.backlight } val toolbarEvents = navigationViewModel.flatMap { navigationViewModel -> navigationViewModel.toolbar } val backlightSubject = PublishSubject<Boolean>() backlightEvents.subscribe { backlightSubject.onNext(it) } toolbarEvents.subscribe { toolBarSubject.onNext(it) } actionBar = toolBarSubject.shareAndReplay(1).observeOn(mainThreadScheduler) extraBrightBacklight = backlightSubject.shareAndReplay(1).observeOn(mainThreadScheduler) loadingState = loadingSubject.shareAndReplay(1).observeOn(mainThreadScheduler) events = eventsSubject.shareAndReplay(0).observeOn(mainThreadScheduler) } enum class Action { /** * Back pressed before the experience navigation view model became available. We can't * deliver the back press event to it as we would normally do; instead we'll handle this * case as an event ourselves and emit an Exit event for it instead. */ BackPressedBeforeExperienceReady, /** * Fetch (or refresh) the displayed experience. */ Fetch } // @Parcelize Kotlin synthetics are generating the CREATOR method for us. @SuppressLint("ParcelCreator") @Parcelize data class State( val navigationState: Parcelable? ) : Parcelable sealed class ExperienceRequest { data class ByUrl(val url: String) : ExperienceRequest() data class ById(val experienceId: String, val useDraft: Boolean = false) : ExperienceRequest() } }
apache-2.0
b4cdbeb92d62a3d9a3ccacbb52701bbd
42.294372
158
0.605339
5.879483
false
false
false
false
Mauin/detekt
detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/complexity/NestedBlockDepthSpec.kt
1
1978
package io.gitlab.arturbosch.detekt.rules.complexity import io.gitlab.arturbosch.detekt.api.ThresholdedCodeSmell import io.gitlab.arturbosch.detekt.rules.Case import io.gitlab.arturbosch.detekt.test.lint import org.assertj.core.api.Assertions.assertThat import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.subject.SubjectSpek import kotlin.test.assertEquals /** * @author Artur Bosch */ class NestedBlockDepthSpec : SubjectSpek<NestedBlockDepth>({ subject { NestedBlockDepth(threshold = 4) } describe("nested classes are also considered") { it("should detect only the nested large class") { subject.lint(Case.NestedClasses.path()) assertEquals(subject.findings.size, 1) assertEquals((subject.findings[0] as ThresholdedCodeSmell).value, 5) } it("should detect too nested block depth") { val code = """ fun f() { if (true) { if (true) { if (true) { if (true) { } } } } }""" assertThat(subject.lint(code)).hasSize(1) } it("should not detect valid nested block depth") { val code = """ fun f() { if (true) { if (true) { if (true) { } } } }""" assertThat(subject.lint(code)).isEmpty() } it("should not count else if as two") { subject.lint(nestedBlockCode) assertThat(subject.findings).isEmpty() } } }) const val nestedBlockCode = """ override fun procedure(node: ASTNode) { val psi = node.psi if (psi.isNotPartOfEnum() && psi.isNotPartOfString()) { if (psi.isDoubleSemicolon()) { addFindings(CodeSmell(id, Entity.from(psi))) withAutoCorrect { deleteOneOrTwoSemicolons(node as LeafPsiElement) } } else if (psi.isSemicolon()) { val nextLeaf = psi.nextLeaf() if (nextLeaf.isSemicolonOrEOF() || nextTokenHasSpaces(nextLeaf)) { addFindings(CodeSmell(id, Entity.from(psi))) withAutoCorrect { psi.delete() } } } } }"""
apache-2.0
4d478a2085a355bef823c7b13b096b9a
24.358974
71
0.662285
3.416235
false
false
false
false
jamieadkins95/Roach
domain/src/main/java/com/jamieadkins/gwent/domain/tracker/AddCardToDeckTrackerUseCase.kt
1
1442
package com.jamieadkins.gwent.domain.tracker import com.jamieadkins.gwent.domain.card.model.GwentCard import com.jamieadkins.gwent.domain.card.model.GwentCardColour import com.jamieadkins.gwent.domain.card.repository.CardRepository import com.jamieadkins.gwent.domain.deck.DeckConstants.BRONZE_MAX import com.jamieadkins.gwent.domain.deck.DeckConstants.GOLD_MAX import io.reactivex.Completable import io.reactivex.Single import io.reactivex.functions.BiFunction import javax.inject.Inject class AddCardToDeckTrackerUseCase @Inject constructor( private val deckTrackerRepository: DeckTrackerRepository, private val cardRepository: CardRepository ) { fun addCard(cardId: String): Completable { return Single.zip( deckTrackerRepository.getCardsPlayed().first(emptyList()), cardRepository.getCard(cardId).firstOrError(), BiFunction { cards: List<GwentCard>, newCard: GwentCard -> val ids = cards.map { it.id } when (newCard.colour) { GwentCardColour.GOLD -> ids.count { it == newCard.id } < GOLD_MAX GwentCardColour.BRONZE -> ids.count { it == newCard.id } < BRONZE_MAX else -> false } } ) .flatMapCompletable { canAdd -> if (canAdd) deckTrackerRepository.trackOpponentCard(cardId) else Completable.complete() } } }
apache-2.0
6ceea6492ce47bf5c351c71aec31e7c8
40.228571
103
0.679612
4.436923
false
false
false
false
SuperAwesomeLTD/sa-mobile-sdk-android
superawesome-common/src/main/java/tv/superawesome/sdk/publisher/common/components/GoogleAdvertisingProxy.kt
1
1865
package tv.superawesome.sdk.publisher.common.components import android.content.Context import android.util.Log import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext interface GoogleAdvertisingProxyType { suspend fun findAdvertisingId(): String? } class GoogleAdvertisingProxy(private val context: Context) : GoogleAdvertisingProxyType { companion object { const val GOOGLE_ADVERTISING_CLASS = "com.google.android.gms.ads.identifier.AdvertisingIdClient" const val GOOGLE_ADVERTISING_ID_CLASS = "com.google.android.gms.ads.identifier.AdvertisingIdClient\$Info" const val GOOGLE_ADVERTISING_INFO_METHOD = "getAdvertisingIdInfo" const val GOOGLE_ADVERTISING_TRACKING_METHOD = "isLimitAdTrackingEnabled" const val GOOGLE_ADVERTISING_ID_METHOD = "getId" } override suspend fun findAdvertisingId(): String? = try { val advertisingIdClass = Class.forName(GOOGLE_ADVERTISING_CLASS) val getAdvertisingIdInfoMethod = advertisingIdClass.getMethod(GOOGLE_ADVERTISING_INFO_METHOD, Context::class.java) val advertisingIdInfoClass = Class.forName(GOOGLE_ADVERTISING_ID_CLASS) val isLimitAdTrackingEnabledMethod = advertisingIdInfoClass.getMethod(GOOGLE_ADVERTISING_TRACKING_METHOD) val getIdMethod = advertisingIdInfoClass.getMethod(GOOGLE_ADVERTISING_ID_METHOD) withContext(Dispatchers.IO) { val adInfo = getAdvertisingIdInfoMethod.invoke(advertisingIdClass, context) val limitAdTracking = isLimitAdTrackingEnabledMethod.invoke(adInfo) as Boolean if (!limitAdTracking) { getIdMethod.invoke(adInfo) as String? } else { null } } } catch (exception: Exception) { Log.i("SuperAwesome", "Google services not available") null } }
lgpl-3.0
1578fed52a91ea7646b5ab2f40129189
42.395349
122
0.727078
4.429929
false
false
false
false
AoEiuV020/PaNovel
api/src/main/java/cc/aoeiuv020/panovel/api/site/yssm.kt
1
2768
package cc.aoeiuv020.panovel.api.site import cc.aoeiuv020.anull.notNull import cc.aoeiuv020.panovel.api.base.DslJsoupNovelContext import cc.aoeiuv020.panovel.api.firstThreeIntPattern import cc.aoeiuv020.panovel.api.firstTwoIntPattern import cc.aoeiuv020.panovel.api.reverseRemoveDuplication import org.jsoup.Jsoup import java.io.ByteArrayOutputStream /** * Created by AoEiuV020 on 2018.05.10-16:48:32. */ class Yssm : DslJsoupNovelContext() {init { reason = "有用户也上不去,看来不是我的网站问题,我这里同一个教育网的电脑能上手机不能上," upkeep = false site { name = "幼狮书盟" baseUrl = "https://www.yssm.tv/" logo = "https://www.yssm.tv//images/logo.png" } search { get { url = "/SearchBook.php" data { "keyword" to it } } // 傻哔吧这网站,一次性返回所有,搜索都市直接出四千多结果,html大于1M, // 这里限制一下,20K大概十几个结果, val max = 20 * 1000 val response = response(call.notNull()) val byteArrayOutputStream = ByteArrayOutputStream(max) response.inputStream { it.copyTo(byteArrayOutputStream, max) } val cutDocument = Jsoup.parse(byteArrayOutputStream.toByteArray().inputStream(), null, response.request().url().toString()) document(cutDocument) { // 由于被截断,可能处理最后一个元素会出异常,无视, itemsIgnoreFailed("#container > div.details.list-type > ul > li") { name("> span.s2 > a") author("> span.s3") } } } bookIdRegex = firstTwoIntPattern // https://www.yssm.org/uctxt/227/227934/ detailPageTemplate = "/uctxt/%s/" detail { document { val div = root.requireElement("#container > div.bookinfo") novel { name("> div > span > h1", parent = div) author("> div > span > em", parent = div, block = pickString("作\\s*者:(\\S*)")) } // 这网站小说没有封面, image = null introduction("> p.intro", parent = div, block = ownLinesString()) update("> p.stats > span.fr > i:nth-child(2)", parent = div, format = "yyyy/MM/dd HH:mm:ss") } } chapters { document { items("#main > div > dl > dd > a") }.reverseRemoveDuplication() } bookIdWithChapterIdRegex = firstThreeIntPattern // https://www.yssm.org/uctxt/227/227934/1301112.html contentPageTemplate = "/uctxt/%s.html" content { document { items("#content") } } } }
gpl-3.0
dbaa30e14ebcc19f51d1c52214827c43
31.675325
131
0.579094
3.553672
false
false
false
false
nickbutcher/plaid
designernews/src/test/java/io/plaidapp/designernews/data/database/ConvertersTest.kt
1
2869
/* * Copyright 2018 Google LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.plaidapp.designernews.data.database import org.junit.Assert.assertEquals import org.junit.Test class ConvertersTest { @Test fun csvToStringArray_oneValue() { // Given a non-empty CSV string with one value val csv = "1" // When the string is converted via the type converter val actualLongList = Converters().csvToLongArray(csv) // Then it should return a list with one element assertEquals(listOf(1L), actualLongList) } @Test fun csvToStringArray_multipleValues() { // Given a non-empty CSV string with multiple values val csv = "1,2,3" // When the string is converted via the type converter val actualLongList = Converters().csvToLongArray(csv) // Then it should return a list of the strings, split by the delimiter assertEquals(listOf(1L, 2L, 3L), actualLongList) } @Test fun csvToStringArray_emptyString() { // Given an empty string val csv = "" // When the string is converted via the type converter val actualLongList = Converters().csvToLongArray(csv) // Then it should return an empty list assertEquals(emptyList<String>(), actualLongList) } @Test fun stringListToCsv_oneValue() { // Given a list with one element val list = listOf(1L) // When the list is converted via the type converter val actualCsv = Converters().longListToCsv(list) // Then it should return a CSV string with one value assertEquals("1", actualCsv) } @Test fun stringListToCsv_multipleValues() { // Given a list with multiple elements val list = listOf(1L, 2L, 3L) // When the list is converted via the type converter val actualCsv = Converters().longListToCsv(list) // Then it should return a CSV string with multiple values assertEquals("1,2,3", actualCsv) } @Test fun stringListToCsv_emptyList() { // Given an empty list val list = emptyList<Long>() // When the list is converted via the type converter val actualCsv = Converters().longListToCsv(list) // Then it should return an empty string assertEquals("", actualCsv) } }
apache-2.0
6cee729720a1ad21e2ee4d21242e8bfb
31.235955
78
0.663994
4.407066
false
true
false
false
vindkaldr/libreplicator
libreplicator-core/src/main/kotlin/org/libreplicator/core/router/DefaultMessageRouter.kt
2
3794
/* * Copyright (C) 2016 Mihály Szabó * * 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 org.libreplicator.core.router import org.libreplicator.api.Observer import org.libreplicator.api.RemoteNode import org.libreplicator.api.Subscription import org.libreplicator.core.client.api.ReplicatorClient import org.libreplicator.core.router.api.MessageRouter import org.libreplicator.core.server.api.ReplicatorServer import org.libreplicator.crypto.api.CipherException import org.libreplicator.json.api.JsonMapper import org.libreplicator.json.api.JsonReadException import org.libreplicator.log.api.warn import org.libreplicator.core.model.ReplicatorMessage import javax.inject.Inject class DefaultMessageRouter @Inject constructor( private val jsonMapper: JsonMapper, private val replicatorClient: ReplicatorClient, private val replicatorServer: ReplicatorServer ) : MessageRouter { private val subscribedObservers = mutableMapOf<String, Observer<ReplicatorMessage>>() private lateinit var serverSubscription: Subscription override fun routeMessage(remoteNode: RemoteNode, message: ReplicatorMessage) { replicatorClient.synchronizeWithNode(remoteNode, jsonMapper.write(message)) } override suspend fun subscribe(scope: String, observer: Observer<ReplicatorMessage>): Subscription { check(isUnsubscribed(scope)) storeObserver(scope, observer) if (isFirstSubscription()) { setUpRouter() } return MessageRouterSubscription(scope, this) } private fun isUnsubscribed(scope: String) = !subscribedObservers.containsKey(scope) private fun storeObserver(scope: String, observer: Observer<ReplicatorMessage>) { subscribedObservers[scope] = observer } private fun isFirstSubscription() = subscribedObservers.size == 1 private suspend fun setUpRouter() { replicatorClient.initialize() serverSubscription = replicatorServer.subscribe(ReplicatorServerObserver(this)) } suspend fun observeMessage(deserializedMessage: String) { try { notifyObserver(deserializedMessage) } catch (e: CipherException) { warn("Failed to deserialize corrupt message!") } catch (e: JsonReadException) { warn("Failed to deserialize invalid message!") } } private suspend fun notifyObserver(deserializedMessage: String) { val message = jsonMapper.read(deserializedMessage, ReplicatorMessage::class) subscribedObservers[message.groupId]?.observe(message) } suspend fun unsubscribe(scope: String) { check(isSubscribed(scope)) removeObserver(scope) if (isLastSubscription()) { tearDownRouter() } } private fun isSubscribed(scope: String) = subscribedObservers.containsKey(scope) private fun removeObserver(scope: String) { subscribedObservers.remove(scope) } private fun isLastSubscription() = subscribedObservers.isEmpty() private suspend fun tearDownRouter() { replicatorClient.close() serverSubscription.unsubscribe() } }
gpl-3.0
e7fae85b7caa64b6fc054723bba6118e
36.176471
104
0.726266
4.745932
false
false
false
false
openHPI/android-app
app/src/main/java/de/xikolo/controllers/dialogs/ProgressDialogHorizontal.kt
1
1572
package de.xikolo.controllers.dialogs import android.app.Dialog import android.os.Bundle import android.view.LayoutInflater import android.widget.ProgressBar import androidx.appcompat.app.AlertDialog import com.yatatsu.autobundle.AutoBundleField import de.xikolo.R import de.xikolo.controllers.dialogs.base.BaseDialogFragment class ProgressDialogHorizontal : BaseDialogFragment() { companion object { @JvmField val TAG: String = ProgressDialogHorizontal::class.java.simpleName } @AutoBundleField(required = false) var title: String? = null @AutoBundleField(required = false) var message: String? = null private var progressBar: ProgressBar? = null var progress: Int = 0 set(value) { progressBar?.progress = value field = value } var max: Int = 1 set(value) { progressBar?.max = value field = value } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val inflater: LayoutInflater = LayoutInflater.from(requireActivity()) progressBar = inflater.inflate(R.layout.dialog_progress_horizontal, null) as ProgressBar progressBar?.max = max progressBar?.progress = progress val builder = AlertDialog.Builder(requireActivity()) .setView(progressBar) .setTitle(title) .setMessage(message) .setCancelable(false) val dialog = builder.create() dialog.setCanceledOnTouchOutside(false) return dialog } }
bsd-3-clause
7aa450af70b08ead4fddf7fcaeadffa0
25.644068
96
0.669847
5.038462
false
false
false
false
lunivore/montecarluni
src/main/kotlin/com/lunivore/montecarluni/app/MontecarluniView.kt
1
6805
package com.lunivore.montecarluni.app import com.lunivore.montecarluni.Events import com.lunivore.montecarluni.model.ClipboardRequest import com.lunivore.montecarluni.model.Distributions import com.lunivore.montecarluni.model.Forecast import com.lunivore.montecarluni.model.ForecastRequest import javafx.beans.property.SimpleBooleanProperty import javafx.beans.property.SimpleObjectProperty import javafx.beans.property.SimpleStringProperty import javafx.collections.FXCollections import javafx.scene.control.TabPane import javafx.scene.control.TableView import org.apache.logging.log4j.LogManager import tornadofx.* import java.time.LocalDate class MontecarluniView : View(){ private val filename = SimpleStringProperty() private val numWorkItemsToForecast = SimpleObjectProperty<Int>() private val forecastStartDate = SimpleObjectProperty<LocalDate>() private val useSelection = SimpleBooleanProperty() private val weeklyDistribution = FXCollections.observableArrayList<WorkItemsDoneInWeekPresenter>() private val cycleTimes = FXCollections.observableArrayList<CycleTimePresenter>() private val forecast = FXCollections.observableArrayList<DataPointPresenter>() private val events : Events by di() private val errorHandler = ErrorHandler() private val logger = LogManager.getLogger() private var weeklyDistributionOutput by singleAssign<TableView<WorkItemsDoneInWeekPresenter>>() private var cycleTimesOutput by singleAssign<TableView<CycleTimePresenter>>() override val root = hbox { title="Montecarluni" borderpane { addClass(Styles.borderBox) top = hbox { addClass(Styles.buttonBox) label("Filename for import:") textfield(filename){ id = "filenameInput"} button("Import"){id = "importButton"}.setOnAction { import() } } center = tabpane { id="distributionTabs" tabClosingPolicy = TabPane.TabClosingPolicy.UNAVAILABLE tab { id="weeklyDistributionTab" text = "Weekly distribution" weeklyDistributionOutput = tableview<WorkItemsDoneInWeekPresenter>(weeklyDistribution) { column("Date range", WorkItemsDoneInWeekPresenter::rangeAsString) { prefWidth = 400.0 } column("# work items closed", WorkItemsDoneInWeekPresenter::count) { prefWidth = 100.0 } id="weeklyDistributionOutput" selectionModel.selectionMode= javafx.scene.control.SelectionMode.MULTIPLE prefHeight=400.0 } } tab { id="cycleTimesTab" text = "Cycle times" cycleTimesOutput = tableview<CycleTimePresenter>(cycleTimes) { id="cycleTimesOutput" column("Id", CycleTimePresenter::id) { prefWidth = 100.0 } column("Date", CycleTimePresenter::date) { prefWidth = 200.0 } column("Gap", CycleTimePresenter::gap) { prefWidth = 200.0 } } } } bottom = vbox { hbox { addClass(Styles.buttonBox) label("Use / copy selection only") checkbox() {id="useSelectionInput"}.bind(useSelection) } hbox { addClass(Styles.buttonBox) button("Copy weeklyDistribution to clipboard") {id="clipboardButton"} .setOnAction { clipboard() } button("Clear") { id="clearButton"}.setOnAction { clearView() } } } } borderpane { addClass(Styles.borderBox) top = gridpane { addClass(Styles.buttonBox) label("Start date (optional)") {gridpaneConstraints {columnRowIndex(0, 0)}} datepicker(forecastStartDate) { id="forecastStartDateInput" gridpaneConstraints {columnRowIndex(1, 0)} } label("Number of work items to complete") {gridpaneConstraints { columnRowIndex(0, 1)}} textfield(numWorkItemsToForecast, IntObjectConverter()) { id="numWorkItemsForecastInput" gridpaneConstraints {columnRowIndex(1, 1)} } button("Run forecast"){ id="forecastButton" gridpaneConstraints { columnRowIndex(2, 1) } }.setOnAction { forecast() } } center=hbox { tableview<DataPointPresenter>(forecast){ column("Probability", DataPointPresenter::probabilityAsPercentageString) { prefWidth = 400.0 } column("Forecast Date", DataPointPresenter::dateAsString) { prefWidth = 100.0 } id="forecastOutput" } } } } init { events.forecastNotification.subscribe({updateForecastOutput(it)}, { errorHandler.handleError(it) }) events.messageNotification.subscribe { errorHandler.handleNotification(it) } events.distributionChangeNotification.subscribe({updateDistributionOutput(it)}, { errorHandler.handleError(it) }) } private fun forecast() { events.forecastRequest.push( ForecastRequest( numWorkItemsToForecast.value, forecastStartDate.value, useSelection.value, weeklyDistributionOutput.selectionModel.selectedIndices)) } private fun clearView() { filename.set("") useSelection.set(false) forecastStartDate.set(null) numWorkItemsToForecast.set(null) events.clearRequest.push(null) } private fun clipboard() { events.clipboardCopyRequest.push( ClipboardRequest(useSelection.value, weeklyDistributionOutput.selectionModel.selectedIndices)) } private fun import() { events.fileImportRequest.push(filename.value) } private fun updateForecastOutput(it: Forecast){ forecast.clear() forecast.addAll(it.dataPoints.map { DataPointPresenter(it) }) } private fun updateDistributionOutput(it: Distributions){ weeklyDistribution.clear() weeklyDistribution.addAll(it.workItemsDone.map { WorkItemsDoneInWeekPresenter(it) }) cycleTimes.clear() cycleTimes.addAll(it.cycleTimes.map { CycleTimePresenter(it)}) } }
apache-2.0
d480343e7c07c7a0c4c2e498afd41cd8
39.505952
114
0.605143
5.457097
false
false
false
false
soywiz/korge
korge/src/commonTest/kotlin/com/soywiz/korge/component/list/GridViewListTest.kt
1
924
package com.soywiz.korge.component.list /* import com.soywiz.korge.tests.* import com.soywiz.korge.view.* import com.soywiz.korim.color.* import com.soywiz.korma.geom.* import kotlin.test.* class GridViewListTest : ViewsForTesting() { @Test fun createGrid() { val rowTemplate = Container().apply { this += SolidRect(10, 10, Colors.RED).apply { xy(0, 0); name = "cell0" } this += SolidRect(10, 10, Colors.RED).apply { xy(20, 0); name = "cell1" } } val row0 = rowTemplate.clone().apply { xy(0, 0); name = "row0" } val row1 = rowTemplate.clone().apply { xy(0, 20); name = "row1" } views.stage.addChild(row0) views.stage.addChild(row1) val gridView = GridViewList(views.stage["row0"].first, views.stage["row1"].first, { it["cell0"].first to it["cell1"].first }, 3, 3) val cell = gridView[2, 2] assertEquals(9, gridView.length) assertEquals(Rectangle(40, 40, 10, 10), cell?.globalBounds) } } */
apache-2.0
075e00711d6e33a8bbd8371ed8e28521
32
119
0.672078
2.860681
false
true
false
false
panpf/sketch
sketch/src/main/java/com/github/panpf/sketch/http/HurlStack.kt
1
9188
/* * Copyright (C) 2022 panpf <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.http import androidx.annotation.WorkerThread import com.github.panpf.sketch.request.ImageRequest import java.io.IOException import java.io.InputStream import java.net.HttpURLConnection import java.net.URL import javax.net.ssl.HttpsURLConnection /** * Use [HttpURLConnection] to request HTTP */ class HurlStack private constructor( /** * Read timeout, in milliseconds */ val readTimeoutMillis: Int = HttpStack.DEFAULT_TIMEOUT, /** * Connection timeout, in milliseconds */ val connectTimeoutMillis: Int = HttpStack.DEFAULT_TIMEOUT, /** * HTTP UserAgent */ val userAgent: String? = null, /** * HTTP header */ val headers: Map<String, String>? = null, /** * Repeatable HTTP headers */ val addHeaders: List<Pair<String, String>>? = null, /** * Callback before executing connection */ val onBeforeConnect: ((url: String, connection: HttpURLConnection) -> Unit)? = null, /** * Enabled tls protocols */ val enabledTlsProtocols: Array<String>? = null ) : HttpStack { @WorkerThread @Throws(IOException::class) override suspend fun getResponse(request: ImageRequest, url: String): HttpStack.Response { var newUri = url while (newUri.isNotEmpty()) { // Currently running on a limited number of IO contexts, so this warning can be ignored @Suppress("BlockingMethodInNonBlockingContext") val connection = (URL(newUri).openConnection() as HttpURLConnection).apply { [email protected] = [email protected] [email protected] = [email protected] doInput = true if ([email protected] != null) { setRequestProperty("User-Agent", [email protected]) } if (addHeaders != null && addHeaders.isNotEmpty()) { for ((key, value) in addHeaders) { addRequestProperty(key, value) } } if (headers != null && headers.isNotEmpty()) { for ((key, value) in headers) { setRequestProperty(key, value) } } request.httpHeaders?.apply { addList.forEach { addRequestProperty(it.first, it.second) } setList.forEach { setRequestProperty(it.first, it.second) } } val enabledTlsProtocols = enabledTlsProtocols if (this is HttpsURLConnection && enabledTlsProtocols?.isNotEmpty() == true) { sslSocketFactory = TlsCompatSocketFactory(enabledTlsProtocols) } } onBeforeConnect?.invoke(url, connection) // Currently running on a limited number of IO contexts, so this warning can be ignored @Suppress("BlockingMethodInNonBlockingContext") connection.connect() val code = connection.responseCode if (code == 301 || code == 302 || code == 307) { newUri = connection.getHeaderField("Location") } else { return HurlResponse(connection) } } throw IOException("Unable to get response") } override fun toString(): String = "HurlStack(connectTimeout=${connectTimeoutMillis},readTimeout=${readTimeoutMillis},userAgent=${userAgent})" override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is HurlStack) return false if (readTimeoutMillis != other.readTimeoutMillis) return false if (connectTimeoutMillis != other.connectTimeoutMillis) return false if (userAgent != other.userAgent) return false if (headers != other.headers) return false if (addHeaders != other.addHeaders) return false if (onBeforeConnect != other.onBeforeConnect) return false return true } override fun hashCode(): Int { var result = readTimeoutMillis result = 31 * result + connectTimeoutMillis result = 31 * result + (userAgent?.hashCode() ?: 0) result = 31 * result + (headers?.hashCode() ?: 0) result = 31 * result + (addHeaders?.hashCode() ?: 0) result = 31 * result + (onBeforeConnect?.hashCode() ?: 0) return result } private class HurlResponse(private val connection: HttpURLConnection) : HttpStack.Response { @get:Throws(IOException::class) override val code: Int by lazy { connection.responseCode } @get:Throws(IOException::class) override val message: String? by lazy { connection.responseMessage } override val contentLength: Long by lazy { connection.getHeaderField("content-length").toLongOrNull() ?: -1 } override val contentType: String? by lazy { connection.contentType } @get:Throws(IOException::class) override val content: InputStream get() = connection.inputStream override fun getHeaderField(name: String): String? { return connection.getHeaderField(name) } } class Builder { private var connectTimeoutMillis: Int = HttpStack.DEFAULT_TIMEOUT private var readTimeoutMillis: Int = HttpStack.DEFAULT_TIMEOUT private var userAgent: String? = null private var extraHeaders: MutableMap<String, String>? = null private var addExtraHeaders: MutableList<Pair<String, String>>? = null private var onBeforeConnect: ((url: String, connection: HttpURLConnection) -> Unit)? = null private var enabledTlsProtocols: List<String>? = null /** * Set connection timeout, in milliseconds */ fun connectTimeoutMillis(connectTimeoutMillis: Int) = apply { this.connectTimeoutMillis = connectTimeoutMillis } /** * Set read timeout, in milliseconds */ fun readTimeoutMillis(readTimeoutMillis: Int): Builder = apply { this.readTimeoutMillis = readTimeoutMillis } /** * Set HTTP UserAgent */ fun userAgent(userAgent: String?): Builder = apply { this.userAgent = userAgent } /** * Set HTTP header */ fun headers(headers: Map<String, String>): Builder = apply { this.extraHeaders = (this.extraHeaders ?: HashMap()).apply { putAll(headers) } } /** * Set HTTP header */ fun headers(vararg headers: Pair<String, String>): Builder = apply { headers(headers.toMap()) } /** * Set repeatable HTTP headers */ fun addHeaders(headers: List<Pair<String, String>>): Builder = apply { this.addExtraHeaders = (this.addExtraHeaders ?: ArrayList()).apply { addAll(headers) } } /** * Set repeatable HTTP headers */ fun addHeaders(vararg headers: Pair<String, String>): Builder = apply { addHeaders(headers.toList()) } /** * Callback before executing connection */ fun onBeforeConnect(block: (url: String, connection: HttpURLConnection) -> Unit): Builder = apply { this.onBeforeConnect = block } /** * Set tls protocols */ fun enabledTlsProtocols(vararg enabledTlsProtocols: String): Builder = apply { this.enabledTlsProtocols = enabledTlsProtocols.toList() } /** * Set tls protocols */ fun enabledTlsProtocols(enabledTlsProtocols: List<String>): Builder = apply { this.enabledTlsProtocols = enabledTlsProtocols.toList() } fun build(): HurlStack = HurlStack( readTimeoutMillis = readTimeoutMillis, connectTimeoutMillis = connectTimeoutMillis, userAgent = userAgent, headers = extraHeaders?.takeIf { it.isNotEmpty() }, addHeaders = addExtraHeaders?.takeIf { it.isNotEmpty() }, onBeforeConnect = onBeforeConnect, enabledTlsProtocols = enabledTlsProtocols?.toTypedArray(), ) } }
apache-2.0
266f1d5a4eeb48a983170d06b4a9ef42
34.072519
115
0.595668
5.132961
false
false
false
false
AndroidX/androidx
compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/tokens/TopAppBarLargeTokens.kt
3
1369
/* * 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. */ // VERSION: v0_103 // GENERATED CODE - DO NOT MODIFY BY HAND package androidx.compose.material3.tokens import androidx.compose.ui.unit.dp internal object TopAppBarLargeTokens { val ContainerColor = ColorSchemeKeyTokens.Surface val ContainerElevation = ElevationTokens.Level0 val ContainerHeight = 152.0.dp val ContainerShape = ShapeKeyTokens.CornerNone val ContainerSurfaceTintLayerColor = ColorSchemeKeyTokens.SurfaceTint val HeadlineColor = ColorSchemeKeyTokens.OnSurface val HeadlineFont = TypographyKeyTokens.HeadlineMedium val LeadingIconColor = ColorSchemeKeyTokens.OnSurface val LeadingIconSize = 24.0.dp val TrailingIconColor = ColorSchemeKeyTokens.OnSurfaceVariant val TrailingIconSize = 24.0.dp }
apache-2.0
428f2770922526bca9d31f024b352211
38.142857
75
0.772096
4.578595
false
false
false
false
mvarnagiris/expensius
firebase/src/test/kotlin/com/mvcoding/expensius/firebase/extensions/FirebaseTransactionExtensions.kt
1
2390
/* * Copyright (C) 2017 Mantas Varnagiris. * * 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. */ package com.mvcoding.expensius.firebase.extensions import com.mvcoding.expensius.firebase.model.FirebaseTransaction import com.mvcoding.expensius.model.TagId import com.mvcoding.expensius.model.TransactionState import com.mvcoding.expensius.model.TransactionType import com.mvcoding.expensius.model.extensions.* fun aFirebaseTransaction() = FirebaseTransaction( id = aStringId(), transactionType = aTransactionType().name, transactionState = aTransactionState().name, timestamp = aLongTimestamp(), timestampInverse = -aLongTimestamp(), amount = anAmount().toPlainString(), currency = aStringCurrencyCode(), tags = listOf(aTagId(), aTagId(), aTagId()).map { it.id }, note = aString("note")) fun FirebaseTransaction.withId(id: String?) = copy(id = id) fun FirebaseTransaction.withTransactionType(transactionType: TransactionType?) = copy(transactionType = transactionType?.name) fun FirebaseTransaction.withTransactionType(transactionType: String) = copy(transactionType = transactionType) fun FirebaseTransaction.withTransactionState(transactionState: TransactionState?) = copy(transactionState = transactionState?.name) fun FirebaseTransaction.withTransactionState(transactionState: String) = copy(transactionState = transactionState) fun FirebaseTransaction.withTimestamp(timestamp: Long?) = copy(timestamp = timestamp) fun FirebaseTransaction.withTimestampInverse(timestampInverse: Long?) = copy(timestampInverse = timestampInverse) fun FirebaseTransaction.withAmount(amount: String?) = copy(amount = amount) fun FirebaseTransaction.withCurrency(currency: String?) = copy(currency = currency) fun FirebaseTransaction.withTagIds(tagIds: Collection<TagId>?) = copy(tags = tagIds?.map { it.id }) fun FirebaseTransaction.withNote(note: String?) = copy(note = note)
gpl-3.0
8387202e5e2e737bc063792713a932fb
53.340909
131
0.775314
4.60501
false
false
false
false
GoSkyer/blog-service
src/main/kotlin/org/goskyer/controller/post/PostController.kt
1
1442
package org.goskyer.controller.post import org.goskyer.controller.auth.BaseController import org.goskyer.domain.BaseResult import org.goskyer.domain.Post import org.goskyer.service.impl.PostServiceImpl import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.web.bind.annotation.* /** * Created by zohar on 2017/4/17. * desc: */ @RestController @RequestMapping("") class PostController : BaseController() { private val logger = LoggerFactory.getLogger(PostController::class.java) @Autowired private lateinit var postService: PostServiceImpl @GetMapping(value = "/post/{postId}") public fun getPostByPostId(@PathVariable("postId") postId: Int): BaseResult<*>? { val post = postService.getPostByPostId(postId) logger.info(post.toString()) return BaseResult.build("获取博客成功", post) } @GetMapping(value = "/posts/{userId}") public fun getPostByUserId(@PathVariable("userId") userId: Int): BaseResult<*>? { val posts = postService.getPostsByUserId(userId) logger.info(posts.toString()) return BaseResult.build("获取用户博客列表成功", posts) } @PostMapping(value = "/post") fun post(@ModelAttribute post: Post): BaseResult<*>? { logger.info(post.toString()) postService.addPost(post) return BaseResult.build("发表成功",0) } }
mit
13b6ebb30cd6ed5dd9171a6de40687b9
27.06
85
0.708987
4.21021
false
false
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/models/social/InboxConversation.kt
2
937
package com.habitrpg.android.habitica.models.social import com.habitrpg.android.habitica.models.BaseObject import com.habitrpg.android.habitica.models.user.ContributorInfo import io.realm.RealmObject import io.realm.annotations.PrimaryKey import java.util.Date open class InboxConversation : RealmObject(), BaseObject { @PrimaryKey var combinedID: String = "" var uuid: String = "" set(value) { field = value combinedID = userID + value } var userID: String = "" set(value) { field = value combinedID = value + uuid } var username: String? = null var user: String? = null var timestamp: Date? = null var contributor: ContributorInfo? = null var userStyles: UserStyles? = null var text: String? = null val formattedUsername: String? get() = if (username?.isNotEmpty() == true) "@$username" else null }
gpl-3.0
f7ac7959c3f0c4ccdce477f1f7979672
28.28125
74
0.651014
4.298165
false
false
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/AchievementsFragment.kt
1
7779
package com.habitrpg.android.habitica.ui.fragments import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.appcompat.widget.Toolbar import androidx.core.content.ContextCompat import androidx.recyclerview.widget.GridLayoutManager import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.data.InventoryRepository import com.habitrpg.android.habitica.databinding.FragmentRefreshRecyclerviewBinding import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.ui.adapter.AchievementsAdapter import com.habitrpg.android.habitica.ui.helpers.ToolbarColorHelper import com.habitrpg.android.habitica.ui.viewmodels.MainUserViewModel import io.reactivex.rxjava3.kotlin.Flowables import io.reactivex.rxjava3.kotlin.combineLatest import javax.inject.Inject class AchievementsFragment : BaseMainFragment<FragmentRefreshRecyclerviewBinding>(), SwipeRefreshLayout.OnRefreshListener { @Inject lateinit var inventoryRepository: InventoryRepository @Inject lateinit var userViewModel: MainUserViewModel override var binding: FragmentRefreshRecyclerviewBinding? = null override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentRefreshRecyclerviewBinding { return FragmentRefreshRecyclerviewBinding.inflate(inflater, container, false) } private var menuID: Int = 0 private lateinit var adapter: AchievementsAdapter private var useGridLayout = false set(value) { field = value adapter.useGridLayout = value adapter.notifyDataSetChanged() } override fun injectFragment(component: UserComponent) { component.inject(this) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { hidesToolbar = true adapter = AchievementsAdapter() onRefresh() return super.onCreateView(inflater, container, savedInstanceState) } override fun onViewStateRestored(savedInstanceState: Bundle?) { super.onViewStateRestored(savedInstanceState) useGridLayout = savedInstanceState?.getBoolean("useGridLayout") ?: false } override fun onSaveInstanceState(outState: Bundle) { outState.putBoolean("useGridLayout", useGridLayout) super.onSaveInstanceState(outState) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val layoutManager = GridLayoutManager(activity, 2) binding?.recyclerView?.layoutManager = layoutManager binding?.recyclerView?.adapter = adapter adapter.useGridLayout = useGridLayout context?.let { binding?.recyclerView?.background = ColorDrawable(ContextCompat.getColor(it, R.color.content_background)) } layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() { override fun getSpanSize(position: Int): Int { return if (adapter.getItemViewType(position) == 1) { 1 } else { 2 } } } binding?.refreshLayout?.setOnRefreshListener(this) compositeSubscription.add( userRepository.getAchievements().map { achievements -> achievements.sortedBy { if (it.category == "onboarding") { it.index } else { (it.category?.first()?.toInt() ?: 2) * it.index } } }.combineLatest( Flowables.combineLatest( userRepository.getQuestAchievements(), userRepository.getQuestAchievements() .map { it.mapNotNull { achievement -> achievement.questKey } } .flatMap { inventoryRepository.getQuestContent(it) } ) ).subscribe( { val achievements = it.first val entries = mutableListOf<Any>() var lastCategory = "" achievements.forEach { achievement -> val categoryIdentifier = achievement.category ?: "" if (categoryIdentifier != lastCategory) { val category = Pair( categoryIdentifier, achievements.count { check -> check.category == categoryIdentifier && check.earned } ) entries.add(category) lastCategory = categoryIdentifier } entries.add(achievement) } val questAchievements = it.second entries.add(Pair("Quests completed", questAchievements.first.size)) entries.addAll( questAchievements.first.map { achievement -> val questContent = questAchievements.second.firstOrNull { achievement.questKey == it.key } achievement.title = questContent?.text achievement } ) val user = userViewModel.user.value val challengeAchievementCount = user?.challengeAchievements?.size ?: 0 if (challengeAchievementCount > 0) { entries.add(Pair("Challenges won", challengeAchievementCount)) user?.challengeAchievements?.let { it1 -> entries.addAll(it1) } } adapter.entries = entries adapter.notifyDataSetChanged() }, RxErrorHandler.handleEmptyError() ) ) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { if (useGridLayout) { val menuItem = menu.add(R.string.switch_to_list_view) menuID = menuItem?.itemId ?: 0 menuItem?.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS) menuItem?.setIcon(R.drawable.ic_round_view_list_24px) tintMenuIcon(menuItem) } else { val menuItem = menu.add(R.string.switch_to_grid_view) menuID = menuItem?.itemId ?: 0 menuItem?.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS) menuItem?.setIcon(R.drawable.ic_round_view_module_24px) tintMenuIcon(menuItem) } activity?.findViewById<Toolbar>(R.id.toolbar)?.let { ToolbarColorHelper.colorizeToolbar(it, activity, null) } super.onCreateOptionsMenu(menu, inflater) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == menuID) { useGridLayout = !useGridLayout activity?.invalidateOptionsMenu() } return super.onOptionsItemSelected(item) } override fun onRefresh() { compositeSubscription.add( userRepository.retrieveAchievements().subscribe( { }, RxErrorHandler.handleEmptyError(), { binding?.refreshLayout?.isRefreshing = false } ) ) } }
gpl-3.0
44d80143f5bda87e9c98737bec920e7a
40.37766
130
0.611261
5.796572
false
false
false
false
androidx/androidx
compose/foundation/foundation/src/androidAndroidTest/kotlin/androidx/compose/foundation/text/DrawPhaseAttributesToggleTest.kt
3
8768
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.text import android.os.Build import androidx.compose.foundation.text.matchers.assertThat import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shadow import androidx.compose.ui.graphics.asAndroidBitmap import androidx.compose.ui.graphics.drawscope.Fill import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.captureToImage import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.text.ExperimentalTextApi import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.style.TextDecoration import androidx.test.filters.MediumTest import androidx.test.filters.SdkSuppress import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @RunWith(Parameterized::class) @SdkSuppress(minSdkVersion = Build.VERSION_CODES.O) @MediumTest class DrawPhaseAttributesToggleTest(private val config: Config) { private val textTag = "text" class Config( private val description: String, val updateStyle: (TextStyle) -> TextStyle, val initializeStyle: (TextStyle) -> TextStyle = { it } ) { override fun toString(): String = "toggling $description" } @OptIn(ExperimentalTextApi::class) companion object { @Parameterized.Parameters(name = "{0}") @JvmStatic fun parameters() = arrayOf( Config( "color unspecified/color/unspecified", initializeStyle = { it.copy(color = Color.Unspecified) }, updateStyle = { it.copy(color = Color.Blue) }, ), Config( "color colorA/colorB/colorA", initializeStyle = { it.copy(color = Color.Black) }, updateStyle = { it.copy(color = Color.Blue) }, ), Config( "color colorA/brushA/colorA", initializeStyle = { it.copy(color = Color.Red) }, updateStyle = { it.copy(brush = Brush.verticalGradient(listOf(Color.Blue, Color.Magenta))) } ), Config( "brush brushA/brushB/brushA", initializeStyle = { it.copy(brush = Brush.horizontalGradient(listOf(Color.Black, Color.Blue))) }, updateStyle = { it.copy(brush = Brush.verticalGradient(listOf(Color.Red, Color.Blue))) } ), Config( "brush brushA/colorA/brushA", initializeStyle = { it.copy(brush = Brush.horizontalGradient(listOf(Color.Black, Color.Blue))) }, updateStyle = { it.copy(color = Color.Red) } ), Config( "alpha", initializeStyle = { it.copy( alpha = 1f, brush = Brush.verticalGradient(0f to Color.Blue, 1f to Color.Magenta) ) }, updateStyle = { it.copy(alpha = 0.5f, brush = it.brush) }, ), Config( "textDecoration none/lineThrough/none", initializeStyle = { it.copy(textDecoration = TextDecoration.None) }, updateStyle = { it.copy(textDecoration = TextDecoration.LineThrough) } ), Config( "textDecoration lineThrough/none/lineThrough", initializeStyle = { it.copy(textDecoration = TextDecoration.LineThrough) }, updateStyle = { it.copy(textDecoration = TextDecoration.None) } ), Config( "textDecoration null/lineThrough/null", initializeStyle = { it.copy(textDecoration = null) }, updateStyle = { it.copy(textDecoration = TextDecoration.LineThrough) } ), Config( "shadow null/shadow/null", initializeStyle = { it.copy(shadow = null) }, updateStyle = { it.copy(shadow = Shadow(Color.Black, blurRadius = 4f)) } ), Config( "shadow shadowA/shadowB/shadowA", initializeStyle = { it.copy(shadow = Shadow(Color.Black, blurRadius = 1f)) }, updateStyle = { it.copy(shadow = Shadow(Color.Black, blurRadius = 4f)) } ), Config( "shadow shadowA/null/shadowA", initializeStyle = { it.copy(shadow = Shadow(Color.Black, blurRadius = 1f)) }, updateStyle = { it.copy(shadow = null) } ), Config( "drawStyle null/drawStyle/null", initializeStyle = { it.copy(drawStyle = null) }, updateStyle = { it.copy(drawStyle = Stroke(width = 2f)) } ), Config( "drawStyle drawStyleA/drawStyleB/drawStyleA", initializeStyle = { it.copy(drawStyle = Stroke(width = 1f)) }, updateStyle = { it.copy(drawStyle = Stroke(width = 2f)) } ), Config( "drawStyle drawStyle/null/drawStyle", initializeStyle = { it.copy(drawStyle = Stroke(width = 1f)) }, updateStyle = { it.copy(drawStyle = null) } ), Config( "drawStyle stroke/fill/stroke", initializeStyle = { it.copy(drawStyle = Stroke(width = 1f)) }, updateStyle = { it.copy(drawStyle = Fill) } ) ) } @get:Rule val rule = createComposeRule() @Test fun basicText() { var style by mutableStateOf( TextStyle( color = Color.Black, textDecoration = null, shadow = null ).let(config.initializeStyle) ) rule.setContent { BasicText( "ABC", style = style, modifier = Modifier.testTag(textTag) ) } rule.waitForIdle() val initialBitmap = rule.onNodeWithTag(textTag).captureToImage().asAndroidBitmap() style = config.updateStyle(style) rule.waitForIdle() val updatedBitmap = rule.onNodeWithTag(textTag).captureToImage().asAndroidBitmap() assertThat(initialBitmap).isNotEqualToBitmap(updatedBitmap) style = config.initializeStyle(style) rule.waitForIdle() val finalBitmap = rule.onNodeWithTag(textTag).captureToImage().asAndroidBitmap() assertThat(finalBitmap).isNotEqualToBitmap(updatedBitmap) assertThat(finalBitmap).isEqualToBitmap(initialBitmap) } @Test fun basicTextField() { var style by mutableStateOf(config.initializeStyle(TextStyle(color = Color.Black))) rule.setContent { BasicTextField( "ABC", onValueChange = {}, textStyle = style, modifier = Modifier.testTag(textTag) ) } rule.waitForIdle() val initialBitmap = rule.onNodeWithTag(textTag).captureToImage().asAndroidBitmap() style = config.updateStyle(style) rule.waitForIdle() val updatedBitmap = rule.onNodeWithTag(textTag).captureToImage().asAndroidBitmap() assertThat(initialBitmap).isNotEqualToBitmap(updatedBitmap) style = config.initializeStyle(style) rule.waitForIdle() val finalBitmap = rule.onNodeWithTag(textTag).captureToImage().asAndroidBitmap() assertThat(finalBitmap).isNotEqualToBitmap(updatedBitmap) assertThat(finalBitmap).isEqualToBitmap(initialBitmap) } }
apache-2.0
d7c20dbdfdfdcbfab1b3235742a9e2a8
36.474359
94
0.58839
4.742023
false
true
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/platform/mixin/inspection/shadow/ShadowFinalInspection.kt
1
1817
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.inspection.shadow import com.demonwav.mcdev.platform.mixin.inspection.MixinInspection import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.FINAL import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.MUTABLE import com.intellij.codeInsight.intention.AddAnnotationFix import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.JavaElementVisitor import com.intellij.psi.PsiAssignmentExpression import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiModifierListOwner import com.intellij.psi.PsiReferenceExpression class ShadowFinalInspection : MixinInspection() { override fun getStaticDescription() = "@Final annotated fields cannot be modified, as the field it is targeting is final. " + "This can be overridden with @Mutable." override fun buildVisitor(holder: ProblemsHolder): PsiElementVisitor = Visitor(holder) private class Visitor(private val holder: ProblemsHolder) : JavaElementVisitor() { override fun visitAssignmentExpression(expression: PsiAssignmentExpression) { val left = expression.lExpression as? PsiReferenceExpression ?: return val resolved = left.resolve() as? PsiModifierListOwner ?: return val modifiers = resolved.modifierList ?: return if (modifiers.findAnnotation(FINAL) != null && modifiers.findAnnotation(MUTABLE) == null) { holder.registerProblem( expression, "@Final fields cannot be modified", AddAnnotationFix(MUTABLE, resolved) ) } } } }
mit
6194181d939a2fa8036ffb9ad97fc241
36.854167
103
0.720418
5.132768
false
false
false
false
robohorse/RoboPOJOGenerator
generator/src/main/kotlin/com/robohorse/robopojogenerator/postrocessing/common/KotlinDataClassPostProcessor.kt
1
4949
package com.robohorse.robopojogenerator.postrocessing.common import com.robohorse.robopojogenerator.models.FieldModel import com.robohorse.robopojogenerator.models.FrameworkVW.FastJson import com.robohorse.robopojogenerator.models.FrameworkVW.Gson import com.robohorse.robopojogenerator.models.FrameworkVW.Jackson import com.robohorse.robopojogenerator.models.FrameworkVW.LoganSquare import com.robohorse.robopojogenerator.models.FrameworkVW.Moshi import com.robohorse.robopojogenerator.models.GenerationModel import com.robohorse.robopojogenerator.postrocessing.BasePostProcessor import com.robohorse.robopojogenerator.postrocessing.utils.MoshiAnnotationsProcessor import com.robohorse.robopojogenerator.properties.ClassItem import com.robohorse.robopojogenerator.properties.annotations.KotlinAnnotations import com.robohorse.robopojogenerator.properties.templates.ClassTemplate import com.robohorse.robopojogenerator.properties.templates.ImportsTemplate import com.robohorse.robopojogenerator.properties.templates.PARCELABLE_ANDROID import com.robohorse.robopojogenerator.properties.templates.PARCELIZE_KOTLINX import com.robohorse.robopojogenerator.utils.ClassGenerateHelper import com.robohorse.robopojogenerator.utils.ClassTemplateHelper internal class KotlinDataClassPostProcessor( generateHelper: ClassGenerateHelper, classTemplateHelper: ClassTemplateHelper, private val moshiAnnotationsProcessor: MoshiAnnotationsProcessor ) : BasePostProcessor(generateHelper, classTemplateHelper) { override fun proceedClassImports( imports: HashSet<String>, generationModel: GenerationModel ): StringBuilder { imports.remove(ImportsTemplate.LIST) if (generationModel.useKotlinParcelable) { imports.add(PARCELABLE_ANDROID) imports.add(PARCELIZE_KOTLINX) } val importsBuilder = StringBuilder() for (importItem in imports) { importsBuilder.append(importItem.replace(";", "")) importsBuilder.append(ClassTemplate.NEW_LINE) } return importsBuilder } override fun proceedClassBody( classItem: ClassItem, generationModel: GenerationModel ): String { val classBodyBuilder = StringBuilder() val classFields = classItem.classFields for (objectName in classFields.keys) { classBodyBuilder.append( classTemplateHelper.createKotlinDataClassField( generationModel, FieldModel( classType = classFields[objectName]?.getKotlinItem(), annotation = classItem.annotation, fieldName = objectName, fieldNameFormatted = generateHelper.formatClassField(objectName) ) ) ) } generateHelper.updateClassModel(classBodyBuilder) return classBodyBuilder.toString() } override fun createClassItemText( packagePath: String?, imports: String?, classTemplate: String? ) = classTemplateHelper .createClassItemWithoutSemicolon( packagePath, imports, classTemplate ) override fun applyAnnotations( generationModel: GenerationModel, classItem: ClassItem ) = when (generationModel.annotationEnum) { is Gson -> { generateHelper.setAnnotations( classItem, KotlinAnnotations.GSON.classAnnotation, KotlinAnnotations.GSON.annotation, ImportsTemplate.GSON.imports ) } is LoganSquare -> { generateHelper.setAnnotations( classItem, KotlinAnnotations.LOGAN_SQUARE.classAnnotation, KotlinAnnotations.LOGAN_SQUARE.annotation, ImportsTemplate.LOGAN_SQUARE.imports ) } is Jackson -> { generateHelper.setAnnotations( classItem, KotlinAnnotations.JACKSON.classAnnotation, KotlinAnnotations.JACKSON.annotation, ImportsTemplate.JACKSON.imports ) } is FastJson -> { generateHelper.setAnnotations( classItem, KotlinAnnotations.FAST_JSON.classAnnotation, KotlinAnnotations.FAST_JSON.annotation, ImportsTemplate.FAST_JSON.imports ) } is Moshi -> moshiAnnotationsProcessor.applyAnnotations(generationModel, classItem) else -> { // NO OP } } override fun createClassTemplate( classItem: ClassItem, classBody: String?, generationModel: GenerationModel ) = classTemplateHelper.createClassBodyKotlinDataClass( classItem, classBody, generationModel ) }
mit
063966be71aa589d3cad52e257ee82a7
35.932836
90
0.671651
5.708189
false
false
false
false
kilel/jotter
snt-dao-starter/src/main/kotlin/org/github/snt/dao/api/entity/NoteSource.kt
1
1227
/* * Copyright 2018 Kislitsyn Ilya * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.github.snt.dao.api.entity import javax.persistence.* /** * Root note for user. */ @Entity @Table(name = "SN_NOTE_SRC") class NoteSource() : AbstractEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column override var id: Long? = null @ManyToOne @JoinColumn(name = "userId") lateinit var user: User @OneToOne @JoinColumn(name = "noteId") lateinit var note: Note @Column(name = "dscr") var description = "Auto-generated note's source" constructor(user: User, note: Note) : this() { this.user = user this.note = note } }
apache-2.0
be4ced42eff1bbc755196e5e832af196
24.061224
75
0.682967
3.907643
false
false
false
false
sebastiansokolowski/AuctionHunter---Allegro
android-app/app/src/main/java/com/sebastian/sokolowski/auctionhunter/rest/AllegroAuthClient.kt
1
2069
package com.sebastian.sokolowski.auctionhunter.rest import android.content.Context import android.util.Base64 import com.sebastian.sokolowski.auctionhunter.BuildConfig import com.sebastian.sokolowski.auctionhunter.rest.response.AuthResponse import com.sebastian.sokolowski.auctionhunter.rest.response.RefreshTokenResponse import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Call import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class AllegroAuthClient(val context: Context) { private lateinit var allegroAuthService: AllegroAuthService fun auth(): Call<AuthResponse> { val allegroAuthService = getAllegroAuthService() return allegroAuthService.auth(getAuthorizationHeader(), "client_credentials") } fun refresh(token: String): Call<RefreshTokenResponse> { val allegroAuthService = getAllegroAuthService() return allegroAuthService.refreshToken(getAuthorizationHeader(), "refresh_token", token) } private fun getAuthorizationHeader(): String { val credential: String = BuildConfig.CLIENT_ID + ":" + BuildConfig.CLIENT_SECRET return "Basic " + Base64.encodeToString(credential.toByteArray(), Base64.NO_WRAP) } private fun getAllegroAuthService(): AllegroAuthService { if (!::allegroAuthService.isInitialized) { val retrofit = Retrofit.Builder() .baseUrl(AllegroAuthService.baseUrl) .addConverterFactory(GsonConverterFactory.create()) .client(getOkHttpClient()) .build() allegroAuthService = retrofit.create(AllegroAuthService::class.java) } return allegroAuthService } private fun getOkHttpClient(): OkHttpClient { val httpLoggingInterceptor = HttpLoggingInterceptor() httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.NONE return OkHttpClient.Builder() .addInterceptor(httpLoggingInterceptor) .build() } }
apache-2.0
d61574cc39cdf54487f65dbece02cf8d
37.333333
96
0.722571
4.868235
false
true
false
false
Polidea/RxAndroidBle
sample-kotlin/src/main/kotlin/com/polidea/rxandroidble2/samplekotlin/util/LocationPermission.kt
1
926
package com.polidea.rxandroidble2.samplekotlin.util import android.app.Activity import android.content.pm.PackageManager import androidx.core.app.ActivityCompat import com.polidea.rxandroidble2.RxBleClient private const val REQUEST_PERMISSION_BLE_SCAN = 101 internal fun Activity.requestLocationPermission(client: RxBleClient) = ActivityCompat.requestPermissions( this, /* * the below would cause a ArrayIndexOutOfBoundsException on API < 23. Yet it should not be called then as runtime * permissions are not needed and RxBleClient.isScanRuntimePermissionGranted() returns `true` */ arrayOf(client.recommendedScanRuntimePermissions[0]), REQUEST_PERMISSION_BLE_SCAN ) internal fun isLocationPermissionGranted(requestCode: Int, grantResults: IntArray) = requestCode == REQUEST_PERMISSION_BLE_SCAN && grantResults[0] == PackageManager.PERMISSION_GRANTED
apache-2.0
130e45e59cfe125b4bae10f46a64a658
41.090909
122
0.767819
4.822917
false
false
false
false
HabitRPG/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/shops/PurchaseDialogContent.kt
1
1696
package com.habitrpg.android.habitica.ui.views.shops import android.content.Context import android.util.AttributeSet import android.view.Gravity import android.widget.LinearLayout import android.widget.TextView import com.habitrpg.android.habitica.extensions.fromHtml import com.habitrpg.android.habitica.models.inventory.QuestContent import com.habitrpg.android.habitica.models.shops.ShopItem import com.habitrpg.common.habitica.extensions.dpToPx import com.habitrpg.common.habitica.extensions.loadGif import com.habitrpg.common.habitica.extensions.loadImage import com.habitrpg.common.habitica.views.PixelArtView abstract class PurchaseDialogContent @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : LinearLayout(context, attrs, defStyleAttr) { abstract val imageView: PixelArtView abstract val titleTextView: TextView init { orientation = VERTICAL gravity = Gravity.CENTER } open fun setItem(item: ShopItem) { if (item.path?.contains("timeTravelBackgrounds") == true) { imageView.loadGif(item.imageName?.replace("icon_", "")) val params = imageView.layoutParams params.height = 147.dpToPx(context) params.width = 140.dpToPx(context) imageView.layoutParams = params } else { imageView.loadImage(item.imageName) } titleTextView.text = item.text } open fun setQuestContentItem(questContent: QuestContent) { imageView.loadImage("inventory_quest_scroll_" + questContent.key) titleTextView.setText(questContent.text.fromHtml(), TextView.BufferType.SPANNABLE) } }
gpl-3.0
9e18fb58fa0972f65ff391179e635b91
35.085106
90
0.732311
4.571429
false
false
false
false
jiaminglu/kotlin-native
backend.native/tests/codegen/innerClass/qualifiedThis.kt
1
994
open class ABase { open fun zzz() = "a_base" } open class BBase { open fun zzz() = "b_base" } class D() { val z = "d" } class A: ABase() { // implicit label @A val z = "a" override fun zzz() = "a" inner class B: BBase() { // implicit label @B val z = "b" override fun zzz() = "b" fun D.foo() : String { // implicit label @foo if([email protected] != "a") return "Fail1" if([email protected] != "b") return "Fail2" if([email protected]() != "a_base") return "Fail3" if(super<BBase>.zzz() != "b_base") return "Fail4" if([email protected]() != "b_base") return "Fail5" if([email protected]() != "a") return "Fail6" if([email protected]() != "b") return "Fail7" if(this.z != "d") return "Fail8" return "OK" } fun bar(d: D): String { return d.foo() } } } fun box() = A().B().bar(D()) fun main(args : Array<String>) { println(box()) }
apache-2.0
65bc90e1477855e50b57dee392807812
20.608696
61
0.459759
2.940828
false
false
false
false
garmax1/material-flashlight
app/src/main/java/co/garmax/materialflashlight/widget/WidgetProviderButton.kt
1
3561
package co.garmax.materialflashlight.widget import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.Canvas import android.os.Build import android.widget.RemoteViews import androidx.core.content.ContextCompat import androidx.core.graphics.drawable.DrawableCompat import co.garmax.materialflashlight.R import co.garmax.materialflashlight.features.LightManager import org.koin.core.component.KoinComponent import org.koin.core.component.inject class WidgetProviderButton : AppWidgetProvider(), KoinComponent { private val lightManager: LightManager by inject() private val widgetManager: WidgetManager by inject() override fun onUpdate( context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray ) { super.onUpdate(context, appWidgetManager, appWidgetIds) // Perform this loop procedure for each App Widget that belongs to this provider for (appWidgetId in appWidgetIds) { val views = RemoteViews(context.packageName, R.layout.view_widget_button) // Set on intent to handle onclick views.setOnClickPendingIntent(R.id.button_widget, getPendingSelfIntent(context)) // Set image according to current state if (lightManager.isTurnedOn) { setWidgetImage(context, views, R.id.button_widget, R.drawable.ic_widget_button_on) } else { setWidgetImage(context, views, R.id.button_widget, R.drawable.ic_widget_button_off) } // Tell the AppWidgetManager to perform an update on the current app widget appWidgetManager.updateAppWidget(appWidgetId, views) } } override fun onReceive(context: Context, intent: Intent) { super.onReceive(context, intent) if (ACTION_WIDGET_BUTTON_CLICK == intent.getAction()) { if (lightManager.isTurnedOn) lightManager.turnOff() else lightManager.turnOn() widgetManager.updateWidgets() } } private fun getPendingSelfIntent(context: Context): PendingIntent { // An explicit intent directed at the current class (the "self"). val intent = Intent(context, javaClass).apply { action = ACTION_WIDGET_BUTTON_CLICK } return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_MUTABLE) } private fun setWidgetImage( context: Context, remoteViews: RemoteViews, viewRes: Int, imageRes: Int ) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { remoteViews.setImageViewResource(viewRes, imageRes) } else { ContextCompat.getDrawable(context, imageRes)?.let { val drawable = DrawableCompat.wrap(it).mutate() val bitmap = Bitmap.createBitmap( drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888 ) val canvas = Canvas(bitmap) drawable.setBounds(0, 0, canvas.width, canvas.height) drawable.draw(canvas) remoteViews.setImageViewBitmap(viewRes, bitmap) } } } companion object { const val ACTION_WIDGET_BUTTON_CLICK = "co.garmax.materialflashlight.action.WIDGET_BUTTON_CLICK" } }
apache-2.0
afb9be916ba114b61f25802cf2ba48bc
35.346939
99
0.666947
4.904959
false
false
false
false
da1z/intellij-community
platform/external-system-impl/src/com/intellij/openapi/externalSystem/configurationStore/PersistentMapManager.kt
1
3028
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.configurationStore import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.externalSystem.service.project.manage.ExternalProjectsDataStorage import com.intellij.openapi.project.Project import com.intellij.openapi.util.JDOMUtil import com.intellij.util.io.* import com.intellij.util.loadElement import com.intellij.util.write import org.jdom.Element import java.nio.file.Path private val LOG = logger<FileSystemExternalSystemStorage>() internal interface ExternalSystemStorage { val isDirty: Boolean fun remove(name: String) fun read(name: String): Element? fun write(name: String, element: Element?, filter: JDOMUtil.ElementOutputFilter? = null) fun forceSave() fun rename(oldName: String, newName: String) } internal class ModuleFileSystemExternalSystemStorage(project: Project) : FileSystemExternalSystemStorage("modules", project) { companion object { private fun nameToFilename(name: String) = "${sanitizeFileName(name)}.xml" } override fun nameToPath(name: String) = super.nameToPath(nameToFilename(name)) } internal class ProjectFileSystemExternalSystemStorage(project: Project) : FileSystemExternalSystemStorage("project", project) internal abstract class FileSystemExternalSystemStorage(dirName: String, project: Project) : ExternalSystemStorage { override val isDirty = false protected val dir: Path = ExternalProjectsDataStorage.getProjectConfigurationDir(project).resolve(dirName) var hasSomeData: Boolean private set init { val fileAttributes = dir.basicAttributesIfExists() hasSomeData = when { fileAttributes == null -> false fileAttributes.isRegularFile -> { // old binary format dir.parent.deleteChildrenStartingWith(dir.fileName.toString()) false } else -> { LOG.assertTrue(fileAttributes.isDirectory) true } } } protected open fun nameToPath(name: String): Path = dir.resolve(name) override fun forceSave() { } override fun remove(name: String) { if (!hasSomeData) { return } nameToPath(name).delete() } override fun read(name: String): Element? { if (!hasSomeData) { return null } val element: Element? = nameToPath(name).inputStreamIfExists()?.use { loadElement(it) } return if (element == null) null else JDOMUtil.internElement(element) } override fun write(name: String, element: Element?, filter: JDOMUtil.ElementOutputFilter?) { if (element == null) { remove(name) return } hasSomeData = true element.write(nameToPath(name), filter = filter) } override fun rename(oldName: String, newName: String) { if (!hasSomeData) { return } val oldFile = nameToPath(oldName) if (oldFile.exists()) { oldFile.move(nameToPath(newName)) } } }
apache-2.0
d91aaa4ffdf8fcbf2714eb8ade179fd4
27.046296
140
0.722259
4.439883
false
false
false
false
Heiner1/AndroidAPS
wear/src/main/java/info/nightscout/androidaps/interaction/utils/EditPlusMinusViewAdapter.kt
1
5133
package info.nightscout.androidaps.interaction.utils import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import info.nightscout.androidaps.R import info.nightscout.androidaps.databinding.ActionEditplusminBinding import info.nightscout.androidaps.databinding.ActionEditplusminMultiBinding import info.nightscout.androidaps.databinding.ActionEditplusminQuickleftyMultiBinding import info.nightscout.androidaps.databinding.ActionEditplusminQuickleftyBinding import info.nightscout.androidaps.databinding.ActionEditplusminQuickrightyBinding import info.nightscout.androidaps.databinding.ActionEditplusminQuickrightyMultiBinding import info.nightscout.androidaps.databinding.ActionEditplusminViktoriaBinding import info.nightscout.shared.sharedPreferences.SP /** * EditPlusMinusViewAdapter binds both ActionEditplusminBinding variants shared attributes to one common view adapter. * Requires at least one of the ViewBinding as a parameter. Recommended to use the factory object to create the binding. */ class EditPlusMinusViewAdapter( eD: ActionEditplusminBinding?, eDP: ActionEditplusminMultiBinding?, eQL: ActionEditplusminQuickleftyBinding?, eQLP: ActionEditplusminQuickleftyMultiBinding?, eQR: ActionEditplusminQuickrightyBinding?, eQRP: ActionEditplusminQuickrightyMultiBinding?, eV: ActionEditplusminViktoriaBinding? ) { init { if (eD == null && eDP == null && eQL == null && eQLP == null && eQR == null && eQRP == null && eV == null) { throw IllegalArgumentException("Require at least on Binding parameter") } } private val errorMessage = "Missing require View Binding parameter" val editText = eD?.editText ?: eDP?.editText ?: eQL?.editText ?: eQLP?.editText ?: eQR?.editText ?: eQRP?.editText ?: eV?.editText ?: throw IllegalArgumentException(errorMessage) val minButton = eD?.minButton ?: eDP?.minButton ?: eQL?.minButton ?: eQLP?.minButton ?: eQR?.minButton ?: eQRP?.minButton ?: eV?.minButton ?: throw IllegalArgumentException(errorMessage) val plusButton1 = eD?.plusButton1 ?: eDP?.plusButton1 ?: eQL?.plusButton1 ?: eQLP?.plusButton1 ?: eQR?.plusButton1 ?: eQRP?.plusButton1 ?: eV?.plusButton1 ?: throw IllegalArgumentException(errorMessage) val label = eD?.label ?: eDP?.label ?: eQL?.label ?: eQLP?.label ?: eQR?.label ?: eQRP?.label ?: eV?.label ?: throw IllegalArgumentException(errorMessage) val plusButton2 = eDP?.plusButton2 ?: eQLP?.plusButton2 ?: eQRP?.plusButton2 val plusButton3 = eDP?.plusButton3 ?: eQLP?.plusButton3 ?: eQRP?.plusButton3 val root = eD?.root ?: eDP?.root ?: eQL?.root ?: eQLP?.root ?: eQR?.root ?: eQRP?.root ?: eV?.root ?: throw IllegalArgumentException(errorMessage) companion object { fun getViewAdapter(sp: SP, context: Context, container: ViewGroup, multiple: Boolean = false): EditPlusMinusViewAdapter { val inflater = LayoutInflater.from(context) return when (sp.getInt(R.string.key_input_design, 1)) { 2 -> { if (multiple) { val bindLayout = ActionEditplusminQuickrightyMultiBinding.inflate(inflater, container, false) EditPlusMinusViewAdapter(null, null, null, null, null, bindLayout, null) } else { val bindLayout = ActionEditplusminQuickrightyBinding.inflate(inflater, container, false) EditPlusMinusViewAdapter(null, null, null, null, bindLayout, null, null) } } 3 -> { if (multiple) { val bindLayout = ActionEditplusminQuickleftyMultiBinding.inflate(inflater, container, false) EditPlusMinusViewAdapter(null, null, null, bindLayout, null, null, null) } else { val bindLayout = ActionEditplusminQuickleftyBinding.inflate(inflater, container, false) EditPlusMinusViewAdapter(null, null, bindLayout, null, null, null, null) } } 4 -> { val bindLayout = ActionEditplusminViktoriaBinding.inflate(inflater, container, false) EditPlusMinusViewAdapter(null, null, null, null, null, null, bindLayout) } else -> { if (multiple) { val bindLayout = ActionEditplusminMultiBinding.inflate(inflater, container, false) EditPlusMinusViewAdapter(null, bindLayout, null, null, null, null, null) } else { val bindLayout = ActionEditplusminBinding.inflate(inflater, container, false) EditPlusMinusViewAdapter(bindLayout, null, null, null, null, null, null) } } } } } }
agpl-3.0
a7ac0ab0f34c6836efd7459585fa4503
50.917526
144
0.640561
4.471254
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/findUsages/handlers/KotlinFindUsagesHandler.kt
3
5869
// 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.findUsages.handlers import com.intellij.find.findUsages.FindUsagesHandler import com.intellij.find.findUsages.FindUsagesOptions import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProgressManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.impl.light.LightMemberReference import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.SearchScope import com.intellij.usageView.UsageInfo import com.intellij.util.CommonProcessors import com.intellij.util.Processor import org.jetbrains.kotlin.idea.base.util.runReadActionInSmartMode import org.jetbrains.kotlin.idea.findUsages.KotlinFindUsagesHandlerFactory import org.jetbrains.kotlin.idea.findUsages.KotlinReferencePreservingUsageInfo import org.jetbrains.kotlin.idea.findUsages.KotlinReferenceUsageInfo import org.jetbrains.kotlin.idea.util.application.runReadAction import java.util.* abstract class KotlinFindUsagesHandler<T : PsiElement>( psiElement: T, private val elementsToSearch: Collection<PsiElement>, val factory: KotlinFindUsagesHandlerFactory ) : FindUsagesHandler(psiElement) { @Suppress("UNCHECKED_CAST") fun getElement(): T { return psiElement as T } constructor(psiElement: T, factory: KotlinFindUsagesHandlerFactory) : this(psiElement, emptyList(), factory) override fun getPrimaryElements(): Array<PsiElement> { return if (elementsToSearch.isEmpty()) arrayOf(psiElement) else elementsToSearch.toTypedArray() } private fun searchTextOccurrences( element: PsiElement, processor: Processor<in UsageInfo>, options: FindUsagesOptions ): Boolean { if (!options.isSearchForTextOccurrences) return true val scope = options.searchScope if (scope is GlobalSearchScope) { if (options.fastTrack == null) { return processUsagesInText(element, processor, scope) } options.fastTrack.searchCustom { processUsagesInText(element, processor, scope) } } return true } override fun processElementUsages( element: PsiElement, processor: Processor<in UsageInfo>, options: FindUsagesOptions ): Boolean { return searchReferences(element, processor, options, forHighlight = false) && searchTextOccurrences(element, processor, options) } private fun searchReferences( element: PsiElement, processor: Processor<in UsageInfo>, options: FindUsagesOptions, forHighlight: Boolean ): Boolean { val searcher = createSearcher(element, processor, options) if (!runReadAction { project }.runReadActionInSmartMode { searcher.buildTaskList(forHighlight) }) return false return searcher.executeTasks() } protected abstract fun createSearcher( element: PsiElement, processor: Processor<in UsageInfo>, options: FindUsagesOptions ): Searcher override fun findReferencesToHighlight(target: PsiElement, searchScope: SearchScope): Collection<PsiReference> { val results = Collections.synchronizedList(arrayListOf<PsiReference>()) val options = findUsagesOptions.clone() options.searchScope = searchScope searchReferences(target, Processor { info -> val reference = info.reference if (reference != null) { results.add(reference) } true }, options, forHighlight = true) return results } protected abstract class Searcher( val element: PsiElement, val processor: Processor<in UsageInfo>, val options: FindUsagesOptions ) { private val tasks = ArrayList<() -> Boolean>() /** * Adds a time-consuming operation to be executed outside read-action */ protected fun addTask(task: () -> Boolean) { tasks.add(task) } /** * Invoked outside read-action */ fun executeTasks(): Boolean { return tasks.all { it() } } /** * Invoked under read-action, should use [addTask] for all time-consuming operations */ abstract fun buildTaskList(forHighlight: Boolean): Boolean } companion object { val LOG = Logger.getInstance(KotlinFindUsagesHandler::class.java) internal fun processUsage(processor: Processor<in UsageInfo>, ref: PsiReference): Boolean = processor.processIfNotNull { when { ref is LightMemberReference -> KotlinReferencePreservingUsageInfo(ref) ref.element.isValid -> KotlinReferenceUsageInfo(ref) else -> null } } internal fun processUsage( processor: Processor<in UsageInfo>, element: PsiElement ): Boolean = processor.processIfNotNull { if (element.isValid) UsageInfo(element) else null } private fun Processor<in UsageInfo>.processIfNotNull(callback: () -> UsageInfo?): Boolean { ProgressManager.checkCanceled() val usageInfo = runReadAction(callback) return if (usageInfo != null) process(usageInfo) else true } internal fun createReferenceProcessor(usageInfoProcessor: Processor<in UsageInfo>): Processor<PsiReference> { val uniqueProcessor = CommonProcessors.UniqueProcessor(usageInfoProcessor) return Processor { processUsage(uniqueProcessor, it) } } } }
apache-2.0
cc66f46549b17fe715ecf267bdf1c05a
35.68125
158
0.67405
5.429232
false
false
false
false
blindpirate/gradle
subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/serialization/codecs/AttributeContainerCodecs.kt
3
4493
/* * Copyright 2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.configurationcache.serialization.codecs import org.gradle.api.attributes.Attribute import org.gradle.api.attributes.AttributeContainer import org.gradle.api.internal.attributes.AttributeContainerInternal import org.gradle.api.internal.attributes.ImmutableAttributes import org.gradle.api.internal.attributes.ImmutableAttributesFactory import org.gradle.configurationcache.extensions.uncheckedCast import org.gradle.configurationcache.serialization.Codec import org.gradle.configurationcache.serialization.ReadContext import org.gradle.configurationcache.serialization.WriteContext import org.gradle.configurationcache.serialization.readCollection import org.gradle.configurationcache.serialization.readNonNull import org.gradle.configurationcache.serialization.writeCollection import org.gradle.internal.state.Managed import org.gradle.internal.state.ManagedFactoryRegistry internal class AttributeContainerCodec( private val attributesFactory: ImmutableAttributesFactory, private val managedFactories: ManagedFactoryRegistry ) : Codec<AttributeContainer> { override suspend fun WriteContext.encode(value: AttributeContainer) { writeAttributes(value) } override suspend fun ReadContext.decode(): AttributeContainer? = readAttributesUsing(attributesFactory, managedFactories) } internal class ImmutableAttributesCodec( private val attributesFactory: ImmutableAttributesFactory, private val managedFactories: ManagedFactoryRegistry ) : Codec<ImmutableAttributes> { override suspend fun WriteContext.encode(value: ImmutableAttributes) { writeAttributes(value) } override suspend fun ReadContext.decode(): ImmutableAttributes = readAttributesUsing(attributesFactory, managedFactories).asImmutable() } private suspend fun WriteContext.writeAttributes(container: AttributeContainer) { writeCollection(container.keySet()) { attribute -> writeAttribute(attribute) val value = container.getAttribute(attribute) writeAttributeValue(value) } } private suspend fun ReadContext.readAttributesUsing( attributesFactory: ImmutableAttributesFactory, managedFactories: ManagedFactoryRegistry ): AttributeContainerInternal = attributesFactory.mutable().apply { readCollection { val attribute = readAttribute() val value = readAttributeValue(managedFactories) attribute(attribute, value) } } private suspend fun WriteContext.writeAttributeValue(value: Any?) { if (value is Managed) { writeBoolean(true) // TODO: consider introducing a ManagedCodec writeManaged(value) } else { writeBoolean(false) write(value) } } private suspend fun ReadContext.readAttributeValue(managedFactories: ManagedFactoryRegistry): Any = if (readBoolean()) { // TODO: consider introducing a ManagedCodec readManaged(managedFactories) } else { readNonNull() } private fun WriteContext.writeAttribute(attribute: Attribute<*>) { writeString(attribute.name) writeClass(attribute.type) } private fun ReadContext.readAttribute(): Attribute<Any> { val name = readString() val type = readClass() return Attribute.of(name, type.uncheckedCast()) } private suspend fun WriteContext.writeManaged(value: Managed) { writeSmallInt(value.factoryId) writeClass(value.publicType()) write(value.unpackState()) } private suspend fun ReadContext.readManaged(managedFactories: ManagedFactoryRegistry): Any { val factoryId = readSmallInt() val type = readClass() val state = read() return managedFactories.lookup(factoryId).fromState(type, state).let { require(it != null) { "Failed to recreate managed value of type $type from state $state" } it } }
apache-2.0
e35c1c52e2e41f4c6161c94b651e3de4
29.773973
91
0.75473
4.810493
false
true
false
false
RadiationX/ForPDA
app/src/main/java/forpdateam/ru/forpda/model/data/remote/api/theme/ThemeApi.kt
1
3238
package forpdateam.ru.forpda.model.data.remote.api.theme import forpdateam.ru.forpda.entity.remote.theme.ThemePage import forpdateam.ru.forpda.model.data.remote.IWebClient import forpdateam.ru.forpda.model.data.remote.api.NetworkRequest import java.net.URLEncoder import java.util.regex.Pattern /** * Created by radiationx on 04.08.16. */ class ThemeApi( private val webClient: IWebClient, private val themeParser: ThemeParser ) { fun getTheme(url: String, hatOpen: Boolean, pollOpen: Boolean): ThemePage { val response = webClient.get(url) val redirectUrl: String = response.redirect ?: url return themeParser.parsePage(response.body, redirectUrl, hatOpen, pollOpen) } fun reportPost(topicId: Int, postId: Int, message: String): Boolean { val request = NetworkRequest.Builder() .url("https://4pda.to/forum/index.php?act=report&send=1&t=$topicId&p=$postId") .formHeader("message", URLEncoder.encode(message, "windows-1251"), true) .build() val response = webClient.request(request) val p = Pattern.compile("<div class=\"errorwrap\">\n" + "\\s*<h4>Причина:</h4>\n" + "\\s*\n" + "\\s*<p>(.*)</p>", Pattern.MULTILINE) val m = p.matcher(response.body) if (m.find()) { throw Exception("Ошибка отправки жалобы: " + m.group(1)) } return true } fun deletePost(postId: Int): Boolean { val url = "https://4pda.to/forum/index.php?act=zmod&auth_key=${webClient.authKey}&code=postchoice&tact=delete&selectedpids=$postId" val response = webClient.request(NetworkRequest.Builder().url(url).xhrHeader().build()) val body = response.body if (body != "ok") { throw Exception("Ошибка изменения репутации поста") } return true } fun votePost(postId: Int, type: Boolean): String { val response = webClient.get("https://4pda.to/forum/zka.php?i=$postId&v=${if (type) "1" else "-1"}") var result: String? = null val alreadyVote = "Ошибка: Вы уже голосовали за это сообщение" val m = Pattern.compile("ok:\\s*?((?:\\+|\\-)?\\d+)").matcher(response.body) if (m.find()) { val code = m.group(1).toInt() when (code) { 0 -> result = alreadyVote 1 -> result = "Репутация поста повышена" -1 -> result = "Репутация поста понижена" } } if (response.body == "evote") { result = alreadyVote } if (result == null) { throw Exception("Ошибка изменения репутации поста") } return result } companion object { val elemToScrollPattern = Pattern.compile("(?:anchor=|#)([^&\\n\\=\\?\\.\\#]*)") val attachImagesPattern = Pattern.compile("(4pda\\.(?:ru|to)\\/forum\\/dl\\/post\\/\\d+\\/[^\"']*?\\.(?:jpe?g|png|gif|bmp))\"?(?:[^>]*?title=\"([^\"']*?\\.(?:jpe?g|png|gif|bmp)) - [^\"']*?\")?") } }
gpl-3.0
d38c452c282b2b88c4980cdaeb3e626c
38.410256
202
0.576773
3.497156
false
false
false
false
KotlinNLP/SimpleDNN
src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/feedforward/squareddistance/SquaredDistanceLayer.kt
1
2107
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.core.layers.models.feedforward.squareddistance import com.kotlinnlp.simplednn.core.arrays.AugmentedArray import com.kotlinnlp.simplednn.core.layers.Layer import com.kotlinnlp.simplednn.core.layers.LayerType import com.kotlinnlp.simplednn.core.layers.helpers.RelevanceHelper import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray /** * The Squared Layer Structure. * * @property inputArray the input array of the layer * @property inputType the input array type (default Dense) * @property outputArray the output array of the layer * @property params the parameters which connect the input to the output * @property dropout the probability of dropout */ internal class SquaredDistanceLayer<InputNDArrayType : NDArray<InputNDArrayType>>( inputArray: AugmentedArray<InputNDArrayType>, inputType: LayerType.Input, outputArray: AugmentedArray<DenseNDArray>, override val params: SquaredDistanceLayerParameters, dropout: Double ) : Layer<InputNDArrayType>( inputArray = inputArray, inputType = inputType, outputArray = outputArray, params = params, activationFunction = null, dropout = dropout ) { /** * It is a support variable used during the calculations. */ val bhOut: AugmentedArray<DenseNDArray> = AugmentedArray(this.params.rank) /** * The helper which executes the forward */ override val forwardHelper = SquaredDistanceForwardHelper(layer = this) /** * The helper which executes the backward */ override val backwardHelper = SquaredDistanceBackwardHelper(layer = this) /** * The helper which calculates the relevance */ override val relevanceHelper: RelevanceHelper? = null }
mpl-2.0
859c18ec673c211bc2720b59a4918c99
34.116667
82
0.744661
4.580435
false
false
false
false
Major-/Vicis
scene3d/src/main/kotlin/rs/emulate/scene3d/backend/opengl/target/javafx/JavaFXRenderTarget.kt
1
2329
package rs.emulate.scene3d.backend.opengl.target.javafx import javafx.application.Platform import javafx.scene.image.ImageView import javafx.scene.image.WritableImage import org.lwjgl.glfw.GLFW.* import org.lwjgl.opengl.GL.createCapabilities import org.lwjgl.opengl.GL11.GL_FALSE import org.lwjgl.opengl.GL11.glFlush import org.lwjgl.opengl.GL30.GL_FRAMEBUFFER import org.lwjgl.opengl.GL30.glBindFramebuffer import org.lwjgl.system.MemoryUtil.NULL import rs.emulate.scene3d.backend.opengl.target.OpenGLRenderTarget /** * A render target that uses an FBO with color/depth attachments and blits its * framebuffer to a [WritableImage], suitable for off-screen rendering. */ class JavaFXRenderTarget(val target: ImageView) : OpenGLRenderTarget { var windowContext: Long = NULL override fun initialize() { if (!glfwInit()) { throw RuntimeException("Unable to initialize GLFW") } glfwDefaultWindowHints() glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3) glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1) glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE) glfwWindowHint(GLFW_VISIBLE, GL_FALSE) glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE) windowContext = glfwCreateWindow(1, 1, "offscreen buffer", NULL, NULL) if (windowContext == NULL) { glfwTerminate() throw RuntimeException("Window == null") } // Bind an OpenGL context for the windowContext to the current thread. glfwMakeContextCurrent(windowContext) createCapabilities() } override fun isVsyncEnabled() = false override fun resize(width: Int, height: Int) { buffer?.dispose() buffer = JavaFXFrameBuffer.create(width, height) bufferImage = WritableImage(width, height) Platform.runLater { target.image = bufferImage } } private var buffer: JavaFXFrameBuffer? = null private var bufferImage = WritableImage(1, 1) override fun bind() { buffer?.let { glBindFramebuffer(GL_FRAMEBUFFER, it.fbo) } } override fun blit() { glFlush() if (target.image == this.bufferImage) { buffer?.copy(this.bufferImage.pixelWriter) } } override fun dispose() { buffer?.dispose() } }
isc
f4697f1beb8860155ef51ed2abfc4f65
30.053333
78
0.683126
4.312963
false
false
false
false
siarhei-luskanau/android-iot-doorbell
base_persistence/src/main/kotlin/siarhei/luskanau/iot/doorbell/persistence/ImageEntity.kt
1
427
package siarhei.luskanau.iot.doorbell.persistence import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "images") data class ImageEntity( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "row_id") val rowId: Int? = null, @ColumnInfo(name = "image_id") val imageId: String, @ColumnInfo(name = "doorbell_id") val doorbellId: String )
mit
bad82a936a30c36788df7e0bf0232a90
20.35
49
0.714286
3.778761
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/growth/usecase/CalculateGrowthStatsUseCase.kt
1
15538
package io.ipoli.android.growth.usecase import io.ipoli.android.common.UseCase import io.ipoli.android.common.datetime.* import io.ipoli.android.growth.persistence.AppUsageStat import io.ipoli.android.growth.persistence.AppUsageStatRepository import io.ipoli.android.planday.usecase.CalculateAwesomenessScoreUseCase import io.ipoli.android.planday.usecase.CalculateFocusDurationUseCase import io.ipoli.android.quest.Color import io.ipoli.android.quest.Icon import io.ipoli.android.quest.Quest import io.ipoli.android.quest.data.persistence.QuestRepository import org.threeten.bp.DayOfWeek import org.threeten.bp.LocalDate import org.threeten.bp.temporal.TemporalAdjusters import kotlin.math.roundToInt class CalculateGrowthStatsUseCase( private val calculateAwesomenessScoreUseCase: CalculateAwesomenessScoreUseCase, private val calculateFocusDurationUseCase: CalculateFocusDurationUseCase, private val questRepository: QuestRepository, private val appUsageStatRepository: AppUsageStatRepository ) : UseCase<CalculateGrowthStatsUseCase.Params, CalculateGrowthStatsUseCase.Result> { private fun calculateAwesomenessScore(quests: List<Quest>) = calculateAwesomenessScoreUseCase.execute( CalculateAwesomenessScoreUseCase.Params.WithQuests( quests ) ) private fun calculateProductiveMinutes(quests: List<Quest>) = calculateFocusDurationUseCase.execute( CalculateFocusDurationUseCase.Params.WithQuests(quests) ) override fun execute(parameters: Params): CalculateGrowthStatsUseCase.Result { val monthStart = parameters.currentDate.withDayOfMonth(1) val monthEnd = monthStart.with(TemporalAdjusters.lastDayOfMonth()) val weekStartDate = parameters.currentDate.with(TemporalAdjusters.previousOrSame(parameters.firstDayOfWeek)) val weekEndDate = parameters.currentDate.with(TemporalAdjusters.nextOrSame(parameters.lastDayOfWeek)) val periodStart = monthStart.with(TemporalAdjusters.previousOrSame(parameters.firstDayOfWeek)) val periodEnd = monthEnd.with(TemporalAdjusters.nextOrSame(parameters.lastDayOfWeek)) val quests = questRepository.findOriginallyScheduledOrCompletedInPeriod(periodStart, periodEnd) val focusTimeByDay = quests.filter { it.isCompleted } .groupBy { it.completedAtDate } .map { it.key!! to calculateProductiveMinutes(it.value) }.toMap() val awesomenessScoreByDay = quests .filter { it.originalScheduledDate != null } .groupBy { it.originalScheduledDate!! } .map { it.key to calculateAwesomenessScore(it.value) }.toMap() val todayQuests = quests.filter { it.completedAtDate == parameters.currentDate } val weeklyQuests = quests.filter { it.completedAtDate?.isBetween( weekStartDate, weekEndDate ) ?: false } val monthlyQuests = quests.filter { it.completedAtDate != null } val todayUsageStats = if (parameters.includeAppUsageStats) appUsageStatRepository.findForDate() else emptyList() val weeklyUsageStats = if (parameters.includeAppUsageStats) appUsageStatRepository.findForWeek() else emptyList() val monthlyUsageStats = if (parameters.includeAppUsageStats) appUsageStatRepository.findForMonth() else emptyList() return Result( todayGrowth = Growth.Today( date = parameters.currentDate, stats = createSummaryStats(todayQuests), tagProgress = createTagProgress(todayQuests), challengeProgress = createTodayChallengeProgress(quests, parameters.currentDate), progressEntries = createTodayProgressEntries(todayQuests), appUsageStats = todayUsageStats, totalAppUsage = todayUsageStats.sumBy { it.usageDuration.intValue }.seconds ), weeklyGrowth = Growth.Week( startDate = weekStartDate, endDate = weekEndDate, stats = createSummaryStats(weeklyQuests), tagProgress = createTagProgress(weeklyQuests), challengeProgress = createWeeklyChallengeProgress( quests = quests, weekStartDate = weekStartDate, weekEndDate = weekEndDate ), progressEntries = createWeeklyProgressEntries( weekStartDate = weekStartDate, focusTimeByDay = focusTimeByDay, awesomenessScoreByDay = awesomenessScoreByDay ), appUsageStats = weeklyUsageStats, totalAppUsage = weeklyUsageStats.sumBy { it.usageDuration.intValue }.seconds ), monthlyGrowth = Growth.Month( stats = createSummaryStats(monthlyQuests), tagProgress = createTagProgress(monthlyQuests), challengeProgress = createMonthlyChallengeProgress( quests = quests, periodStart = periodStart, periodEnd = periodEnd ), progressEntries = createMonthlyProgressEntries( periodStart = periodStart, periodEnd = periodEnd, focusTimeByDay = focusTimeByDay, awesomenessScoreByDay = awesomenessScoreByDay ), appUsageStats = monthlyUsageStats, totalAppUsage = monthlyUsageStats.sumBy { it.usageDuration.intValue }.seconds ) ) } private fun createTagProgress(todayQuests: List<Quest>): List<TagTimeSpent> { val questsByMainTag = todayQuests .filter { it.tags.isNotEmpty() } .groupBy { it.tags.first() } var totalTimeSpent = 0 val tts = questsByMainTag .map { (tag, quests) -> val ts = timeSpentFor(quests) totalTimeSpent += ts.intValue TagTimeSpent( tagId = tag.id, name = tag.name, color = tag.color, icon = tag.icon, timeSpent = ts, focusTime = focusTimeFor(quests) ) }.sortedByDescending { it.timeSpent.intValue } return tts.map { it.copy( timeSpentPercent = ((it.timeSpent.intValue / totalTimeSpent.toFloat()) * 100f) .roundToInt() ) } } private fun focusTimeFor(quests: List<Quest>) = timeSpentFor( quests .filter { it.hasTimer }) private fun createSummaryStats(quests: List<Quest>) = SummaryStats( timeSpent = timeSpentFor(quests), experienceEarned = quests.map { it.reward!!.experience }.sum(), coinsEarned = quests.map { it.reward!!.coins }.sum() ) private fun createTodayChallengeProgress( quests: List<Quest>, currentDate: LocalDate ): List<ChallengeProgress> { val todayQuests = quests .filter { (it.completedAtDate == currentDate || it.scheduledDate == currentDate) && it.challengeId != null } return createChallenges(todayQuests) } private fun createWeeklyChallengeProgress( quests: List<Quest>, weekStartDate: LocalDate, weekEndDate: LocalDate ): List<ChallengeProgress> { val weeklyQuests = quests.filter { val completed = it.completedAtDate?.isBetween( weekStartDate, weekEndDate ) ?: false val scheduled = it.scheduledDate?.isBetween( weekStartDate, weekEndDate ) ?: false (completed || scheduled) && it.challengeId != null } return createChallenges(weeklyQuests) } private fun createMonthlyChallengeProgress( quests: List<Quest>, periodStart: LocalDate, periodEnd: LocalDate ): List<ChallengeProgress> { val weeklyQuests = quests.filter { val completed = it.completedAtDate?.isBetween( periodStart, periodEnd ) ?: false val scheduled = it.scheduledDate?.isBetween( periodStart, periodEnd ) ?: false (completed || scheduled) && it.challengeId != null } return createChallenges(weeklyQuests) } private fun createChallenges(questsForPeriod: List<Quest>): List<ChallengeProgress> { val questsByChallenge = questsForPeriod.groupBy { it.challengeId!! } return questsByChallenge.map { val qs = it.value val completedCount = qs.count { it.isCompleted } ChallengeProgress( id = it.key, progressPercent = ((completedCount / qs.size.toFloat()) * 100f).toInt(), completeQuestCount = completedCount, totalQuestCount = qs.size, timeSpent = minutesSpentForQuests(qs) ) } } private fun minutesSpentForQuests(qs: List<Quest>) = timeSpentFor(qs .filter { it.isCompleted }) private fun timeSpentFor(quests: List<Quest>): Duration<Minute> { return quests .map { it.actualDuration.asMinutes.intValue } .sum() .minutes } private fun createTodayProgressEntries( todayQuests: List<Quest> ): List<ProgressEntry.Today> { val ranges = LinkedHashMap<Time, MutableList<Quest>>() (6..24 step 3).forEach { ranges[Time.atHours(it)] = mutableListOf() } todayQuests.forEach { q -> for (time in ranges.keys) { if (q.completedAtTime!! < time) { ranges[time]!!.add(q) break } } } var prodMins = 0 var awesomeScore = 0.0 return ranges.map { (t, qs) -> prodMins += calculateProductiveMinutes(qs).intValue awesomeScore += calculateAwesomenessScore(qs) ProgressEntry.Today( periodEnd = t, productiveMinutes = prodMins.minutes, awesomenessScore = awesomeScore ) } } private fun createWeeklyProgressEntries( weekStartDate: LocalDate, focusTimeByDay: Map<LocalDate, Duration<Minute>>, awesomenessScoreByDay: Map<LocalDate, Double> ): List<ProgressEntry.Week> { val weekDays = weekStartDate.datesAhead(7) return weekDays.map { ProgressEntry.Week( date = it, productiveMinutes = focusTimeByDay[it] ?: 0.minutes, awesomenessScore = awesomenessScoreByDay[it] ?: 0.0 ) } } private fun createMonthlyProgressEntries( periodStart: LocalDate, periodEnd: LocalDate, focusTimeByDay: Map<LocalDate, Duration<Minute>>, awesomenessScoreByDay: Map<LocalDate, Double> ): MutableList<ProgressEntry.Month> { val monthProgressEntries = mutableListOf<ProgressEntry.Month>() var start = periodStart while (start.isBefore(periodEnd)) { val end = start.plusDays(6) val mins = start.datesBetween(end).map { focusTimeByDay[it] ?: 0.minutes } val scores = start.datesBetween(end).map { awesomenessScoreByDay[it] ?: 0.0 } monthProgressEntries.add( ProgressEntry.Month( weekStart = start, weekEnd = end, productiveMinutes = (mins.sumBy { it.intValue } / 7).minutes, awesomenessScore = (scores.sum() / 7.0) ) ) start = start.plusWeeks(1) } return monthProgressEntries } data class TagTimeSpent( val tagId: String, val name: String, val color: Color, val icon: Icon?, val timeSpentPercent: Int = -1, val timeSpent: Duration<Minute>, val focusTime: Duration<Minute> ) data class ChallengeProgress( val id: String, val progressPercent: Int, val completeQuestCount: Int, val totalQuestCount: Int, val timeSpent: Duration<Minute> ) data class SummaryStats( val timeSpent: Duration<Minute>, val experienceEarned: Int, val coinsEarned: Int ) sealed class ProgressEntry( open val productiveMinutes: Duration<Minute>, open val awesomenessScore: Double ) { data class Today( val periodEnd: Time, override val productiveMinutes: Duration<Minute>, override val awesomenessScore: Double ) : ProgressEntry(productiveMinutes, awesomenessScore) data class Week( val date: LocalDate, override val productiveMinutes: Duration<Minute>, override val awesomenessScore: Double ) : ProgressEntry(productiveMinutes, awesomenessScore) data class Month( val weekStart: LocalDate, val weekEnd: LocalDate, override val productiveMinutes: Duration<Minute>, override val awesomenessScore: Double ) : ProgressEntry(productiveMinutes, awesomenessScore) } sealed class Growth { data class Today( val date: LocalDate, val stats: SummaryStats, val tagProgress: List<TagTimeSpent>, val challengeProgress: List<ChallengeProgress>, val progressEntries: List<ProgressEntry.Today>, val appUsageStats: List<AppUsageStat>, val totalAppUsage: Duration<Second> ) : Growth() data class Week( val startDate: LocalDate, val endDate: LocalDate, val stats: SummaryStats, val tagProgress: List<TagTimeSpent>, val challengeProgress: List<ChallengeProgress>, val progressEntries: List<ProgressEntry.Week>, val appUsageStats: List<AppUsageStat>, val totalAppUsage: Duration<Second> ) : Growth() data class Month( val stats: SummaryStats, val tagProgress: List<TagTimeSpent>, val challengeProgress: List<ChallengeProgress>, val progressEntries: List<ProgressEntry.Month>, val appUsageStats: List<AppUsageStat>, val totalAppUsage: Duration<Second> ) : Growth() } data class Params( val includeAppUsageStats: Boolean = false, val currentDate: LocalDate = LocalDate.now(), val firstDayOfWeek: DayOfWeek = DateUtils.firstDayOfWeek, val lastDayOfWeek: DayOfWeek = DateUtils.lastDayOfWeek ) data class Result( val todayGrowth: Growth.Today, val weeklyGrowth: Growth.Week, val monthlyGrowth: Growth.Month ) }
gpl-3.0
38795dbe4087def95ef7c276d903b4b8
34.969907
124
0.596087
5.000966
false
false
false
false
GunoH/intellij-community
plugins/git4idea/src/git4idea/commands/GitHttpLoginDialog.kt
2
6857
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.commands import com.google.common.annotations.VisibleForTesting import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.NlsSafe import com.intellij.ui.UIBundle import com.intellij.ui.components.* import com.intellij.ui.components.panels.Wrapper import com.intellij.ui.dsl.builder.AlignX import com.intellij.ui.dsl.builder.Panel import com.intellij.ui.dsl.builder.bind import com.intellij.ui.dsl.builder.panel import com.intellij.ui.layout.* import com.intellij.util.AuthData import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import git4idea.i18n.GitBundle import git4idea.remote.InteractiveGitHttpAuthDataProvider import java.awt.event.ActionEvent import javax.swing.AbstractAction import javax.swing.JComponent class GitHttpLoginDialog @JvmOverloads constructor(project: Project, url: @NlsSafe String, rememberPassword: Boolean = true, username: @NlsSafe String? = null, editableUsername: Boolean = true, private val showActionForCredHelper: Boolean = false) : DialogWrapper(project, true) { private val usernameField = JBTextField(username, 20).apply { isEditable = editableUsername } private val passwordField = JBPasswordField() private val rememberCheckbox = JBCheckBox(UIBundle.message("auth.remember.cb"), rememberPassword) private val additionalProvidersButton = JBOptionButton(null, null).apply { isVisible = false } private var useCredentialHelper = false private lateinit var dialogPanel: DialogPanel companion object { const val USE_CREDENTIAL_HELPER_CODE = NEXT_USER_EXIT_CODE } var externalAuthData: AuthData? = null private set init { title = GitBundle.message("login.dialog.label.login.to.url", url) setOKButtonText(GitBundle.message("login.dialog.button.login")) init() } override fun createCenterPanel(): JComponent { if (!showActionForCredHelper) { dialogPanel = panel { row(GitBundle.message("login.dialog.prompt.enter.credentials")) {} buildCredentialsPanel() } } else { dialogPanel = panel { buttonsGroup { lateinit var rbCredentials: JBRadioButton row { rbCredentials = radioButton(GitBundle.message("login.dialog.select.login.way.credentials"), false) .component } indent{ buildCredentialsPanel() }.enabledIf(rbCredentials.selected) row { radioButton(GitBundle.message("login.dialog.select.login.way.use.helper"), true).also { it.component.addActionListener { isOKActionEnabled = true } } } }.bind(::useCredentialHelper) } } return dialogPanel } private fun Panel.buildCredentialsPanel() { row(GitBundle.message("login.dialog.username.label")) { cell(usernameField).align(AlignX.FILL) } row(GitBundle.message("login.dialog.password.label")) { cell(passwordField).align(AlignX.FILL) } row("") { cell(rememberCheckbox) } } override fun doOKAction() { dialogPanel.apply() if (useCredentialHelper) { close(USE_CREDENTIAL_HELPER_CODE, false) return } super.doOKAction() } override fun doValidateAll(): List<ValidationInfo> { dialogPanel.apply() if (useCredentialHelper) { return emptyList() } return listOfNotNull( if (username.isBlank()) ValidationInfo(GitBundle.message("login.dialog.error.username.cant.be.empty"), usernameField) else null, if (passwordField.password.isEmpty()) ValidationInfo(GitBundle.message("login.dialog.error.password.cant.be.empty"), passwordField) else null ) } override fun createSouthAdditionalPanel(): Wrapper = Wrapper(additionalProvidersButton) .apply { border = JBUI.Borders.emptyRight(UIUtil.DEFAULT_HGAP) } override fun getPreferredFocusedComponent(): JComponent = if (username.isBlank()) usernameField else passwordField fun setInteractiveDataProviders(providers: Map<String, InteractiveGitHttpAuthDataProvider>) { if (providers.isEmpty()) return val actions: List<AbstractAction> = providers.map { object : AbstractAction(GitBundle.message("login.dialog.login.with.selected.provider", it.key)) { override fun actionPerformed(e: ActionEvent?) { val authData = it.value.getAuthData([email protected]) if (authData != null) { if (authData.password != null) { externalAuthData = authData [email protected](0, true) } else { usernameField.text = authData.login } } } } } additionalProvidersButton.action = actions.first() if (actions.size > 1) { additionalProvidersButton.options = actions.subList(1, actions.size).toTypedArray() } additionalProvidersButton.isVisible = true } @set:VisibleForTesting var username: String get() = usernameField.text internal set(value) { usernameField.text = value } @set:VisibleForTesting var password: String get() = String(passwordField.password!!) internal set(value) { passwordField.text = value } @set:VisibleForTesting var rememberPassword: Boolean get() = rememberCheckbox.isSelected internal set(value) { rememberCheckbox.isSelected = value } } @Suppress("HardCodedStringLiteral") class TestGitHttpLoginDialogAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { e.project?.let { val gitHttpLoginDialog = GitHttpLoginDialog(it, "http://google.com", showActionForCredHelper = true) gitHttpLoginDialog.show() if (gitHttpLoginDialog.exitCode == GitHttpLoginDialog.USE_CREDENTIAL_HELPER_CODE) { Messages.showMessageDialog(e.project,"Credential selected", "Git login test", null) } else { Messages.showMessageDialog(e.project, "Regular login", "Git login test", null) } } } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } }
apache-2.0
d63365210f8303d8a5a58f015388ae0c
35.089474
140
0.683098
4.617508
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateChecker.kt
1
32113
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.updateSettings.impl import com.intellij.execution.process.ProcessIOExecutorService import com.intellij.ide.IdeBundle import com.intellij.ide.externalComponents.ExternalComponentManager import com.intellij.ide.externalComponents.ExternalComponentSource import com.intellij.ide.plugins.* import com.intellij.ide.plugins.marketplace.MarketplaceRequests import com.intellij.ide.util.PropertiesComponent import com.intellij.internal.statistic.eventLog.fus.MachineIdManager import com.intellij.notification.* import com.intellij.openapi.actionSystem.PlatformCoreDataKeys import com.intellij.openapi.application.* import com.intellij.openapi.application.ex.ApplicationInfoEx import com.intellij.openapi.diagnostic.IdeaLoggingEvent import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.* import com.intellij.openapi.util.text.HtmlBuilder import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame import com.intellij.reference.SoftReference import com.intellij.util.Urls import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.concurrency.annotations.RequiresReadLockAbsence import com.intellij.util.containers.MultiMap import com.intellij.util.io.HttpRequests import com.intellij.util.io.URLUtil import com.intellij.util.ui.UIUtil import com.intellij.xml.util.XmlStringUtil import org.jdom.JDOMException import org.jetbrains.annotations.ApiStatus import java.io.File import java.io.IOException import java.net.HttpURLConnection import java.nio.file.Files import java.nio.file.Path import java.util.* import java.util.concurrent.TimeUnit import java.util.concurrent.locks.ReentrantLock import javax.swing.JComponent import kotlin.Result import kotlin.concurrent.withLock /** * See XML file by [ApplicationInfoEx.getUpdateUrls] for reference. */ object UpdateChecker { private val LOG = logger<UpdateChecker>() private const val DISABLED_UPDATE = "disabled_update.txt" private const val DISABLED_PLUGIN_UPDATE = "plugin_disabled_updates.txt" private const val PRODUCT_DATA_TTL_MIN = 5L private const val MACHINE_ID_DISABLED_PROPERTY = "machine.id.disabled" private const val MACHINE_ID_PARAMETER = "mid" private enum class NotificationKind { PLATFORM, PLUGINS, EXTERNAL } private val updateUrl: String get() = System.getProperty("idea.updates.url") ?: ApplicationInfoEx.getInstanceEx().updateUrls!!.checkingUrl private val productDataLock = ReentrantLock() private var productDataCache: SoftReference<Result<Product?>>? = null private val ourUpdatedPlugins: MutableMap<PluginId, PluginDownloader> = HashMap() private val ourShownNotifications = MultiMap<NotificationKind, Notification>() private var machineIdInitialized = false /** * Adding a plugin ID to this collection allows excluding a plugin from a regular update check. * Has no effect on non-bundled plugins. */ val excludedFromUpdateCheckPlugins: HashSet<String> = hashSetOf() init { UpdateRequestParameters.addParameter("build", ApplicationInfo.getInstance().build.asString()) UpdateRequestParameters.addParameter("uid", PermanentInstallationID.get()) UpdateRequestParameters.addParameter("os", SystemInfo.OS_NAME + ' ' + SystemInfo.OS_VERSION) if (ExternalUpdateManager.ACTUAL != null) { val name = if (ExternalUpdateManager.ACTUAL == ExternalUpdateManager.TOOLBOX) "Toolbox" else ExternalUpdateManager.ACTUAL.toolName UpdateRequestParameters.addParameter("manager", name) } if (ApplicationInfoEx.getInstanceEx().isEAP) { UpdateRequestParameters.addParameter("eap", "") } } @JvmStatic fun getNotificationGroup(): NotificationGroup = NotificationGroupManager.getInstance().getNotificationGroup("IDE and Plugin Updates") @JvmStatic fun getNotificationGroupForPluginUpdateResults(): NotificationGroup = NotificationGroupManager.getInstance().getNotificationGroup("Plugin Update Results") @JvmStatic fun getNotificationGroupForIdeUpdateResults(): NotificationGroup = NotificationGroupManager.getInstance().getNotificationGroup("IDE Update Results") /** * For scheduled update checks. */ @JvmStatic fun updateAndShowResult(): ActionCallback { return ActionCallback().also { ProcessIOExecutorService.INSTANCE.execute { doUpdateAndShowResult( userInitiated = false, preferDialog = false, showSettingsLink = true, callback = it, ) } } } /** * For manual update checks (Help | Check for Updates, Settings | Updates | Check Now) * (the latter action passes customized update settings and forces results presentation in a dialog). */ @JvmStatic @JvmOverloads fun updateAndShowResult( project: Project?, customSettings: UpdateSettings? = null, ) { ProgressManager.getInstance().run(object : Task.Backgroundable(project, IdeBundle.message("updates.checking.progress"), true) { override fun run(indicator: ProgressIndicator) = doUpdateAndShowResult( getProject(), customSettings, userInitiated = true, preferDialog = isConditionalModal, showSettingsLink = shouldStartInBackground(), indicator = indicator, ) override fun isConditionalModal(): Boolean = customSettings != null override fun shouldStartInBackground(): Boolean = !isConditionalModal }) } @JvmStatic private fun doUpdateAndShowResult( project: Project? = null, customSettings: UpdateSettings? = null, userInitiated: Boolean, preferDialog: Boolean, showSettingsLink: Boolean, indicator: ProgressIndicator? = null, callback: ActionCallback? = null, ) { if (!PropertiesComponent.getInstance().getBoolean(MACHINE_ID_DISABLED_PROPERTY, false) && !machineIdInitialized) { machineIdInitialized = true val machineId = MachineIdManager.getAnonymizedMachineId("JetBrainsUpdates", "") if (machineId != null) { UpdateRequestParameters.addParameter(MACHINE_ID_PARAMETER, machineId) } } val updateSettings = customSettings ?: UpdateSettings.getInstance() val platformUpdates = getPlatformUpdates(updateSettings, indicator) if (platformUpdates is PlatformUpdates.ConnectionError) { if (userInitiated) { showErrors(project, IdeBundle.message("updates.error.connection.failed", platformUpdates.error.message), preferDialog) } callback?.setRejected() return } val (pluginUpdates, customRepoPlugins, internalErrors) = getInternalPluginUpdates( (platformUpdates as? PlatformUpdates.Loaded)?.newBuild?.apiVersion, indicator, ) indicator?.text = IdeBundle.message("updates.external.progress") val (externalUpdates, externalErrors) = getExternalPluginUpdates(updateSettings, indicator) UpdateSettings.getInstance().saveLastCheckedInfo() if (userInitiated && (internalErrors.isNotEmpty() || externalErrors.isNotEmpty())) { val builder = HtmlBuilder() internalErrors.forEach { (host, ex) -> if (!builder.isEmpty) builder.br() val message = host?.let { IdeBundle.message("updates.plugins.error.message2", it, ex.message) } ?: IdeBundle.message("updates.plugins.error.message1", ex.message) builder.append(message) } externalErrors.forEach { (key, value) -> if (!builder.isEmpty) builder.br() builder.append(IdeBundle.message("updates.external.error.message", key.name, value.message)) } showErrors(project, builder.wrapWithHtmlBody().toString(), preferDialog) } ApplicationManager.getApplication().invokeLater { fun nonIgnored(downloaders: Collection<PluginDownloader>) = downloaders.filterNot { isIgnored(it.descriptor) } val enabledPlugins = nonIgnored(pluginUpdates.allEnabled) val updatedPlugins = enabledPlugins + nonIgnored(pluginUpdates.allDisabled) val forceDialog = preferDialog || userInitiated && !notificationsEnabled() if (platformUpdates is PlatformUpdates.Loaded) { showResults( project, platformUpdates, updatedPlugins, pluginUpdates.incompatible, showNotification = userInitiated || WelcomeFrame.getInstance() != null, forceDialog, showSettingsLink, ) } else { showResults( project, updatedPlugins, customRepoPlugins, externalUpdates, enabledPlugins.isNotEmpty(), userInitiated, forceDialog, showSettingsLink, ) } callback?.setDone() } } @JvmOverloads @JvmStatic @JvmName("getPlatformUpdates") internal fun getPlatformUpdates( settings: UpdateSettings = UpdateSettings.getInstance(), indicator: ProgressIndicator? = null, ): PlatformUpdates = try { indicator?.text = IdeBundle.message("updates.checking.platform") val productData = loadProductData(indicator) if (productData == null || !settings.isCheckNeeded || ExternalUpdateManager.ACTUAL != null) { PlatformUpdates.Empty } else { UpdateStrategy(ApplicationInfo.getInstance().build, productData, settings).checkForUpdates() } } catch (e: Exception) { LOG.infoWithDebug(e) when (e) { is JDOMException -> PlatformUpdates.Empty // corrupted content, don't bother telling users else -> PlatformUpdates.ConnectionError(e) } } @JvmStatic @Throws(IOException::class, JDOMException::class) fun loadProductData(indicator: ProgressIndicator?): Product? = productDataLock.withLock { val cached = SoftReference.dereference(productDataCache) if (cached != null) return@withLock cached.getOrThrow() val result = runCatching { var url = Urls.newFromEncoded(updateUrl) if (url.scheme != URLUtil.FILE_PROTOCOL) { url = UpdateRequestParameters.amendUpdateRequest(url) } LOG.debug { "loading ${url}" } HttpRequests.request(url) .connect { JDOMUtil.load(it.getReader(indicator)) } .let { parseUpdateData(it) } ?.also { if (it.disableMachineId) { PropertiesComponent.getInstance().setValue(MACHINE_ID_DISABLED_PROPERTY, true) UpdateRequestParameters.removeParameter(MACHINE_ID_PARAMETER) } } } productDataCache = SoftReference(result) AppExecutorUtil.getAppScheduledExecutorService().schedule(this::clearProductDataCache, PRODUCT_DATA_TTL_MIN, TimeUnit.MINUTES) return@withLock result.getOrThrow() } private fun clearProductDataCache() { if (productDataLock.tryLock(1, TimeUnit.MILLISECONDS)) { // a longer time means loading now, no much sense in clearing productDataCache = null productDataLock.unlock() } } @ApiStatus.Internal @JvmStatic fun updateDescriptorsForInstalledPlugins(state: InstalledPluginsState) { if (ApplicationInfoEx.getInstanceEx().usesJetBrainsPluginRepository()) { ApplicationManager.getApplication().executeOnPooledThread { val updateable = collectUpdateablePlugins() if (updateable.isNotEmpty()) { findUpdatesInJetBrainsRepository(updateable, mutableMapOf(), mutableMapOf(), null, state, null) } } } } /** * When [buildNumber] is null, returns new versions of plugins compatible with the current IDE version, * otherwise, returns versions compatible with the specified build. */ @RequiresBackgroundThread @RequiresReadLockAbsence @JvmOverloads @JvmStatic fun getInternalPluginUpdates( buildNumber: BuildNumber? = null, indicator: ProgressIndicator? = null, ): InternalPluginResults { indicator?.text = IdeBundle.message("updates.checking.plugins") if (!PluginEnabler.HEADLESS.isIgnoredDisabledPlugins) { val brokenPlugins = MarketplaceRequests.getInstance().getBrokenPlugins(ApplicationInfo.getInstance().build) if (brokenPlugins.isNotEmpty()) { PluginManagerCore.updateBrokenPlugins(brokenPlugins) } } val updateable = collectUpdateablePlugins() if (updateable.isEmpty()) { return InternalPluginResults(PluginUpdates()) } val toUpdate = HashMap<PluginId, PluginDownloader>() val toUpdateDisabled = HashMap<PluginId, PluginDownloader>() val customRepoPlugins = HashMap<PluginId, PluginNode>() val errors = LinkedHashMap<String?, Exception>() val state = InstalledPluginsState.getInstance() for (host in RepositoryHelper.getPluginHosts()) { try { if (host == null && ApplicationInfoEx.getInstanceEx().usesJetBrainsPluginRepository()) { findUpdatesInJetBrainsRepository(updateable, toUpdate, toUpdateDisabled, buildNumber, state, indicator) } else { RepositoryHelper.loadPlugins(host, buildNumber, indicator).forEach { descriptor -> val id = descriptor.pluginId if (updateable.remove(id) != null) { prepareDownloader(state, descriptor, buildNumber, toUpdate, toUpdateDisabled, indicator, host) } // collect latest plugins from custom repos val storedDescriptor = customRepoPlugins[id] if (storedDescriptor == null || StringUtil.compareVersionNumbers(descriptor.version, storedDescriptor.version) > 0) { customRepoPlugins[id] = descriptor } } } } catch (e: Exception) { LOG.info( "failed to load plugins from ${host ?: "default repository"}: ${e.message}", if (LOG.isDebugEnabled) e else null, ) errors[host] = e } } val incompatible = if (buildNumber == null) emptyList() else { // collecting plugins that aren't going to be updated and are incompatible with the new build // (the map may contain updateable bundled plugins - those are expected to have a compatible version in IDE) updateable.values.asSequence() .filterNotNull() .filter { it.isEnabled && !it.isBundled && !PluginManagerCore.isCompatible(it, buildNumber) } .toSet() } return InternalPluginResults(PluginUpdates(toUpdate.values, toUpdateDisabled.values, incompatible), customRepoPlugins.values, errors) } private fun collectUpdateablePlugins(): MutableMap<PluginId, IdeaPluginDescriptor?> { val updateable = HashMap<PluginId, IdeaPluginDescriptor?>() // installed plugins that could be updated (either downloaded or updateable bundled) PluginManagerCore.getPlugins() .filter { !it.isBundled || it.allowBundledUpdate() } .associateByTo(updateable) { it.pluginId } // plugins installed in an instance from which the settings were imported val onceInstalled = PluginManager.getOnceInstalledIfExists() if (onceInstalled != null) { try { Files.readAllLines(onceInstalled).forEach { line -> val id = PluginId.getId(line.trim { it <= ' ' }) updateable.putIfAbsent(id, null) } } catch (e: IOException) { LOG.error(onceInstalled.toString(), e) } @Suppress("SSBasedInspection") onceInstalled.toFile().deleteOnExit() } // excluding plugins that take care of their own updates if (excludedFromUpdateCheckPlugins.isNotEmpty() && !ApplicationManager.getApplication().isInternal) { excludedFromUpdateCheckPlugins.forEach { val id = PluginId.getId(it) val plugin = updateable[id] if (plugin != null && plugin.isBundled) { updateable.remove(id) } } } return updateable } @RequiresBackgroundThread @RequiresReadLockAbsence private fun findUpdatesInJetBrainsRepository(updateable: MutableMap<PluginId, IdeaPluginDescriptor?>, toUpdate: MutableMap<PluginId, PluginDownloader>, toUpdateDisabled: MutableMap<PluginId, PluginDownloader>, buildNumber: BuildNumber?, state: InstalledPluginsState, indicator: ProgressIndicator?) { val marketplacePluginIds = MarketplaceRequests.getInstance().getMarketplacePlugins(indicator) val idsToUpdate = updateable.keys.filter { it in marketplacePluginIds }.toSet() val updates = MarketplaceRequests.getLastCompatiblePluginUpdate(idsToUpdate, buildNumber) updateable.forEach { (id, descriptor) -> val lastUpdate = updates.find { it.pluginId == id.idString } if (lastUpdate != null && (descriptor == null || PluginDownloader.compareVersionsSkipBrokenAndIncompatible(lastUpdate.version, descriptor, buildNumber) > 0)) { runCatching { MarketplaceRequests.loadPluginDescriptor(id.idString, lastUpdate, indicator) } .onFailure { if (it !is HttpRequests.HttpStatusException || it.statusCode != HttpURLConnection.HTTP_NOT_FOUND) throw it } .onSuccess { it.externalPluginIdForScreenShots = lastUpdate.externalPluginId } .onSuccess { prepareDownloader(state, it, buildNumber, toUpdate, toUpdateDisabled, indicator, null) } } } (toUpdate.keys.asSequence() + toUpdateDisabled.keys.asSequence()).forEach { updateable.remove(it) } } private fun prepareDownloader(state: InstalledPluginsState, descriptor: PluginNode, buildNumber: BuildNumber?, toUpdate: MutableMap<PluginId, PluginDownloader>, toUpdateDisabled: MutableMap<PluginId, PluginDownloader>, indicator: ProgressIndicator?, host: String?) { val downloader = PluginDownloader.createDownloader(descriptor, host, buildNumber) state.onDescriptorDownload(descriptor) checkAndPrepareToInstall(downloader, state, if (PluginManagerCore.isDisabled(downloader.id)) toUpdateDisabled else toUpdate, buildNumber, indicator) } @JvmOverloads @JvmStatic fun getExternalPluginUpdates( updateSettings: UpdateSettings, indicator: ProgressIndicator? = null, ): ExternalPluginResults { val result = ArrayList<ExternalUpdate>() val errors = LinkedHashMap<ExternalComponentSource, Exception>() val manager = ExternalComponentManager.getInstance() for (source in ExternalComponentManager.getComponentSources()) { indicator?.checkCanceled() try { val siteResult = source.getAvailableVersions(indicator, updateSettings) .filter { it.isUpdateFor(manager.findExistingComponentMatching(it, source)) } if (siteResult.isNotEmpty()) { result += ExternalUpdate(source, siteResult) } } catch (e: Exception) { LOG.info("failed to load updates for ${source}: ${e.message}", if (LOG.isDebugEnabled) e else null) errors[source] = e } } return ExternalPluginResults(result, errors) } @Throws(IOException::class) @JvmOverloads @JvmStatic fun checkAndPrepareToInstall( originalDownloader: PluginDownloader, state: InstalledPluginsState, toUpdate: MutableMap<PluginId, PluginDownloader>, buildNumber: BuildNumber? = null, indicator: ProgressIndicator? = null, ) { val pluginId = originalDownloader.id val pluginVersion = originalDownloader.pluginVersion val installedPlugin = PluginManagerCore.getPlugin(pluginId) if (installedPlugin == null || pluginVersion == null || PluginDownloader.compareVersionsSkipBrokenAndIncompatible(pluginVersion, installedPlugin, buildNumber) > 0) { val oldDownloader = ourUpdatedPlugins[pluginId] val downloader = if (PluginManagerCore.isDisabled(pluginId)) { originalDownloader } else if (oldDownloader == null || StringUtil.compareVersionNumbers(pluginVersion, oldDownloader.pluginVersion) > 0) { val descriptor = originalDownloader.descriptor if (descriptor is PluginNode && descriptor.isIncomplete) { originalDownloader.prepareToInstall(indicator ?: EmptyProgressIndicator()) ourUpdatedPlugins[pluginId] = originalDownloader } originalDownloader } else { oldDownloader } val descriptor = downloader.descriptor if (PluginManagerCore.isCompatible(descriptor, downloader.buildNumber) && !state.wasUpdated(descriptor.pluginId)) { toUpdate[pluginId] = downloader } } } private fun showErrors(project: Project?, @NlsContexts.DialogMessage message: String, preferDialog: Boolean) { if (preferDialog) { UIUtil.invokeLaterIfNeeded { Messages.showErrorDialog(project, message, IdeBundle.message("updates.error.connection.title")) } } else { getNotificationGroup().createNotification(message, NotificationType.WARNING).notify(project) } } @RequiresEdt private fun showResults( project: Project?, updatedPlugins: List<PluginDownloader>, customRepoPlugins: Collection<PluginNode>, externalUpdates: Collection<ExternalUpdate>, pluginsEnabled: Boolean, userInitiated: Boolean, forceDialog: Boolean, showSettingsLink: Boolean, ) { if (pluginsEnabled) { if (userInitiated) { ourShownNotifications.remove(NotificationKind.PLUGINS)?.forEach { it.expire() } } val runnable = { PluginUpdateDialog(project, updatedPlugins, customRepoPlugins).show() } if (forceDialog) { runnable() } else { UpdateSettingsEntryPointActionProvider.newPluginUpdates(updatedPlugins, customRepoPlugins) if (userInitiated) { val updatedPluginNames = updatedPlugins.map { it.pluginName } val (title, message) = when (updatedPluginNames.size) { 1 -> "" to IdeBundle.message("updates.plugin.ready.title", updatedPluginNames[0]) else -> IdeBundle.message("updates.plugins.ready.title") to updatedPluginNames.joinToString { """"$it"""" } } showNotification( project, NotificationKind.PLUGINS, "plugins.update.available", title, message, NotificationAction.createExpiring(IdeBundle.message("updates.all.plugins.action", updatedPlugins.size)) { e, _ -> PluginUpdateDialog.runUpdateAll(updatedPlugins, e.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT) as JComponent?, null) }, NotificationAction.createSimpleExpiring(IdeBundle.message("updates.plugins.dialog.action"), runnable), NotificationAction.createSimpleExpiring(IdeBundle.message("updates.ignore.updates.link", updatedPlugins.size)) { ignorePlugins(updatedPlugins.map { it.descriptor }) }) } } } if (externalUpdates.isNotEmpty()) { ourShownNotifications.remove(NotificationKind.EXTERNAL)?.forEach { it.expire() } for (update in externalUpdates) { val runnable = { update.source.installUpdates(update.components) } if (forceDialog) { runnable() } else { val message = IdeBundle.message("updates.external.ready.message", update.components.size, update.components.joinToString(", ")) showNotification( project, NotificationKind.EXTERNAL, "external.components.available", "", message, NotificationAction.createSimpleExpiring(IdeBundle.message("updates.notification.update.action"), runnable)) } } } else if (!pluginsEnabled) { if (forceDialog) { NoUpdatesDialog(showSettingsLink).show() } else if (userInitiated) { showNotification(project, NotificationKind.PLUGINS, "no.updates.available", "", NoUpdatesDialog.getNoUpdatesText()) } } } @RequiresEdt private fun showResults( project: Project?, platformUpdates: PlatformUpdates.Loaded, updatedPlugins: List<PluginDownloader>, incompatiblePlugins: Collection<IdeaPluginDescriptor>, showNotification: Boolean, forceDialog: Boolean, showSettingsLink: Boolean, ) { if (showNotification) { ourShownNotifications.remove(NotificationKind.PLATFORM)?.forEach { it.expire() } } val runnable = { UpdateInfoDialog( project, platformUpdates, showSettingsLink, updatedPlugins, incompatiblePlugins, ).show() } if (forceDialog) { runnable() } else { UpdateSettingsEntryPointActionProvider.newPlatformUpdate(platformUpdates, updatedPlugins, incompatiblePlugins) if (showNotification) { IdeUpdateUsageTriggerCollector.NOTIFICATION_SHOWN.log(project) val message = IdeBundle.message( "updates.new.build.notification.title", ApplicationNamesInfo.getInstance().fullProductName, platformUpdates.newBuild.version, ) showNotification( project, NotificationKind.PLATFORM, "ide.update.available", "", message, NotificationAction.createSimpleExpiring(IdeBundle.message("updates.notification.update.action")) { IdeUpdateUsageTriggerCollector.NOTIFICATION_CLICKED.log(project) runnable() }) } } } private fun notificationsEnabled(): Boolean = NotificationsConfiguration.getNotificationsConfiguration().let { it.areNotificationsEnabled() && it.getDisplayType(getNotificationGroup().displayId) != NotificationDisplayType.NONE } private fun showNotification(project: Project?, kind: NotificationKind, displayId: String, @NlsContexts.NotificationTitle title: String, @NlsContexts.NotificationContent message: String, vararg actions: NotificationAction) { val type = if (kind == NotificationKind.PLATFORM) NotificationType.IDE_UPDATE else NotificationType.INFORMATION val notification = getNotificationGroup().createNotification(title, XmlStringUtil.wrapInHtml(message), type) .setDisplayId(displayId) .setCollapseDirection(Notification.CollapseActionsDirection.KEEP_LEFTMOST) notification.whenExpired { ourShownNotifications.remove(kind, notification) } actions.forEach { notification.addAction(it) } notification.notify(project) ourShownNotifications.putValue(kind, notification) } @JvmStatic val disabledToUpdate: Set<PluginId> by lazy { TreeSet(readConfigLines(DISABLED_UPDATE).map { PluginId.getId(it) }) } @JvmStatic fun saveDisabledToUpdatePlugins() { runCatching { PluginManagerCore.writePluginIdsToFile( /* path = */ PathManager.getConfigDir().resolve(DISABLED_UPDATE), /* pluginIds = */ disabledToUpdate, ) }.onFailure { LOG.error(it) } } @JvmStatic @JvmName("isIgnored") internal fun isIgnored(descriptor: IdeaPluginDescriptor): Boolean = descriptor.ignoredKey in ignoredPlugins @JvmStatic @JvmName("ignorePlugins") internal fun ignorePlugins(descriptors: List<IdeaPluginDescriptor>) { ignoredPlugins += descriptors.map { it.ignoredKey } runCatching { Files.write(Path.of(PathManager.getConfigPath(), DISABLED_PLUGIN_UPDATE), ignoredPlugins) } .onFailure { LOG.error(it) } UpdateSettingsEntryPointActionProvider.removePluginsUpdate(descriptors) } private val ignoredPlugins: MutableSet<String> by lazy { TreeSet(readConfigLines(DISABLED_PLUGIN_UPDATE)) } private val IdeaPluginDescriptor.ignoredKey: String get() = "${pluginId.idString}+${version}" private fun readConfigLines(fileName: String): List<String> { if (!ApplicationManager.getApplication().isUnitTestMode) { runCatching { val file = Path.of(PathManager.getConfigPath(), fileName) if (Files.isRegularFile(file)) { return Files.readAllLines(file) } }.onFailure { LOG.error(it) } } return emptyList() } private var ourHasFailedPlugins = false @JvmStatic fun checkForUpdate(event: IdeaLoggingEvent) { if (!ourHasFailedPlugins) { val app = ApplicationManager.getApplication() if (app != null && !app.isDisposed && UpdateSettings.getInstance().isPluginsCheckNeeded) { val pluginDescriptor = PluginManagerCore.getPlugin(PluginUtil.getInstance().findPluginId(event.throwable)) if (pluginDescriptor != null && !pluginDescriptor.isBundled) { ourHasFailedPlugins = true updateAndShowResult() } } } } /** A helper method for manually testing platform updates (see [com.intellij.internal.ShowUpdateInfoDialogAction]). */ @ApiStatus.Internal fun testPlatformUpdate( project: Project?, updateDataText: String, patchFile: File?, forceUpdate: Boolean, ) { if (!ApplicationManager.getApplication().isInternal) { throw IllegalStateException() } val currentBuild = ApplicationInfo.getInstance().build val productCode = currentBuild.productCode val checkForUpdateResult = if (forceUpdate) { val node = JDOMUtil.load(updateDataText) .getChild("product") ?.getChild("channel") ?: throw IllegalArgumentException("//channel missing") val channel = UpdateChannel(node, productCode) val newBuild = channel.builds.firstOrNull() ?: throw IllegalArgumentException("//build missing") val patches = newBuild.patches.firstOrNull() ?.let { UpdateChain(listOf(it.fromBuild, newBuild.number), it.size) } PlatformUpdates.Loaded(newBuild, channel, patches) } else { UpdateStrategy( currentBuild, parseUpdateData(updateDataText, productCode), ).checkForUpdates() } val dialog = when (checkForUpdateResult) { is PlatformUpdates.Loaded -> UpdateInfoDialog(project, checkForUpdateResult, patchFile) else -> NoUpdatesDialog(true) } dialog.show() } //<editor-fold desc="Deprecated stuff."> @ApiStatus.ScheduledForRemoval @Deprecated(level = DeprecationLevel.ERROR, replaceWith = ReplaceWith("getNotificationGroup()"), message = "Use getNotificationGroup()") @Suppress("DEPRECATION", "unused") @JvmField val NOTIFICATIONS = NotificationGroup("IDE and Plugin Updates", NotificationDisplayType.STICKY_BALLOON, true, null, null, null, PluginManagerCore.CORE_ID) @get:ApiStatus.ScheduledForRemoval @get:Deprecated(message = "Use disabledToUpdate", replaceWith = ReplaceWith("disabledToUpdate")) @Deprecated(message = "Use disabledToUpdate", replaceWith = ReplaceWith("disabledToUpdate")) @Suppress("unused") @JvmStatic val disabledToUpdatePlugins: Set<String> get() = disabledToUpdate.mapTo(TreeSet()) { it.idString } @ApiStatus.ScheduledForRemoval @Deprecated(message = "Use checkForPluginUpdates", replaceWith = ReplaceWith("")) @JvmStatic fun getPluginUpdates(): Collection<PluginDownloader>? = getInternalPluginUpdates().pluginUpdates.allEnabled.ifEmpty { null } //</editor-fold> }
apache-2.0
50e51d04c83bf7e7d4337b3b004d5afa
38.694685
156
0.695762
5.424493
false
false
false
false
Lizhny/BigDataFortuneTelling
baselibrary/src/main/java/com/bdft/baselibrary/utils/ui/ViewUtil.kt
1
2255
package com.bdft.baselibrary.utils.ui import android.graphics.Rect import android.view.TouchDelegate import android.view.View import com.socks.library.KLog import java.util.* /** * ${} * Created by spark_lizhy on 2017/10/31. */ object ViewUtil { fun setViewsClickListener(listener: View.OnClickListener, vararg views: View) { for (view in views) { view.setOnClickListener { listener } } } fun setViewsVisible(visible: Int, vararg views: View) { for (view in views) { view.visibility = visible } } fun setViewsEnable(enable: Boolean, vararg views: View) { for (view in views) { view.isEnabled = enable } } fun setViewsEnableAndClickble(enable: Boolean, clickable: Boolean, vararg views: View) { for (view in views) { view.isEnabled = enable view.isClickable = clickable } } /** * 扩大View的触摸和点击响应范围,最大不超过其父View范围(ABSListView无效) * 延迟300毫秒执行,使该方法可以在onCreate里面使用 */ fun expandViewTouchDelegate(view: View?, left: Int, top: Int, right: Int, bottom: Int) { if (view == null) return val parent: View? = view.parent as View parent?.postDelayed({ val bounds = Rect() view.isEnabled = true view.getHitRect(bounds) bounds.left -= left bounds.top -= top bounds.right += right bounds.bottom += bottom KLog.d("bounds", "rect - top" + bounds.top + " - right" + bounds.right) val touchDelegate = TouchDelegate(bounds, view) if (view.parent is View) { parent.touchDelegate = touchDelegate } }, 300) } fun restoreViewTouchDelegate(view: View?) { if (view == null) return val parent: View? = view.parent as View parent?.postDelayed({ val bounds = Rect() bounds.setEmpty() val touchDelegate = TouchDelegate(bounds, view) if (view.parent is View) { parent.touchDelegate = touchDelegate } }, 300) } }
apache-2.0
57521948acd497e69e607f3c31be16e2
27.181818
92
0.572614
4.061798
false
false
false
false
GunoH/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/editor/tables/ui/MarkdownTableInlayProvider.kt
7
3498
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.editor.tables.ui import com.intellij.codeInsight.hints.* import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.Key import com.intellij.openapi.util.registry.Registry import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.refactoring.suggested.startOffset import com.intellij.util.DocumentUtil import org.intellij.plugins.markdown.MarkdownBundle import org.intellij.plugins.markdown.editor.tables.TableModificationUtils.hasCorrectBorders import org.intellij.plugins.markdown.editor.tables.TableUtils import org.intellij.plugins.markdown.editor.tables.ui.presentation.HorizontalBarPresentation import org.intellij.plugins.markdown.editor.tables.ui.presentation.VerticalBarPresentation import org.intellij.plugins.markdown.lang.MarkdownFileType import org.intellij.plugins.markdown.lang.psi.impl.MarkdownTable import org.intellij.plugins.markdown.lang.psi.impl.MarkdownTableRow import org.intellij.plugins.markdown.lang.psi.impl.MarkdownTableSeparatorRow import org.intellij.plugins.markdown.settings.MarkdownSettings import javax.swing.JPanel internal class MarkdownTableInlayProvider: InlayHintsProvider<NoSettings> { override fun getCollectorFor(file: PsiFile, editor: Editor, settings: NoSettings, sink: InlayHintsSink): InlayHintsCollector? { if (!Registry.`is`("markdown.tables.editing.support.enable") || !MarkdownSettings.getInstance(file.project).isEnhancedEditingEnabled) { return null } if (file.fileType != MarkdownFileType.INSTANCE) { return null } return Collector(editor) } private class Collector(editor: Editor): FactoryInlayHintsCollector(editor) { override fun collect(element: PsiElement, editor: Editor, sink: InlayHintsSink): Boolean { if (editor.getUserData(DISABLE_TABLE_INLAYS) == true) { return true } if (element is MarkdownTableRow || element is MarkdownTableSeparatorRow) { if (DocumentUtil.isAtLineStart(element.startOffset, editor.document) && TableUtils.findTable(element)?.hasCorrectBorders() == true) { val presentation = VerticalBarPresentation.create(factory, editor, element) sink.addInlineElement(element.startOffset, false, presentation, false) } } else if (element is MarkdownTable && element.hasCorrectBorders()) { val presentation = HorizontalBarPresentation.create(factory, editor, element) sink.addBlockElement(element.startOffset, false, true, -1, presentation) } return true } } override fun createSettings() = NoSettings() override val name: String get() = MarkdownBundle.message("markdown.table.inlay.kind.name") override val description: String get() = MarkdownBundle.message("markdown.table.inlay.kind.description") override val key: SettingsKey<NoSettings> get() = settingsKey override val previewText: String? = null override fun createConfigurable(settings: NoSettings): ImmediateConfigurable { return object: ImmediateConfigurable { override fun createComponent(listener: ChangeListener) = JPanel() } } companion object { private val settingsKey = SettingsKey<NoSettings>("MarkdownTableInlayProviderSettingsKey") val DISABLE_TABLE_INLAYS = Key<Boolean>("MarkdownDisableTableInlaysKey") } }
apache-2.0
316a912f3cb408e14035a54e3ed31fd2
44.428571
158
0.77673
4.645418
false
false
false
false
NiciDieNase/chaosflix
touch/src/main/java/de/nicidienase/chaosflix/touch/playback/PlayerActivity.kt
1
4142
package de.nicidienase.chaosflix.touch.playback import android.content.Context import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import de.nicidienase.chaosflix.common.mediadata.entities.recording.persistence.Event import de.nicidienase.chaosflix.common.mediadata.entities.recording.persistence.Recording import de.nicidienase.chaosflix.common.mediadata.entities.streaming.StreamUrl import de.nicidienase.chaosflix.touch.R import de.nicidienase.chaosflix.touch.browse.cast.CastService class PlayerActivity : AppCompatActivity() { private lateinit var casty: CastService override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_player) casty = CastService(this, false) val extras = intent.extras if (savedInstanceState == null && extras != null) { val contentType = intent.getStringExtra(CONTENT_TYPE) var playbackItem = PlaybackItem("Empty", "Empty", "", "") if (contentType == CONTENT_RECORDING) { val event = extras.getParcelable<Event>(EVENT_KEY) val recording = extras.getParcelable<Recording>(RECORDING_KEY) val recordingUri = extras.getString(OFFLINE_URI) playbackItem = PlaybackItem( event?.title ?: "", event?.subtitle ?: "", event?.guid ?: "", recordingUri ?: recording?.recordingUrl ?: "") } else if (contentType.equals(CONTENT_STREAM)) { // TODO implement Player for Stream val conference = extras.getString(CONFERENCE, "") val room = extras.getString(ROOM, "") val stream = extras.getString(STREAM, "") playbackItem = PlaybackItem(conference, room, "", stream) } val ft = supportFragmentManager.beginTransaction() val playerFragment = ExoPlayerFragment.newInstance(playbackItem) ft.replace(R.id.fragment_container, playerFragment) ft.commit() } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { super.onCreateOptionsMenu(menu) menu?.let { casty.addMediaRouteMenuItem(it) } return true } override fun onOptionsItemSelected(item: MenuItem?): Boolean { if (item?.itemId == android.R.id.home) { finish() return true } return super.onOptionsItemSelected(item) } companion object { const val CONTENT_TYPE = "content" const val CONTENT_RECORDING = "content_recording" const val CONTENT_STREAM = "content_stream" const val EVENT_KEY = "event" const val RECORDING_KEY = "recording" const val CONFERENCE = "live_conferences" const val ROOM = "room" const val STREAM = "stream" const val OFFLINE_URI = "recording_uri" fun launch(context: Context, event: Event, uri: String) { val i = Intent(context, PlayerActivity::class.java) i.putExtra(CONTENT_TYPE, CONTENT_RECORDING) i.putExtra(EVENT_KEY, event) i.putExtra(OFFLINE_URI, uri) context.startActivity(i) } fun launch(context: Context, event: Event, recording: Recording) { val i = Intent(context, PlayerActivity::class.java) i.putExtra(CONTENT_TYPE, CONTENT_RECORDING) i.putExtra(EVENT_KEY, event) i.putExtra(RECORDING_KEY, recording) context.startActivity(i) } fun launch(context: Context, conference: String, room: String, stream: StreamUrl) { val i = Intent(context, PlayerActivity::class.java) i.putExtra(CONTENT_TYPE, CONTENT_STREAM) i.putExtra(CONFERENCE, conference) i.putExtra(ROOM, room) i.putExtra(STREAM, stream.url) context.startActivity(i) } } }
mit
53f92c6d84b072fe32af78921afac9fe
37.71028
91
0.623853
4.793981
false
false
false
false
marius-m/wt4
components/src/test/java/lt/markmerkk/utils/hourglass/HourGlassChangeStart2Test.kt
1
1478
package lt.markmerkk.utils.hourglass import lt.markmerkk.TimeProviderTest import lt.markmerkk.WTEventBus import org.assertj.core.api.Assertions.assertThat import org.joda.time.Duration import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.MockitoAnnotations class HourGlassChangeStart2Test { @Mock lateinit var eventBus: WTEventBus private lateinit var hourGlass: HourGlass private val timeProvider = TimeProviderTest() @Before fun setUp() { MockitoAnnotations.initMocks(this) hourGlass = HourGlassImpl(eventBus, timeProvider) } @Test fun valid() { // Assemble val now = timeProvider.now() // Act hourGlass.changeStart(now.minusMinutes(5)) val duration = hourGlass.duration val start = hourGlass.start // Assert assertThat(start).isEqualTo(now.minusMinutes(5)) assertThat(duration).isEqualTo( Duration( now, now.plusMinutes(5) ) ) } @Test fun startOverNow() { // Assemble val now = timeProvider.now() // Act hourGlass.changeStart(now.plusMinutes(5)) val duration = hourGlass.duration val start = hourGlass.start // Assert assertThat(start).isEqualTo(now) assertThat(duration).isEqualTo( Duration(now, now) ) } }
apache-2.0
b7ae336fb31f21e08d5962c23b6bdb35
22.854839
57
0.61908
4.633229
false
true
false
false
hawaiianmoose/Android-DankBoard
app/src/main/java/com/boomcity/dankboard/SoundClip.kt
1
207
package com.boomcity.dankboard open class SoundClip(title: String = "", audioId: Int = 0, path: String? = null) { var Title: String = title var AudioId: Int = audioId var Path: String? = path }
gpl-3.0
653980e8c3bf099985b90d9dd0cc3a1a
28.571429
82
0.661836
3.285714
false
false
false
false
evanchooly/kobalt
src/main/kotlin/com/beust/kobalt/app/remote/WasabiServer.kt
1
1467
//package com.beust.kobalt.app.remote // //import com.beust.kobalt.Args //import com.beust.kobalt.api.Project // //class WasabiServer(val initCallback: (String) -> List<Project>, val cleanUpCallback: () -> Unit) // : KobaltServer.IServer { // override fun run(port: Int) { // with(AppServer(AppConfiguration(port))) { // get("/", { response.send("Hello World!") }) // get("/v0/getDependencies", // { // val buildFile = request.queryParams["buildFile"] // if (buildFile != null) { // // val projects = initCallback(buildFile) // val result = try { // val dependencyData = Kobalt.INJECTOR.getInstance(DependencyData::class.java) // val args = Kobalt.INJECTOR.getInstance(Args::class.java) // // val dd = dependencyData.dependenciesDataFor(buildFile, args) // Gson().toJson(dd) // } catch(ex: Exception) { // "Error: " + ex.message // } finally { // cleanUpCallback() // } // // response.send(result) // } // } // ) // start() // } // } //} //
apache-2.0
b4078f83ecc282f8b04d160647f86f3e
38.648649
110
0.42195
4.686901
false
false
false
false
ktorio/ktor
ktor-http/ktor-http-cio/jvm/test/io/ktor/tests/http/cio/MultipartTest.kt
1
15568
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.tests.http.cio import io.ktor.http.cio.* import io.ktor.utils.io.* import kotlinx.coroutines.* import kotlinx.coroutines.channels.* import kotlin.test.* @OptIn(ExperimentalCoroutinesApi::class, DelicateCoroutinesApi::class) class MultipartTest { @Test fun smokeTest() = runBlocking { val body = """ POST /send-message.html HTTP/1.1 Host: webmail.example.com Referer: http://webmail.example.com/send-message.html User-Agent: BrowserForDummies/4.67b Content-Type: multipart/form-data; boundary=Asrf456BGe4h Connection: close Keep-Alive: 300 preamble --Asrf456BGe4h Content-Disposition: form-data; name="DestAddress" [email protected] --Asrf456BGe4h Content-Disposition: form-data; name="MessageTitle" Good news --Asrf456BGe4h Content-Disposition: form-data; name="MessageText" See attachments... --Asrf456BGe4h Content-Disposition: form-data; name="AttachedFile1"; filename="horror-photo-1.jpg" Content-Type: image/jpeg JFIF first --Asrf456BGe4h Content-Disposition: form-data; name="AttachedFile2"; filename="horror-photo-2.jpg" Content-Type: image/jpeg JFIF second --Asrf456BGe4h-- epilogue """.trimIndent() .lines() .joinToString("\r\n") val ch = ByteReadChannel(body.toByteArray()) val request = parseRequest(ch)!! val mp = parseMultipart(ch, request.headers) val allEvents = ArrayList<MultipartEvent>() mp.consumeEach { allEvents.add(it) } assertEquals(7, allEvents.size) val preamble = allEvents[0] as MultipartEvent.Preamble assertEquals("preamble\r\n", preamble.body.readText()) val recipient = allEvents[1] as MultipartEvent.MultipartPart assertEquals("[email protected]", recipient.body.readRemaining().readText()) val title = allEvents[2] as MultipartEvent.MultipartPart assertEquals("Good news", title.body.readRemaining().readText()) val text = allEvents[3] as MultipartEvent.MultipartPart assertEquals("See attachments...", text.body.readRemaining().readText()) val jpeg1 = allEvents[4] as MultipartEvent.MultipartPart assertEquals("JFIF first", jpeg1.body.readRemaining().readText()) val jpeg2 = allEvents[5] as MultipartEvent.MultipartPart assertEquals("JFIF second", jpeg2.body.readRemaining().readText()) val epilogue = allEvents[6] as MultipartEvent.Epilogue assertEquals("epilogue", epilogue.body.readText()) } @Test fun smokeTestUnicode() = runBlocking { val body = """ POST /send-message.html HTTP/1.1 Host: webmail.example.com Referer: http://webmail.example.com/send-message.html User-Agent: BrowserForDummies/4.67b Content-Type: multipart/form-data; boundary=Asrf456BGe4h Connection: close Keep-Alive: 300 preamble --Asrf456BGe4h Content-Disposition: form-data; name="DestAddress" [email protected] --Asrf456BGe4h Content-Disposition: form-data; name="MessageTitle" Good news --Asrf456BGe4h Content-Disposition: form-data; name="MessageText" See attachments... --Asrf456BGe4h Content-Disposition: form-data; name="AttachedFile1"; filename="horror-photo-${"\u0422"}.jpg" Content-Type: image/jpeg JFIF first --Asrf456BGe4h Content-Disposition: form-data; name="AttachedFile2"; filename="horror-photo-2.jpg" Content-Type: image/jpeg JFIF second --Asrf456BGe4h-- epilogue """.trimIndent() .lines() .joinToString("\r\n") val ch = ByteReadChannel(body.toByteArray()) val request = parseRequest(ch)!! val mp = parseMultipart(ch, request.headers) val allEvents = ArrayList<MultipartEvent>() mp.consumeEach { allEvents.add(it) } assertEquals(7, allEvents.size) val preamble = allEvents[0] as MultipartEvent.Preamble assertEquals("preamble\r\n", preamble.body.readText()) val recipient = allEvents[1] as MultipartEvent.MultipartPart assertEquals("[email protected]", recipient.body.readRemaining().readText()) val title = allEvents[2] as MultipartEvent.MultipartPart assertEquals("Good news", title.body.readRemaining().readText()) val text = allEvents[3] as MultipartEvent.MultipartPart assertEquals("See attachments...", text.body.readRemaining().readText()) val jpeg1 = allEvents[4] as MultipartEvent.MultipartPart assertEquals("JFIF first", jpeg1.body.readRemaining().readText()) val jpeg2 = allEvents[5] as MultipartEvent.MultipartPart assertEquals("JFIF second", jpeg2.body.readRemaining().readText()) } @Test fun smokeTestFirefox() = runBlocking { // captured from Firefox val body = """ POST /mp HTTP/1.1 Host: localhost:9096 User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:56.0) Gecko/20100101 Firefox/56.0 Accept-Language: ru-RU,ru;q=0.5 Accept-Encoding: gzip, deflate Referer: http://localhost:9096/mp Content-Type: multipart/form-data; boundary=---------------------------13173666125065307431959751823 Content-Length: 712 Connection: keep-alive Upgrade-Insecure-Requests: 1 Pragma: no-cache Cache-Control: no-cache -----------------------------13173666125065307431959751823 Content-Disposition: form-data; name="title" Hello -----------------------------13173666125065307431959751823 Content-Disposition: form-data; name="body"; filename="bug" Content-Type: application/octet-stream Let's assume we have cwd `/absolute/path/to/dir`, there is node_modules and webpack.config.js on the right place. ``` "resolve": { "modules": [ "node_modules" // this works well //"/absolute/path/to/dir/node_modules" // this doens't ] } ``` plain webpack works well with both but webpack-dev-server fails with error -----------------------------13173666125065307431959751823-- """.trimIndent() .lines() .joinToString("\r\n") val ch = ByteReadChannel(body.toByteArray()) val request = parseRequest(ch)!! val mp = parseMultipart(ch, request.headers) val allEvents = ArrayList<MultipartEvent>() @OptIn(ExperimentalCoroutinesApi::class) mp.consumeEach { allEvents.add(it) } val parts = allEvents.filterIsInstance<MultipartEvent.MultipartPart>() val title = parts.getOrNull(0) ?: fail("No title part found") val file = parts.getOrNull(1) ?: fail("No file part found") assertEquals("Hello", title.body.readRemaining().readText()) val fileContent = file.body.readRemaining().readText() // println(fileContent) assertEquals(380, fileContent.length) } @OptIn(DelicateCoroutinesApi::class) @Test fun testMultipartFormDataChunkedEncoded() = runBlocking { val body = """ POST /send-message.html HTTP/1.1 Content-Type: multipart/form-data; boundary=Asrf456BGe4h Connection: keep-alive Transfer-Encoding: chunked 248 preamble --Asrf456BGe4h Content-Disposition: form-data; name="DestAddress" [email protected] --Asrf456BGe4h Content-Disposition: form-data; name="MessageTitle" Good news --Asrf456BGe4h Content-Disposition: form-data; name="MessageText" See attachments... --Asrf456BGe4h Content-Disposition: form-data; name="AttachedFile1"; filename="horror-photo-1.jpg" Content-Type: image/jpeg JFIF first --Asrf456BGe4h Content-Disposition: form-data; name="AttachedFile2"; filename="horror-photo-2.jpg" Content-Type: image/jpeg JFIF second --Asrf456BGe4h-- epilogue 0 """.trimIndent() .lines() .joinToString("\r\n", postfix = "\r\n\r\n") val ch = ByteReadChannel(body.toByteArray()) val request = parseRequest(ch)!! val decoded = GlobalScope.decodeChunked(ch, -1L) val mp = GlobalScope.parseMultipart(decoded.channel, request.headers) val allEvents = ArrayList<MultipartEvent>() @OptIn(ExperimentalCoroutinesApi::class) mp.consumeEach { allEvents.add(it) } assertEquals(7, allEvents.size) val preamble = allEvents[0] as MultipartEvent.Preamble assertEquals("preamble\r\n", preamble.body.readText()) val recipient = allEvents[1] as MultipartEvent.MultipartPart assertEquals("[email protected]", recipient.body.readRemaining().readText()) val title = allEvents[2] as MultipartEvent.MultipartPart assertEquals("Good news", title.body.readRemaining().readText()) val text = allEvents[3] as MultipartEvent.MultipartPart assertEquals("See attachments...", text.body.readRemaining().readText()) val jpeg1 = allEvents[4] as MultipartEvent.MultipartPart assertEquals("JFIF first", jpeg1.body.readRemaining().readText()) val jpeg2 = allEvents[5] as MultipartEvent.MultipartPart assertEquals("JFIF second", jpeg2.body.readRemaining().readText()) val epilogue = allEvents[6] as MultipartEvent.Epilogue assertEquals("epilogue", epilogue.body.readText()) } @Test fun testParseBoundary() { testBoundary("\r\n--A", "multipart/mixed;boundary=A") testBoundary("\r\n--A", "multipart/mixed; boundary=A") testBoundary("\r\n--A", "multipart/mixed; boundary=A") testBoundary("\r\n--AB", "multipart/mixed; boundary=AB") testBoundary("\r\n--A", "multipart/mixed; boundary=A ") testBoundary("\r\n--AB", "multipart/mixed; boundary=AB ") testBoundary("\r\n--AB", "multipart/mixed; boundary=AB c") testBoundary("\r\n--A", "multipart/mixed; boundary=A,") testBoundary("\r\n--AB", "multipart/mixed; boundary=AB,") testBoundary("\r\n--AB", "multipart/mixed; boundary=AB,c") testBoundary("\r\n--A", "multipart/mixed; boundary=A;") testBoundary("\r\n--A", "multipart/mixed; boundary=A;b") testBoundary("\r\n--AB", "multipart/mixed; boundary=AB;") testBoundary("\r\n--AB", "multipart/mixed; boundary=AB;c") testBoundary("\r\n--A", "multipart/mixed; boundary= A;") testBoundary("\r\n--A", "multipart/mixed; boundary= A;b") testBoundary("\r\n--A", "multipart/mixed; boundary= A,") testBoundary("\r\n--A", "multipart/mixed; boundary= A,b") testBoundary("\r\n--A", "multipart/mixed; boundary= A ") testBoundary("\r\n--A", "multipart/mixed; boundary= A b") testBoundary("\r\n--Ab", "multipart/mixed; boundary= Ab") testBoundary("\r\n-- A\"", "multipart/mixed; boundary=\" A\\\"\"") testBoundary("\r\n--A", "multipart/mixed; boundary= \"A\"") testBoundary("\r\n--A", "multipart/mixed; boundary=\"A\" ") testBoundary("\r\n--A", "multipart/mixed; a_boundary=\"boundary=z\"; boundary=A") testBoundary( "\r\n--" + "0".repeat(70), "multipart/mixed; boundary=" + "0".repeat(70) ) assertFails { parseBoundaryInternal("multipart/mixed; boundary=" + "0".repeat(71)) } assertFails { parseBoundaryInternal("multipart/mixed; boundary=") } assertFails { parseBoundaryInternal("multipart/mixed; boundary= ") } assertFails { parseBoundaryInternal("multipart/mixed; boundary= \"\" ") } } @OptIn(DelicateCoroutinesApi::class) @Test fun testEmptyPayload() = runBlocking { val body = "POST /add HTTP/1.1\r\n" + "Host: 127.0.0.1:8080\r\n" + "User-Agent: curl/7.46.0\r\n" + "Accept: */*\r\n" + "Content-Type: multipart/form-data; " + "boundary=------------------------abcdef" + "\r\n\r\n" val ch = ByteReadChannel(body.toByteArray()) val request = parseRequest(ch)!! val mp = GlobalScope.parseMultipart(ch, request.headers) mp.consumeEach { fail("Should be no events") } } @Test fun testEpilogueOnly() = runBlocking { val body = "POST /add HTTP/1.1\r\n" + "Host: 127.0.0.1:8080\r\n" + "User-Agent: curl/7.46.0\r\n" + "Accept: */*\r\n" + "Content-Type: multipart/form-data; " + "boundary=abcdef" + "\r\n\r\n" + "--abcdef--" val ch = ByteReadChannel(body.toByteArray()) val request = parseRequest(ch)!! val mp = GlobalScope.parseMultipart(ch, request.headers) mp.consumeEach { fail("Should be no events but got $it") } } @Test fun testEpilogueOnlyAndDoubleLine() = runBlocking { val body = "POST /add HTTP/1.1\r\n" + "Host: 127.0.0.1:8080\r\n" + "User-Agent: curl/7.46.0\r\n" + "Accept: */*\r\n" + "Content-Type: multipart/form-data; " + "boundary=abcdef" + "\r\n\r\n" + "--abcdef--\r\n\r\n" val ch = ByteReadChannel(body.toByteArray()) val request = parseRequest(ch)!! val mp = GlobalScope.parseMultipart(ch, request.headers) mp.consumeEach { fail("Should be no events but got $it") } } @Test fun testNoCRLFAfterBoundaryDelimiter() { val body = "--boundary\r\n" + "Content-Disposition: form-data; name=\"key\"\r\n\r\n" + "value\r\n" + "--boundary--" val input = ByteReadChannel(body.toByteArray()) runBlocking { val events = parseMultipart( input, "multipart/form-data; boundary=boundary", body.length.toLong() ).toList() assertEquals(1, events.size) assertEquals("value", (events[0] as MultipartEvent.MultipartPart).body.readRemaining().readText()) } } private fun testBoundary(expectedBoundary: String, headerValue: String) { val boundary = parseBoundaryInternal(headerValue) val actualBoundary = String( boundary.array(), boundary.arrayOffset() + boundary.position(), boundary.remaining() ) assertEquals(expectedBoundary, actualBoundary) } }
apache-2.0
2f4e24ad86f04b65882eab364a76ccf0
35.037037
125
0.586074
4.15479
false
true
false
false
voxelcarrot/Warren
src/main/kotlin/engineer/carrot/warren/warren/extension/cap/CapManager.kt
2
3147
package engineer.carrot.warren.warren.extension.cap import engineer.carrot.warren.kale.IKale import engineer.carrot.warren.warren.IMessageSink import engineer.carrot.warren.warren.extension.account_notify.AccountNotifyExtension import engineer.carrot.warren.warren.extension.away_notify.AwayNotifyExtension import engineer.carrot.warren.warren.extension.extended_join.ExtendedJoinExtension import engineer.carrot.warren.warren.extension.sasl.SaslExtension import engineer.carrot.warren.warren.extension.sasl.SaslState import engineer.carrot.warren.warren.handler.CapAckHandler import engineer.carrot.warren.warren.handler.CapLsHandler import engineer.carrot.warren.warren.handler.CapNakHandler import engineer.carrot.warren.warren.state.CaseMappingState import engineer.carrot.warren.warren.state.ChannelsState import engineer.carrot.warren.warren.state.IStateCapturing data class CapState(var lifecycle: CapLifecycle, var negotiate: Set<String>, var server: Map<String, String?>, var accepted: Set<String>, var rejected: Set<String>) enum class CapLifecycle { NEGOTIATING, NEGOTIATED, FAILED } interface ICapManager : IStateCapturing<CapState> { fun capEnabled(name: String) fun capDisabled(name: String) } enum class CapKeys(val key: String) { SASL("sasl"), ACCOUNT_NOTIFY("account-notify"), AWAY_NOTIFY("away-notify"), EXTENDED_JOIN("extended-join"), MULTI_PREFIX("multi-prefix"), } class CapManager(initialState: CapState, private val kale: IKale, channelsState: ChannelsState, initialSaslState: SaslState, sink: IMessageSink, caseMappingState: CaseMappingState) : ICapManager, ICapExtension { internal var internalState: CapState = initialState @Volatile override var state: CapState = initialState.copy() val sasl = SaslExtension(initialSaslState, kale, internalState, sink) private val capLsHandler: CapLsHandler by lazy { CapLsHandler(internalState, sasl.internalState, sink) } private val capAckHandler: CapAckHandler by lazy { CapAckHandler(internalState, sasl.internalState, sink, this) } private val capNakHandler: CapNakHandler by lazy { CapNakHandler(internalState, sasl.internalState, sink, this) } private val capExtensions = mapOf( CapKeys.SASL.key to sasl, CapKeys.ACCOUNT_NOTIFY.key to AccountNotifyExtension(kale, channelsState.joined), CapKeys.AWAY_NOTIFY.key to AwayNotifyExtension(kale, channelsState.joined), CapKeys.EXTENDED_JOIN.key to ExtendedJoinExtension(kale, channelsState, caseMappingState) ) override fun captureStateSnapshot() { state = internalState.copy() sasl.captureStateSnapshot() } override fun capEnabled(name: String) { capExtensions[name]?.setUp() } override fun capDisabled(name: String) { capExtensions[name]?.tearDown() } override fun setUp() { kale.register(capLsHandler) kale.register(capAckHandler) kale.register(capNakHandler) } override fun tearDown() { kale.unregister(capLsHandler) kale.unregister(capAckHandler) kale.unregister(capNakHandler) } }
isc
b6975ecd6f785081f3f73c38dcc04198
38.35
211
0.760089
3.968474
false
false
false
false
fabianonline/telegram_backup
src/main/kotlin/de/fabianonline/telegram_backup/Config.kt
1
1887
/* Telegram_Backup * Copyright (C) 2016 Fabian Schlenz * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.fabianonline.telegram_backup import java.io.File import java.io.IOException import java.io.FileInputStream import java.util.Properties object Config { val APP_ID = 32860 val APP_HASH = "16e4ff955cd0adfc058f95ca564f562d" val APP_MODEL = "Desktop" val APP_SYSVER = "1.0" val APP_APPVER: String val APP_LANG = "en" var TARGET_DIR = System.getProperty("user.home") + File.separatorChar + ".telegram_backup" val FILE_NAME_AUTH_KEY = "auth.dat" val FILE_NAME_DC = "dc.dat" val FILE_NAME_DB = "database.sqlite" val FILE_NAME_DB_BACKUP = "database.version_%d.backup.sqlite" val FILE_FILES_BASE = "files" val FILE_STICKER_BASE = "stickers" var DELAY_AFTER_GET_MESSAGES: Long = 400 var DELAY_AFTER_GET_FILE: Long = 100 var GET_MESSAGES_BATCH_SIZE = 200 var RENAMING_MAX_TRIES = 5 var RENAMING_DELAY: Long = 1000 var DEFAULT_PAGINATION = 5_000 val SECRET_GMAPS = "AI" + "za" + "SyD_" + "c0DKsfCXqgG" + "z0Sip7KHsBCU-paBfeJk" init { val p = Properties() try { p.load(Config::class.java.getResourceAsStream("/build.properties")) APP_APPVER = p.getProperty("version") } catch (e: IOException) { throw RuntimeException(e) } } }
gpl-3.0
95084e1aa65601b0378ab761ec225a5b
29.435484
91
0.719661
3.134551
false
false
false
false
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/user/internal/LogInCall.kt
1
9061
/* * 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.user.internal import dagger.Reusable import io.reactivex.Single import javax.inject.Inject import net.openid.appauth.AuthState import org.hisp.dhis.android.core.arch.api.executors.internal.APICallExecutor import org.hisp.dhis.android.core.arch.api.internal.ServerURLWrapper import org.hisp.dhis.android.core.arch.db.access.DatabaseAdapter import org.hisp.dhis.android.core.arch.db.stores.internal.IdentifiableObjectStore import org.hisp.dhis.android.core.arch.db.stores.internal.ObjectWithoutUidStore import org.hisp.dhis.android.core.arch.handlers.internal.Handler import org.hisp.dhis.android.core.arch.repositories.collection.ReadOnlyWithDownloadObjectRepository import org.hisp.dhis.android.core.arch.storage.internal.Credentials import org.hisp.dhis.android.core.arch.storage.internal.CredentialsSecureStore import org.hisp.dhis.android.core.arch.storage.internal.UserIdInMemoryStore import org.hisp.dhis.android.core.configuration.internal.ServerUrlParser import org.hisp.dhis.android.core.maintenance.D2Error import org.hisp.dhis.android.core.maintenance.D2ErrorCode import org.hisp.dhis.android.core.systeminfo.SystemInfo import org.hisp.dhis.android.core.user.AccountDeletionReason import org.hisp.dhis.android.core.user.AuthenticatedUser import org.hisp.dhis.android.core.user.User import org.hisp.dhis.android.core.user.UserInternalAccessor @Reusable @Suppress("LongParameterList") internal class LogInCall @Inject internal constructor( private val databaseAdapter: DatabaseAdapter, private val apiCallExecutor: APICallExecutor, private val userService: UserService, private val credentialsSecureStore: CredentialsSecureStore, private val userIdStore: UserIdInMemoryStore, private val userHandler: Handler<User>, private val authenticatedUserStore: ObjectWithoutUidStore<AuthenticatedUser>, private val systemInfoRepository: ReadOnlyWithDownloadObjectRepository<SystemInfo>, private val userStore: IdentifiableObjectStore<User>, private val apiCallErrorCatcher: UserAuthenticateCallErrorCatcher, private val databaseManager: LogInDatabaseManager, private val exceptions: LogInExceptions, private val accountManager: AccountManagerImpl ) { fun logIn(username: String?, password: String?, serverUrl: String?): Single<User> { return Single.fromCallable { blockingLogIn(username, password, serverUrl) } } @Throws(D2Error::class) private fun blockingLogIn(username: String?, password: String?, serverUrl: String?): User { exceptions.throwExceptionIfUsernameNull(username) exceptions.throwExceptionIfPasswordNull(password) exceptions.throwExceptionIfAlreadyAuthenticated() val trimmedServerUrl = ServerUrlParser.trimAndRemoveTrailingSlash(serverUrl) val parsedServerUrl = ServerUrlParser.parse(trimmedServerUrl) ServerURLWrapper.setServerUrl(parsedServerUrl.toString()) val authenticateCall = userService.authenticate( okhttp3.Credentials.basic(username!!, password!!), UserFields.allFieldsWithoutOrgUnit ) val credentials = Credentials(username, trimmedServerUrl!!, password, null) return try { val user = apiCallExecutor.executeObjectCallWithErrorCatcher(authenticateCall, apiCallErrorCatcher) loginOnline(user, credentials) } catch (d2Error: D2Error) { if (d2Error.isOffline) { tryLoginOffline(credentials, d2Error) } else { throw handleOnlineException(d2Error, credentials) } } } @Suppress("TooGenericExceptionCaught") private fun handleOnlineException(d2Error: D2Error, credentials: Credentials?): D2Error { return if (d2Error.errorCode() == D2ErrorCode.USER_ACCOUNT_DISABLED) { try { if (credentials != null) { accountManager.deleteAccountAndEmit(credentials, AccountDeletionReason.ACCOUNT_DISABLED) } d2Error } catch (e: Exception) { d2Error } } else if (d2Error.errorCode() == D2ErrorCode.UNEXPECTED || d2Error.errorCode() == D2ErrorCode.API_RESPONSE_PROCESS_ERROR ) { exceptions.noDHIS2Server() } else { d2Error } } @Suppress("TooGenericExceptionCaught") private fun loginOnline(user: User, credentials: Credentials): User { credentialsSecureStore.set(credentials) userIdStore.set(user.uid()) databaseManager.loadDatabaseOnline(credentials.serverUrl, credentials.username).blockingAwait() val transaction = databaseAdapter.beginNewTransaction() return try { val authenticatedUser = AuthenticatedUser.builder() .user(user.uid()) .hash(credentials.getHash()) .build() authenticatedUserStore.updateOrInsertWhere(authenticatedUser) systemInfoRepository.download().blockingAwait() userHandler.handle(user) transaction.setSuccessful() user } catch (e: Exception) { // Credentials are stored and then removed in case of error since they are required to download system info credentialsSecureStore.remove() userIdStore.remove() throw e } finally { transaction.end() } } @Throws(D2Error::class) @Suppress("ThrowsCount") private fun tryLoginOffline(credentials: Credentials, originalError: D2Error): User { val existingDatabase = databaseManager.loadExistingKeepingEncryption(credentials.serverUrl, credentials.username) if (!existingDatabase) { throw originalError } val existingUser = authenticatedUserStore.selectFirst() ?: throw exceptions.noUserOfflineError() if (credentials.getHash() != existingUser.hash()) { throw exceptions.badCredentialsError() } credentialsSecureStore.set(credentials) userIdStore.set(existingUser.user()!!) return userStore.selectByUid(existingUser.user()!!)!! } @Throws(D2Error::class) fun blockingLogInOpenIDConnect(serverUrl: String, openIDConnectState: AuthState): User { val trimmedServerUrl = ServerUrlParser.trimAndRemoveTrailingSlash(serverUrl) val parsedServerUrl = ServerUrlParser.parse(trimmedServerUrl) ServerURLWrapper.setServerUrl(parsedServerUrl.toString()) val authenticateCall = userService.authenticate( "Bearer ${openIDConnectState.idToken}", UserFields.allFieldsWithoutOrgUnit ) var credentials: Credentials? = null return try { val user = apiCallExecutor.executeObjectCallWithErrorCatcher(authenticateCall, apiCallErrorCatcher) credentials = getOpenIdConnectCredentials(user, trimmedServerUrl!!, openIDConnectState) loginOnline(user, credentials) } catch (d2Error: D2Error) { throw handleOnlineException(d2Error, credentials) } } private fun getOpenIdConnectCredentials(user: User, serverUrl: String, openIDConnectState: AuthState): Credentials { val username = UserInternalAccessor.accessUserCredentials(user).username()!! return Credentials(username, serverUrl, null, openIDConnectState) } }
bsd-3-clause
bba252c4bbba9fbca7ac93453b795862
44.994924
120
0.721775
4.784055
false
false
false
false
android/project-replicator
plugin/src/main/kotlin/com/android/gradle/replicator/ResourceDataGathering.kt
1
4811
package com.android.gradle.replicator import com.android.gradle.replicator.model.internal.filedata.* import com.android.utils.XmlUtils import org.xml.sax.Attributes import org.xml.sax.InputSource import org.xml.sax.Locator import org.xml.sax.SAXParseException import org.xml.sax.helpers.DefaultHandler import java.io.File import java.io.StringReader import javax.xml.parsers.SAXParserFactory // Method to create the correct data class. Need to make this so it scans the files appropriately fun processResourceFiles(resourceType: String, qualifiers: String, extension: String, resourceFiles: Set<File>): AbstractAndroidResourceProperties { return when (resourceType) { "values" -> getValuesResourceData(qualifiers, extension, resourceFiles) else -> getDefaultResourceData(qualifiers, extension, resourceFiles) } } // Methods to parse specific resource types // Parses values xml files and counts each type of value fun getValuesResourceData(qualifiers: String, extension: String, resourceFiles: Set<File>): ValuesAndroidResourceProperties { return ValuesAndroidResourceProperties( qualifiers = qualifiers, extension = extension, quantity = resourceFiles.size, valuesMapPerFile = mutableListOf<ValuesMap>().apply { resourceFiles.forEach { this.add(parseValuesFile(it)) } } ) } fun getDefaultResourceData(qualifiers: String, extension: String, resourceFiles: Set<File>): DefaultAndroidResourceProperties { return DefaultAndroidResourceProperties( qualifiers = qualifiers, extension = extension, quantity = resourceFiles.size, fileData = mutableListOf<Long>().apply { // XML files want lines instead of bytes if (extension == "xml") { resourceFiles.forEach { this.add(it.readLines().size.toLong()) } } else { resourceFiles.forEach { this.add(it.length()) } } } ) } fun parseValuesFile(valuesFile: File): ValuesMap { val valuesMap = ValuesMap() val handler: DefaultHandler = object : DefaultHandler() { private var myDepth = 0 private var myLocator: Locator? = null private var currentItemCount = 0 override fun setDocumentLocator(locator: Locator) { myLocator = locator } override fun startElement( uri: String, localName: String, qName: String, attributes: Attributes ) { myDepth++ if (myDepth == 3 && qName == "item") { currentItemCount++ } if (myDepth == 2) { when (qName) { "string" -> { valuesMap.stringCount++ } "int" -> { valuesMap.intCount++ } "bool" -> { valuesMap.boolCount++ } "color" -> { valuesMap.colorCount++ } "dimen" -> { valuesMap.dimenCount++ } "item" -> { if (attributes.getValue("type") == "id") { valuesMap.idCount++ } } "integer-array" -> {} // Only add on close "array" -> {} // Only add on close "style" -> {} // Only add on close else -> {} // Ignore } } } override fun endElement(uri: String, localName: String, qName: String) { if (myDepth == 2) { when (qName) { "integer-array" -> { valuesMap.integerArrayCount.add(currentItemCount) } "array" -> { valuesMap.arrayCount.add(currentItemCount) } "style" -> { valuesMap.styleCount.add(currentItemCount) } else -> { } } currentItemCount = 0 } myDepth-- } } val factory = SAXParserFactory.newInstance() // Parse the input XmlUtils.configureSaxFactory(factory, false, false) val saxParser = XmlUtils.createSaxParser(factory) try { saxParser.parse(InputSource(StringReader(valuesFile.readText())), handler) } catch (e: SAXParseException) { println("e: Invalid xml file $valuesFile") println(" line ${e.lineNumber}; column ${e.columnNumber}: ${e.message}") println(" ${valuesFile.readLines()[e.lineNumber-1]}") println(" ${" ".repeat(e.columnNumber-1)}↑") println( "Skipping file parsing") return ValuesMap() // Return empty map } return valuesMap }
apache-2.0
d928d4108d1923d65b15efa411cb5231
35.165414
125
0.56519
4.804196
false
false
false
false
drakelord/wire
wire-java-generator/src/test/java/com/squareup/wire/java/internal/ProfileParserTest.kt
1
4303
/* * Copyright (C) 2016 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire.java.internal import com.squareup.wire.schema.Location import com.squareup.wire.schema.internal.parser.OptionElement import org.assertj.core.api.Assertions.assertThat import org.junit.Assert.fail import org.junit.Test class ProfileParserTest { private var location = Location.get("android.wire") @Test fun parseType() { val proto = """ |syntax = "wire2"; |package squareup.dinosaurs; | |import "squareup/geology/period.proto"; | |/* Roar! */ |type squareup.dinosaurs.Dinosaur { | target com.squareup.dino.Dinosaur using com.squareup.dino.Dinosaurs#DINO_ADAPTER; |} | |type squareup.geology.Period { | with custom_type = "duration"; | target java.time.Period using com.squareup.time.Time#PERIOD_ADAPTER; |} """.trimMargin() val expected = ProfileFileElement( location = location, packageName = "squareup.dinosaurs", imports = listOf("squareup/geology/period.proto"), typeConfigs = listOf( TypeConfigElement( location = location.at(7, 1), documentation = "Roar!", type = "squareup.dinosaurs.Dinosaur", target = "com.squareup.dino.Dinosaur", adapter = "com.squareup.dino.Dinosaurs#DINO_ADAPTER" ), TypeConfigElement( location = location.at(11, 1), type = "squareup.geology.Period", with = listOf( OptionElement.create( "custom_type", OptionElement.Kind.STRING, "duration" ) ), target = "java.time.Period", adapter = "com.squareup.time.Time#PERIOD_ADAPTER" ) ) ) val parser = ProfileParser(location, proto) assertThat(parser.read()).isEqualTo(expected) } @Test fun invalidSyntax() { val proto = """ |syntax = "proto2"; | |type squareup.dinosaurs.Dinosaur { | target com.squareup.dino.Dinosaur using com.squareup.dino.Dinosaurs#DINO_ADAPTER; |} """.trimMargin() val parser = ProfileParser(location, proto) try { parser.read() fail() } catch (expected: IllegalStateException) { assertThat(expected).hasMessage("Syntax error in android.wire at 1:18: expected 'wire2'") } } @Test fun tooManyTargets() { val proto = """ |syntax = "wire2"; | |type squareup.dinosaurs.Dinosaur { | target com.squareup.dino.Herbivore using com.squareup.dino.Dinosaurs#PLANT_ADAPTER; | target com.squareup.dino.Carnivore using com.squareup.dino.Dinosaurs#MEAT_ADAPTER; |} """.trimMargin() val parser = ProfileParser(location, proto) try { parser.read() fail() } catch (expected: IllegalStateException) { assertThat(expected).hasMessage("Syntax error in android.wire at 5:3: too many targets") } } @Test fun readAndWriteRoundTrip() { val proto = """ |// android.wire |syntax = "wire2"; |package squareup.dinosaurs; | |import "squareup/geology/period.proto"; | |// Roar! |type squareup.dinosaurs.Dinosaur { | target com.squareup.dino.Dinosaur using com.squareup.dino.Dinosaurs#DINO_ADAPTER; |} |type squareup.geology.Period { | with custom_type = "duration"; | target java.time.Period using com.squareup.time.Time#PERIOD_ADAPTER; |} |""".trimMargin() val parser = ProfileParser(location, proto) assertThat(parser.read().toSchema()).isEqualTo(proto) } }
apache-2.0
5b54f5d490dc7ca84e8de47a0e3b465d
30.408759
95
0.615849
3.841964
false
false
false
false
ogarcia/ultrasonic
core/subsonic-api/src/main/kotlin/org/moire/ultrasonic/api/subsonic/models/Album.kt
2
514
package org.moire.ultrasonic.api.subsonic.models import com.fasterxml.jackson.annotation.JsonProperty import java.util.Calendar data class Album( val id: String = "", val name: String = "", val coverArt: String = "", val artist: String = "", val artistId: String = "", val songCount: Int = 0, val duration: Int = 0, val created: Calendar? = null, val year: Int = 0, val genre: String = "", @JsonProperty("song") val songList: List<MusicDirectoryChild> = emptyList() )
gpl-3.0
5c6952fea250603b50353960c83438c2
27.555556
79
0.651751
3.864662
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/proxy/CoroutineDebugProbesProxy.kt
5
2575
// 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.proxy import com.intellij.debugger.engine.DebuggerManagerThreadImpl import com.intellij.debugger.engine.SuspendContextImpl import com.intellij.openapi.util.registry.Registry import org.jetbrains.kotlin.idea.debugger.coroutine.CoroutinesInfoFromJsonAndReferencesProvider import org.jetbrains.kotlin.idea.debugger.coroutine.data.CoroutineInfoCache import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.mirror.DebugProbesImpl import org.jetbrains.kotlin.idea.debugger.coroutine.util.executionContext import org.jetbrains.kotlin.idea.debugger.coroutine.util.logger import org.jetbrains.kotlin.idea.debugger.evaluate.DefaultExecutionContext class CoroutineDebugProbesProxy(val suspendContext: SuspendContextImpl) { /** * Invokes DebugProbes from debugged process's classpath and returns states of coroutines * Should be invoked on debugger manager thread */ @Synchronized fun dumpCoroutines(): CoroutineInfoCache { DebuggerManagerThreadImpl.assertIsManagerThread() val coroutineInfoCache = CoroutineInfoCache() try { val executionContext = suspendContext.executionContext() ?: return coroutineInfoCache.fail() val libraryAgentProxy = findProvider(executionContext) ?: return coroutineInfoCache.ok() val infoList = libraryAgentProxy.dumpCoroutinesInfo() coroutineInfoCache.ok(infoList) } catch (e: Throwable) { log.error("Exception is thrown by calling dumpCoroutines.", e) coroutineInfoCache.fail() } return coroutineInfoCache } private fun findProvider(executionContext: DefaultExecutionContext): CoroutineInfoProvider? { val debugProbesImpl = DebugProbesImpl.instance(executionContext) return when { debugProbesImpl != null && debugProbesImpl.isInstalled -> CoroutinesInfoFromJsonAndReferencesProvider.instance(executionContext, debugProbesImpl) ?: CoroutineLibraryAgent2Proxy(executionContext, debugProbesImpl) standaloneCoroutineDebuggerEnabled() -> CoroutineNoLibraryProxy(executionContext) else -> null } } companion object { private val log by logger } } fun standaloneCoroutineDebuggerEnabled() = Registry.`is`("kotlin.debugger.coroutines.standalone")
apache-2.0
8ca1b5ba69cc9d710faf53087cf2c5a4
47.584906
158
0.744078
5.443975
false
false
false
false
elpassion/el-space-android
el-space-app/src/main/java/pl/elpassion/elspace/hub/report/list/ReportListController.kt
1
5129
package pl.elpassion.elspace.hub.report.list import io.reactivex.Observable import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.Observables import io.reactivex.rxkotlin.addTo import io.reactivex.schedulers.Schedulers import pl.elpassion.elspace.common.SchedulersSupplier import pl.elpassion.elspace.common.extensions.* import pl.elpassion.elspace.hub.report.Report import pl.elpassion.elspace.hub.report.list.adapter.addSeparators import pl.elpassion.elspace.hub.report.list.service.DateChangeObserver import pl.elpassion.elspace.hub.report.list.service.DayFilter import pl.elpassion.elspace.hub.report.list.service.ReportDayService class ReportListController(private val reportDayService: ReportDayService, private val dayFilter: DayFilter, private val actions: ReportList.Actions, private val view: ReportList.View, private val schedulers: SchedulersSupplier) { private val subscriptions = CompositeDisposable() private val dateChangeObserver by lazy { DateChangeObserver(getCurrentTimeCalendar()) } private val todayPositionObserver = TodayPositionObserver() private val calendar = getCurrentTimeCalendar() fun onCreate() { fetchReports() subscribeDateChange() Observable.merge( actions.reportAdd().doOnNext { view.openAddReportScreen(calendar.getDateString()) }, actions.monthChangeToNext().doOnNext { dateChangeObserver.setNextMonth() }, actions.monthChangeToPrev().doOnNext { dateChangeObserver.setPreviousMonth() }, actions.scrollToCurrent().doOnNext { onToday() }) .subscribe() .addTo(subscriptions) } fun updateLastPassedDayPosition(position: Int) { if (isCurrentYearAndMonth()) { todayPositionObserver.updatePosition(position) } } fun onDestroy() { subscriptions.clear() } fun onDayClick(date: String) { view.openAddReportScreen(date) } fun onReportClick(report: Report) = view.openEditReportScreen(report) private fun onToday() { if (isCurrentYearAndMonth()) { scrollToTodayPosition(todayPositionObserver.lastPosition) } else { dateChangeObserver.setYearMonth(calendar.year, calendar.month) todayPositionObserver.observe().filter { it != -1 } .subscribe { scrollToTodayPosition(it) }.addTo(subscriptions) } } private fun scrollToTodayPosition(todayPosition: Int) { if (todayPosition != -1) { view.scrollToPosition(todayPosition) } } private fun fetchReports() { Observables.combineLatest(fetchDays(), actions.reportsFilter(), { list: List<Day>, shouldFilter: Boolean -> when (shouldFilter) { true -> dayFilter.fetchFilteredDays(list) else -> list } }) .subscribe({ days -> createAdapterItems(days) }, { }) .addTo(subscriptions) } private fun createAdapterItems(days: List<Day>) { val adapterItems = getDaysAndReportsAsAdapterItems(days) val adapterItemsWithSeparators = addSeparators(adapterItems) view.showDays(adapterItemsWithSeparators) } private fun getDaysAndReportsAsAdapterItems(days: List<Day>) = mutableListOf<AdapterItem>().apply { days.forEach { add(it) when (it) { is DayWithHourlyReports -> it.reports.forEach { add(it) } } } } private fun refreshingDataObservable() = Observable.merge(Observable.just(Unit), actions.resultRefresh(), actions.refreshingEvents(), actions.snackBarRetry()) private fun fetchDays() = refreshingDataObservable() .switchMap { reportDayService.createDays(dateChangeObserver.observe().observeOn(Schedulers.io())) .subscribeOn(schedulers.backgroundScheduler) .observeOn(schedulers.uiScheduler) .doOnSubscribe { if (!view.isDuringPullToRefresh()) { view.showLoader() } } .doOnNext { view.hideLoader() } .catchOnError { view.hideLoader() view.showError(it) } } private fun subscribeDateChange() { dateChangeObserver.observe() .subscribe { view.showMonthName(it.month.monthName) } .addTo(subscriptions) } private fun isCurrentYearAndMonth() = dateChangeObserver.lastDate.let { it.year == calendar.year && it.month.index == calendar.month } } typealias OnDayClick = (String) -> Unit typealias OnReportClick = (Report) -> Unit
gpl-3.0
715833ad981d1dd227ec52a5b26b720f
37.283582
103
0.61162
5.134134
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/cognito/src/main/kotlin/com/kotlin/cognito/ListUserPoolClients.kt
1
1965
// snippet-sourcedescription:[ListUserPoolClients.kt demonstrates how to list existing user pool clients that are available in the specified AWS Region in your current AWS account.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-service:[Amazon Cognito] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.cognito // snippet-start:[cognito.kotlin.ListUserPoolClients.import] import aws.sdk.kotlin.services.cognitoidentityprovider.CognitoIdentityProviderClient import aws.sdk.kotlin.services.cognitoidentityprovider.model.ListUserPoolClientsRequest import kotlin.system.exitProcess // snippet-end:[cognito.kotlin.ListUserPoolClients.import] /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main(args: Array<String>) { val usage = """ Usage: <userPoolId> Where: userPoolId - The ID given to your user pool. """ if (args.size != 1) { println(usage) exitProcess(0) } val userPoolId = args[0] listAllUserPoolClients(userPoolId) } // snippet-start:[cognito.kotlin.ListUserPoolClients.main] suspend fun listAllUserPoolClients(userPoolId: String) { val request = ListUserPoolClientsRequest { this.userPoolId = userPoolId } CognitoIdentityProviderClient { region = "us-east-1" }.use { cognitoClient -> val response = cognitoClient.listUserPoolClients(request) response.userPoolClients?.forEach { pool -> println("Client ID is ${pool.clientId}") println("Client Name is ${pool.clientName}") } } } // snippet-end:[cognito.kotlin.ListUserPoolClients.main]
apache-2.0
b0ff3215c4aac594fca59d8c51e0dd31
31.305085
181
0.702799
3.977733
false
false
false
false
xmartlabs/Android-Base-Project
core/src/androidTest/java/com/xmartlabs/bigbang/core/MetricsExtensionsTest.kt
1
1775
package com.xmartlabs.bigbang.core import android.content.res.Resources import android.util.DisplayMetrics import androidx.annotation.DimenRes import androidx.annotation.Dimension import androidx.test.runner.AndroidJUnit4 import com.xmartlabs.bigbang.core.extensions.displayMetrics import com.xmartlabs.bigbang.core.extensions.dpToPx import com.xmartlabs.bigbang.core.extensions.pxToDp import com.xmartlabs.bigbang.core.extensions.spToPx import org.junit.Assert import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.Mockito import org.mockito.junit.MockitoJUnit @RunWith(AndroidJUnit4::class) class MetricsExtensionsTest { companion object { private val DENSITY = 2.5f } @Rule @JvmField var mockitoRule = MockitoJUnit.rule() @Mock internal lateinit var resources: Resources @Mock internal lateinit var displayMetrics23: DisplayMetrics @Before fun setUp() { displayMetrics23.density = DENSITY displayMetrics23.scaledDensity = DENSITY Mockito.`when`(resources.displayMetrics).thenReturn(displayMetrics23) displayMetrics = displayMetrics23 } @Test fun testDpToPx() { @Dimension(unit = Dimension.DP) val dp = 10 Assert.assertEquals(25, dp.dpToPx) } @Test fun testSpToPx() { @Dimension(unit = Dimension.SP) val sp = 10 Assert.assertEquals(25, sp.spToPx) } @Test fun testDimResToPxInt() { @DimenRes val res = 14 val returned = 12.5f Mockito.`when`(resources.getDimension(res)).thenReturn(returned) Assert.assertEquals(12, resources.getDimension(res).toInt()) } @Test fun testPxToDp() { @Dimension(unit = Dimension.PX) val px = 3.5f Assert.assertEquals(1.4f, px.pxToDp) } }
apache-2.0
467c353adaf67d3e0ea800c12652f1f4
24
73
0.755493
3.918322
false
true
false
false
paplorinc/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/inference/ConstructorCallConstraint.kt
2
2222
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.resolve.processors.inference import com.intellij.psi.PsiClass import com.intellij.psi.PsiType import com.intellij.psi.impl.source.resolve.graphInference.constraints.ConstraintFormula import com.intellij.psi.impl.source.resolve.graphInference.constraints.TypeCompatibilityConstraint import org.jetbrains.plugins.groovy.lang.psi.api.GroovyMethodResult import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrNewExpression class ConstructorCallConstraint(private val leftType: PsiType?, private val expression: GrNewExpression) : GrConstraintFormula() { override fun reduce(session: GroovyInferenceSession, constraints: MutableList<ConstraintFormula>): Boolean { val reference = expression.referenceElement ?: return true val result = reference.advancedResolve() val clazz = result.element as? PsiClass ?: return true val contextSubstitutor = result.contextSubstitutor session.startNestedSession(clazz.typeParameters, contextSubstitutor, expression, result) { nested -> runConstructorSession(nested) if (leftType != null) { val left = nested.substituteWithInferenceVariables(leftType) if (left != null) { val classType = nested.substituteWithInferenceVariables(contextSubstitutor.substitute(clazz.type())) if (classType != null) { nested.addConstraint(TypeCompatibilityConstraint(left, classType)) } } } nested.repeatInferencePhases() } return true } private fun runConstructorSession(classSession: GroovyInferenceSession) { val result = expression.advancedResolve() as? GroovyMethodResult ?: return val mapping = result.candidate?.argumentMapping ?: return classSession.startNestedSession(result.element.typeParameters, result.contextSubstitutor, expression, result) { it.initArgumentConstraints(mapping, classSession.inferenceSubstitution) it.repeatInferencePhases() } } override fun toString(): String = "${expression.text} -> ${leftType?.presentableText}" }
apache-2.0
9a8298c61e113454a788de04699058b6
48.377778
140
0.765527
4.905077
false
false
false
false
paplorinc/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/history/FileHistory.kt
1
21513
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.vcs.log.history import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.Couple import com.intellij.openapi.util.Ref import com.intellij.openapi.util.UnorderedPair import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vcs.FilePath import com.intellij.util.containers.ContainerUtil import com.intellij.util.containers.MultiMap import com.intellij.util.containers.Stack import com.intellij.vcs.log.data.index.VcsLogPathsIndex import com.intellij.vcs.log.data.index.VcsLogPathsIndex.ChangeKind import com.intellij.vcs.log.graph.api.LinearGraph import com.intellij.vcs.log.graph.api.LiteLinearGraph import com.intellij.vcs.log.graph.api.permanent.PermanentCommitsInfo import com.intellij.vcs.log.graph.api.permanent.PermanentGraphInfo import com.intellij.vcs.log.graph.collapsing.CollapsedGraph import com.intellij.vcs.log.graph.impl.facade.* import com.intellij.vcs.log.graph.utils.* import com.intellij.vcs.log.graph.utils.impl.BitSetFlags import gnu.trove.* import java.util.* import java.util.function.BiConsumer internal class FileHistoryBuilder(private val startCommit: Int?, private val startPath: FilePath, private val fileNamesData: FileNamesData) : BiConsumer<LinearGraphController, PermanentGraphInfo<Int>> { val pathsMap = mutableMapOf<Int, MaybeDeletedFilePath>() override fun accept(controller: LinearGraphController, permanentGraphInfo: PermanentGraphInfo<Int>) { val needToRepeat = removeTrivialMerges(controller, permanentGraphInfo, fileNamesData, this::reportTrivialMerges) pathsMap.putAll(refine(controller, startCommit, permanentGraphInfo)) if (needToRepeat) { LOG.info("Some merge commits were not excluded from file history for ${startPath.path}") removeTrivialMerges(controller, permanentGraphInfo, fileNamesData, this::reportTrivialMerges) } } private fun reportTrivialMerges(trivialMerges: Set<Int>) { LOG.debug("Excluding ${trivialMerges.size} trivial merges from history for ${startPath.path}") } private fun refine(controller: LinearGraphController, startCommit: Int?, permanentGraphInfo: PermanentGraphInfo<Int>): Map<Int, MaybeDeletedFilePath> { if (fileNamesData.hasRenames && Registry.`is`("vcs.history.refine")) { val visibleLinearGraph = controller.compiledGraph val (row, path) = startCommit?.let { findAncestorRowAffectingFile(startCommit, visibleLinearGraph, permanentGraphInfo) } ?: Pair(0, MaybeDeletedFilePath(startPath)) if (row >= 0) { val refiner = FileHistoryRefiner(visibleLinearGraph, permanentGraphInfo, fileNamesData) val (paths, excluded) = refiner.refine(row, path) if (!excluded.isEmpty()) { LOG.info("Excluding ${excluded.size} commits from history for ${startPath.path}") val hidden = hideCommits(controller, permanentGraphInfo, excluded) if (!hidden) LOG.error("Could not hide excluded commits from history for ${startPath.path}") } return paths } } return fileNamesData.buildPathsMap() } private fun findAncestorRowAffectingFile(commitId: Int, visibleLinearGraph: LinearGraph, permanentGraphInfo: PermanentGraphInfo<Int>): Pair<Int, MaybeDeletedFilePath> { val existing = MaybeDeletedFilePath(startPath) val deleted = MaybeDeletedFilePath(startPath, true) val isDeleted: Ref<Boolean> = Ref.create(false) val row = findVisibleAncestorRow(commitId, visibleLinearGraph, permanentGraphInfo) { nodeId -> val id = permanentGraphInfo.permanentCommitsInfo.getCommitId(nodeId) when { fileNamesData.affects(id, existing) -> true fileNamesData.affects(id, deleted) -> { isDeleted.set(true) true } else -> false } } ?: -1 return Pair(row, if (isDeleted.get()) deleted else existing) } companion object { private val LOG = Logger.getInstance(FileHistoryBuilder::class.java) } } fun removeTrivialMerges(controller: LinearGraphController, permanentGraphInfo: PermanentGraphInfo<Int>, fileNamesData: FileNamesData, report: (Set<Int>) -> Unit): Boolean { val trivialCandidates = TIntHashSet() val nonTrivialMerges = TIntHashSet() fileNamesData.forEach { _, commit, changes -> if (changes.size() > 1) { if (changes.containsValue(ChangeKind.NOT_CHANGED)) { trivialCandidates.add(commit) } else { nonTrivialMerges.add(commit) } } } // since this code can be executed before refine, there can be commits with several files changed in them // if several files are changed in the merge commit, it can be trivial for one file, but not trivial for the other // in this case we may need to repeat the process after refine val needToRepeat = trivialCandidates.removeAll(nonTrivialMerges) if (!trivialCandidates.isEmpty) { modifyGraph(controller) { collapsedGraph -> val trivialMerges = hideTrivialMerges(collapsedGraph) { nodeId: Int -> trivialCandidates.contains(permanentGraphInfo.permanentCommitsInfo.getCommitId(nodeId)) } if (trivialMerges.isNotEmpty()) report(trivialMerges) fileNamesData.removeAll(trivialMerges.map { permanentGraphInfo.permanentCommitsInfo.getCommitId(it) }) } } return needToRepeat } internal fun hideTrivialMerges(collapsedGraph: CollapsedGraph, isCandidateNodeId: (Int) -> Boolean): Set<Int> { val result = mutableSetOf<Int>() val graph = LinearGraphUtils.asLiteLinearGraph(collapsedGraph.compiledGraph) outer@ for (v in graph.nodesCount() - 1 downTo 0) { val nodeId = collapsedGraph.compiledGraph.getNodeId(v) if (isCandidateNodeId(nodeId)) { val downNodes = graph.getNodes(v, LiteLinearGraph.NodeFilter.DOWN) if (downNodes.size == 1) { result.add(nodeId) hideTrivialMerge(collapsedGraph, graph, v, downNodes.single()) } else if (downNodes.size >= 2) { val sortedParentsIt = downNodes.sortedDescending().iterator() var currentParent = sortedParentsIt.next() while (sortedParentsIt.hasNext()) { val nextParent = sortedParentsIt.next() if (!graph.isAncestor(currentParent, nextParent)) continue@outer currentParent = nextParent } result.add(nodeId) hideTrivialMerge(collapsedGraph, graph, v, currentParent) } } } return result } private fun hideTrivialMerge(collapsedGraph: CollapsedGraph, graph: LiteLinearGraph, node: Int, singleParent: Int) { collapsedGraph.modify { hideRow(node) for (upNode in graph.getNodes(node, LiteLinearGraph.NodeFilter.UP)) { connectRows(upNode, singleParent) } } } internal class FileHistoryRefiner(private val visibleLinearGraph: LinearGraph, permanentGraphInfo: PermanentGraphInfo<Int>, private val namesData: FileNamesData) : Dfs.NodeVisitor { private val permanentCommitsInfo: PermanentCommitsInfo<Int> = permanentGraphInfo.permanentCommitsInfo private val permanentLinearGraph: LiteLinearGraph = LinearGraphUtils.asLiteLinearGraph(permanentGraphInfo.linearGraph) private val paths = Stack<MaybeDeletedFilePath>() private val visibilityBuffer = BitSetFlags(permanentLinearGraph.nodesCount()) // a reusable buffer for bfs private val pathsForCommits = ContainerUtil.newHashMap<Int, MaybeDeletedFilePath>() fun refine(row: Int, startPath: MaybeDeletedFilePath): Pair<HashMap<Int, MaybeDeletedFilePath>, HashSet<Int>> { paths.push(startPath) LinearGraphUtils.asLiteLinearGraph(visibleLinearGraph).walk(row, this) val excluded = ContainerUtil.newHashSet<Int>() pathsForCommits.forEach { commit, path -> if (path != null && !namesData.affects(commit, path, true)) { excluded.add(commit) } } excluded.forEach { pathsForCommits.remove(it) } return Pair(pathsForCommits, excluded) } override fun enterNode(currentNode: Int, previousNode: Int, down: Boolean) { val currentNodeId = visibleLinearGraph.getNodeId(currentNode) val currentCommit = permanentCommitsInfo.getCommitId(currentNodeId) val previousPath = paths.last() var currentPath: MaybeDeletedFilePath = previousPath if (previousNode != Dfs.NextNode.NODE_NOT_FOUND) { val previousNodeId = visibleLinearGraph.getNodeId(previousNode) val previousCommit = permanentCommitsInfo.getCommitId(previousNodeId) currentPath = if (down) { val pathGetter = { parentIndex: Int -> namesData.getPathInParentRevision(previousCommit, permanentCommitsInfo.getCommitId(parentIndex), previousPath) } val path = findPathWithoutConflict(previousNodeId, pathGetter) path ?: pathGetter(permanentLinearGraph.getCorrespondingParent(previousNodeId, currentNodeId, visibilityBuffer)) } else { val pathGetter = { parentIndex: Int -> namesData.getPathInChildRevision(currentCommit, permanentCommitsInfo.getCommitId(parentIndex), previousPath) } val path = findPathWithoutConflict(currentNodeId, pathGetter) // since in reality there is no edge between the nodes, but the whole path, we need to know, which parent is affected by this path path ?: pathGetter(permanentLinearGraph.getCorrespondingParent(currentNodeId, previousNodeId, visibilityBuffer)) } } pathsForCommits[currentCommit] = currentPath paths.push(currentPath) } private fun findPathWithoutConflict(nodeId: Int, pathGetter: (Int) -> MaybeDeletedFilePath): MaybeDeletedFilePath? { val parents = permanentLinearGraph.getNodes(nodeId, LiteLinearGraph.NodeFilter.DOWN) val path = pathGetter(parents.first()) if (parents.size == 1) return path if (parents.subList(1, parents.size).find { pathGetter(it) != path } != null) return null return path } override fun exitNode(node: Int) { paths.pop() } } abstract class FileNamesData(startPaths: Collection<FilePath>) { // file -> (commitId -> (parent commitId -> change kind)) private val affectedCommits = THashMap<FilePath, TIntObjectHashMap<TIntObjectHashMap<ChangeKind>>>(FILE_PATH_HASHING_STRATEGY) private val commitToRename = MultiMap.createSmart<UnorderedPair<Int>, Rename>() val isEmpty: Boolean get() = affectedCommits.isEmpty val hasRenames: Boolean get() = !commitToRename.isEmpty val files: Set<FilePath> get() = affectedCommits.keys constructor(startPath: FilePath) : this(listOf(startPath)) init { val newPaths = THashSet<FilePath>(FILE_PATH_HASHING_STRATEGY) newPaths.addAll(startPaths) while (newPaths.isNotEmpty()) { val commits = THashMap<FilePath, TIntObjectHashMap<TIntObjectHashMap<ChangeKind>>>(FILE_PATH_HASHING_STRATEGY) newPaths.associateTo(commits) { kotlin.Pair(it, getAffectedCommits(it)) } affectedCommits.putAll(commits) newPaths.clear() collectAdditionsDeletions(commits) { ad -> if (commitToRename[ad.commits].any { rename -> ad.matches(rename) }) return@collectAdditionsDeletions findRename(ad.parent, ad.child, ad::matches)?.let { files -> val rename = Rename(files.first, files.second, ad.parent, ad.child) commitToRename.putValue(ad.commits, rename) val otherPath = rename.getOtherPath(ad)!! if (!affectedCommits.containsKey(otherPath)) { newPaths.add(otherPath) } } } } } private fun collectAdditionsDeletions(commits: Map<FilePath, TIntObjectHashMap<TIntObjectHashMap<ChangeKind>>>, action: (AdditionDeletion) -> Unit) { commits.forEach { path, commit, changes -> changes.forEachEntry { parent, change -> createAdditionDeletion(parent, commit, change, path)?.let { ad -> action(ad) } true } } } private fun createAdditionDeletion(parent: Int, commit: Int, change: ChangeKind, path: FilePath): AdditionDeletion? { if (parent != commit && (change == ChangeKind.ADDED || change == ChangeKind.REMOVED)) { return AdditionDeletion(path, commit, parent, change == ChangeKind.ADDED) } return null } fun getPathInParentRevision(commit: Int, parent: Int, childPath: MaybeDeletedFilePath): MaybeDeletedFilePath { val childFilePath = childPath.filePath val changeKind = affectedCommits[childFilePath]?.get(commit)?.get(parent) ?: return childPath if (changeKind == ChangeKind.NOT_CHANGED) return childPath val renames = commitToRename.get(UnorderedPair(commit, parent)) if (!childPath.deleted) { val otherPath = renames.firstNotNull { rename -> rename.getOtherPath(commit, childFilePath) } if (otherPath != null) return MaybeDeletedFilePath(otherPath) return MaybeDeletedFilePath(childFilePath, changeKind == ChangeKind.ADDED) } if (changeKind == ChangeKind.REMOVED) { // checking if this is actually an unrelated rename if (renames.firstNotNull { rename -> rename.getOtherPath(parent, childFilePath) } != null) return childPath } return MaybeDeletedFilePath(childFilePath, changeKind != ChangeKind.REMOVED) } fun getPathInChildRevision(commit: Int, parent: Int, parentPath: MaybeDeletedFilePath): MaybeDeletedFilePath { val parentFilePath = parentPath.filePath val changeKind = affectedCommits[parentFilePath]?.get(commit)?.get(parent) ?: return parentPath if (changeKind == ChangeKind.NOT_CHANGED) return parentPath val renames = commitToRename.get(UnorderedPair(commit, parent)) if (!parentPath.deleted) { val otherPath = renames.firstNotNull { rename -> rename.getOtherPath(parent, parentFilePath) } if (otherPath != null) return MaybeDeletedFilePath(otherPath) return MaybeDeletedFilePath(parentFilePath, changeKind == ChangeKind.REMOVED) } if (changeKind == ChangeKind.ADDED) { // checking if this is actually an unrelated rename if (renames.firstNotNull { rename -> rename.getOtherPath(commit, parentFilePath) } != null) return parentPath } return MaybeDeletedFilePath(parentFilePath, changeKind != ChangeKind.ADDED) } fun affects(commit: Int, path: MaybeDeletedFilePath, verify: Boolean = false): Boolean { val changes = affectedCommits[path.filePath]?.get(commit) ?: return false if (path.deleted) { if (!changes.containsValue(ChangeKind.REMOVED)) return false if (!verify) return true for (parent in changes.keys()) { if (commitToRename.get(UnorderedPair(commit, parent)).firstNotNull { rename -> rename.getOtherPath(parent, path.filePath) } != null) { // this is a rename from path to something else, we should not match this commit return false } } return true } return !changes.containsValue(ChangeKind.REMOVED) } fun getCommits(): Set<Int> { val result = mutableSetOf<Int>() affectedCommits.forEach { _, commit, _ -> result.add(commit) } return result } fun buildPathsMap(): Map<Int, MaybeDeletedFilePath> { val result = mutableMapOf<Int, MaybeDeletedFilePath>() affectedCommits.forEach { filePath, commit, changes -> result[commit] = MaybeDeletedFilePath(filePath, changes.containsValue(ChangeKind.REMOVED)) } return result } fun getChanges(filePath: FilePath, commit: Int) = affectedCommits[filePath]?.get(commit) fun forEach(action: (FilePath, Int, TIntObjectHashMap<VcsLogPathsIndex.ChangeKind>) -> Unit) = affectedCommits.forEach(action) fun removeAll(commits: List<Int>) { affectedCommits.forEach { _, commitsMap -> commitsMap.removeAll(commits) } } abstract fun findRename(parent: Int, child: Int, accept: (Couple<FilePath>) -> Boolean): Couple<FilePath>? abstract fun getAffectedCommits(path: FilePath): TIntObjectHashMap<TIntObjectHashMap<VcsLogPathsIndex.ChangeKind>> } private class AdditionDeletion(val filePath: FilePath, val child: Int, val parent: Int, val isAddition: Boolean) { val commits get() = UnorderedPair(parent, child) fun matches(rename: Rename): Boolean { if (rename.commit1 == parent && rename.commit2 == child) { return if (isAddition) FILE_PATH_HASHING_STRATEGY.equals(rename.filePath2, filePath) else FILE_PATH_HASHING_STRATEGY.equals(rename.filePath1, filePath) } else if (rename.commit2 == parent && rename.commit1 == child) { return if (isAddition) FILE_PATH_HASHING_STRATEGY.equals(rename.filePath1, filePath) else FILE_PATH_HASHING_STRATEGY.equals(rename.filePath2, filePath) } return false } fun matches(files: Couple<FilePath>): Boolean { return (isAddition && FILE_PATH_HASHING_STRATEGY.equals(files.second, filePath)) || (!isAddition && FILE_PATH_HASHING_STRATEGY.equals(files.first, filePath)) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as AdditionDeletion if (!FILE_PATH_HASHING_STRATEGY.equals(filePath, other.filePath)) return false if (child != other.child) return false if (parent != other.parent) return false if (isAddition != other.isAddition) return false return true } override fun hashCode(): Int { var result = FILE_PATH_HASHING_STRATEGY.computeHashCode(filePath) result = 31 * result + child result = 31 * result + parent result = 31 * result + isAddition.hashCode() return result } } private class Rename(val filePath1: FilePath, val filePath2: FilePath, val commit1: Int, val commit2: Int) { fun getOtherPath(commit: Int, filePath: FilePath): FilePath? { if (commit == commit1 && FILE_PATH_HASHING_STRATEGY.equals(filePath, filePath1)) return filePath2 if (commit == commit2 && FILE_PATH_HASHING_STRATEGY.equals(filePath, filePath2)) return filePath1 return null } fun getOtherPath(ad: AdditionDeletion): FilePath? { return getOtherPath(if (ad.isAddition) ad.child else ad.parent, ad.filePath) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Rename if (!FILE_PATH_HASHING_STRATEGY.equals(filePath1, other.filePath1)) return false if (!FILE_PATH_HASHING_STRATEGY.equals(filePath2, other.filePath2)) return false if (commit1 != other.commit1) return false if (commit2 != other.commit2) return false return true } override fun hashCode(): Int { var result = FILE_PATH_HASHING_STRATEGY.computeHashCode(filePath1) result = 31 * result + FILE_PATH_HASHING_STRATEGY.computeHashCode(filePath2) result = 31 * result + commit1 result = 31 * result + commit2 return result } } class MaybeDeletedFilePath(val filePath: FilePath, val deleted: Boolean) { constructor(filePath: FilePath) : this(filePath, false) override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as MaybeDeletedFilePath if (!FILE_PATH_HASHING_STRATEGY.equals(filePath, other.filePath)) return false if (deleted != other.deleted) return false return true } override fun hashCode(): Int { var result = FILE_PATH_HASHING_STRATEGY.computeHashCode(filePath) result = 31 * result + deleted.hashCode() return result } } internal fun Map<FilePath, TIntObjectHashMap<TIntObjectHashMap<VcsLogPathsIndex.ChangeKind>>>.forEach(action: (FilePath, Int, TIntObjectHashMap<VcsLogPathsIndex.ChangeKind>) -> Unit) { forEach { (filePath, affectedCommits) -> affectedCommits.forEachEntry { commit, changesMap -> action(filePath, commit, changesMap) true } } } internal fun TIntObjectHashMap<*>.removeAll(keys: List<Int>) { keys.forEach { this.remove(it) } } internal fun TIntHashSet.removeAll(elements: TIntHashSet): Boolean { var result = false for (i in elements) { result = this.remove(i) or result } return result } private fun <E, R> Collection<E>.firstNotNull(mapping: (E) -> R): R? { for (e in this) { val value = mapping(e) if (value != null) return value } return null } @JvmField val FILE_PATH_HASHING_STRATEGY: TObjectHashingStrategy<FilePath> = FilePathCaseSensitiveStrategy() internal class FilePathCaseSensitiveStrategy : TObjectHashingStrategy<FilePath> { override fun equals(path1: FilePath?, path2: FilePath?): Boolean { if (path1 === path2) return true if (path1 == null || path2 == null) return false if (path1.isDirectory != path2.isDirectory) return false val canonical1 = FileUtil.toCanonicalPath(path1.path) val canonical2 = FileUtil.toCanonicalPath(path2.path) return canonical1 == canonical2 } override fun computeHashCode(path: FilePath?): Int { if (path == null) return 0 var result = if (path.path.isEmpty()) 0 else FileUtil.toCanonicalPath(path.path).hashCode() result = 31 * result + if (path.isDirectory) 1 else 0 return result } }
apache-2.0
e6654bc9197a70ee2bf3207ad0b542e0
39.592453
184
0.708688
4.591889
false
false
false
false
google/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/details/commit/CommitDetailsPanel.kt
1
12007
// 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.vcs.log.ui.details.commit import com.intellij.ide.IdeTooltipManager import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.HtmlChunk import com.intellij.openapi.vcs.ui.FontUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.BrowserHyperlinkListener import com.intellij.ui.ColorUtil import com.intellij.ui.components.panels.Wrapper import com.intellij.ui.scale.JBUIScale import com.intellij.util.ui.* import com.intellij.util.ui.components.BorderLayoutPanel import com.intellij.vcs.log.CommitId import com.intellij.vcs.log.VcsRef import com.intellij.vcs.log.ui.frame.CommitPresentationUtil.* import com.intellij.vcs.log.ui.frame.VcsCommitExternalStatusPresentation import com.intellij.vcs.log.util.VcsLogUiUtil import net.miginfocom.layout.CC import net.miginfocom.layout.LC import net.miginfocom.swing.MigLayout import java.awt.* import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.JPanel import javax.swing.event.HyperlinkEvent class CommitDetailsPanel @JvmOverloads constructor(navigate: (CommitId) -> Unit = {}) : JPanel() { companion object { const val SIDE_BORDER = 14 const val INTERNAL_BORDER = 10 const val EXTERNAL_BORDER = 14 const val LAYOUT_MIN_WIDTH = 40 } private val statusesActionGroup = DefaultActionGroup() data class RootColor(val root: VirtualFile, val color: Color) private val hashAndAuthorPanel = HashAndAuthorPanel() private val statusesToolbar = ActionManager.getInstance().createActionToolbar("CommitDetailsPanel", statusesActionGroup, false).apply { targetComponent = this@CommitDetailsPanel (this as ActionToolbarImpl).setForceShowFirstComponent(true) component.apply { isOpaque = false border = JBUI.Borders.empty() isVisible = false } } private val messagePanel = CommitMessagePanel(navigate) private val branchesPanel = ReferencesPanel(Registry.intValue("vcs.log.max.branches.shown")) private val tagsPanel = ReferencesPanel(Registry.intValue("vcs.log.max.tags.shown")) private val rootPanel = RootColorPanel(hashAndAuthorPanel) private val containingBranchesPanel = ContainingBranchesPanel() init { layout = MigLayout(LC().gridGap("0", "0").insets("0").fill()) isOpaque = false val mainPanel = JPanel(null).apply { layout = MigLayout(LC().gridGap("0", "0").insets("0").fill().flowY()) isOpaque = false val metadataPanel = BorderLayoutPanel().apply { isOpaque = false border = JBUI.Borders.empty(INTERNAL_BORDER, SIDE_BORDER, INTERNAL_BORDER, 0) addToLeft(rootPanel) addToCenter(hashAndAuthorPanel) } val componentLayout = CC().minWidth("$LAYOUT_MIN_WIDTH").grow().push() add(messagePanel, componentLayout) add(metadataPanel, componentLayout) add(branchesPanel, componentLayout) add(tagsPanel, componentLayout) add(containingBranchesPanel, componentLayout) } add(mainPanel, CC().grow().push()) //show at most 4 icons val maxHeight = JBUIScale.scale(22 * 4) add(statusesToolbar.component, CC().hideMode(3).alignY("top").maxHeight("$maxHeight")) updateStatusToolbar(false) } fun setCommit(presentation: CommitPresentation) { messagePanel.updateMessage(presentation) hashAndAuthorPanel.presentation = presentation } fun setRefs(references: List<VcsRef>?) { references ?: return branchesPanel.setReferences(references.filter { it.type.isBranch }) tagsPanel.setReferences(references.filter { !it.type.isBranch }) if (tagsPanel.isVisible) { branchesPanel.border = JBUI.Borders.empty(0, SIDE_BORDER - ReferencesPanel.H_GAP, 0, 0) tagsPanel.border = JBUI.Borders.empty(0, SIDE_BORDER - ReferencesPanel.H_GAP, INTERNAL_BORDER, 0) } else if (branchesPanel.isVisible) { branchesPanel.border = JBUI.Borders.empty(0, SIDE_BORDER - ReferencesPanel.H_GAP, INTERNAL_BORDER, 0) } update() } fun setRoot(rootColor: RootColor?) { rootPanel.setRoot(rootColor) } fun setBranches(branches: List<String>?) { containingBranchesPanel.setBranches(branches) } fun setStatuses(statuses: List<VcsCommitExternalStatusPresentation>) { hashAndAuthorPanel.signature = statuses.filterIsInstance(VcsCommitExternalStatusPresentation.Signature::class.java).firstOrNull() val nonSignaturesStatuses = statuses.filter { it !is VcsCommitExternalStatusPresentation.Signature } statusesActionGroup.removeAll() statusesActionGroup.addAll(nonSignaturesStatuses.map(::statusToAction)) updateStatusToolbar(nonSignaturesStatuses.isNotEmpty()) } private fun statusToAction(status: VcsCommitExternalStatusPresentation) = object : DumbAwareAction(status.text, null, status.icon) { override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } override fun update(e: AnActionEvent) { e.presentation.apply { isVisible = true isEnabled = status is VcsCommitExternalStatusPresentation.Clickable && status.clickEnabled(e.inputEvent) disabledIcon = status.icon } } override fun actionPerformed(e: AnActionEvent) { if (status is VcsCommitExternalStatusPresentation.Clickable) { if (status.clickEnabled(e.inputEvent)) status.onClick(e.inputEvent) } } } private fun updateStatusToolbar(hasStatuses: Boolean) { border = if (hasStatuses) JBUI.Borders.empty() else JBUI.Borders.emptyRight(SIDE_BORDER) statusesToolbar.updateActionsImmediately() statusesToolbar.component.isVisible = hasStatuses } fun update() { messagePanel.update() rootPanel.update() hashAndAuthorPanel.update() branchesPanel.update() tagsPanel.update() containingBranchesPanel.update() } override fun getBackground(): Color = getCommitDetailsBackground() } private class CommitMessagePanel(private val navigate: (CommitId) -> Unit) : HtmlPanel() { private var presentation: CommitPresentation? = null override fun hyperlinkUpdate(e: HyperlinkEvent) { presentation?.let { presentation -> if (e.eventType == HyperlinkEvent.EventType.ACTIVATED && isGoToHash(e)) { val commitId = presentation.parseTargetCommit(e) ?: return navigate(commitId) } else { BrowserHyperlinkListener.INSTANCE.hyperlinkUpdate(e) } } } init { border = JBUI.Borders.empty(CommitDetailsPanel.EXTERNAL_BORDER, CommitDetailsPanel.SIDE_BORDER, CommitDetailsPanel.INTERNAL_BORDER, 0) } fun updateMessage(message: CommitPresentation?) { presentation = message update() } override fun getBody() = presentation?.text ?: "" override fun getBackground(): Color = getCommitDetailsBackground() override fun update() { isVisible = presentation != null super.update() } } private class ContainingBranchesPanel : HtmlPanel() { private var branches: List<String>? = null private var expanded = false init { border = JBUI.Borders.empty(0, CommitDetailsPanel.SIDE_BORDER, CommitDetailsPanel.EXTERNAL_BORDER, 0) isVisible = false } override fun setBounds(x: Int, y: Int, w: Int, h: Int) { val oldWidth = width super.setBounds(x, y, w, h) if (w != oldWidth) { update() } } override fun hyperlinkUpdate(e: HyperlinkEvent) { if (e.eventType == HyperlinkEvent.EventType.ACTIVATED && isShowHideBranches(e)) { expanded = !expanded update() } } fun setBranches(branches: List<String>?) { this.branches = branches expanded = false isVisible = true update() } override fun getBody(): String { val insets = insets val availableWidth = width - insets.left - insets.right val text = getBranchesText(branches, expanded, availableWidth, getFontMetrics(bodyFont)) return if (expanded) text else HtmlChunk.raw(text).wrapWith("nobr").toString() } override fun getBackground(): Color = getCommitDetailsBackground() override fun getBodyFont(): Font = FontUtil.getCommitMetadataFont() } private class HashAndAuthorPanel : HtmlPanel() { init { editorKit = HTMLEditorKitBuilder() .withViewFactoryExtensions(ExtendableHTMLViewFactory.Extensions.WORD_WRAP, ExtendableHTMLViewFactory.Extensions.icons { signature?.icon } ) .build().apply { //language=css styleSheet.addRule(""".signature { color: ${ColorUtil.toHtmlColor(UIUtil.getContextHelpForeground())}; }""".trimMargin()) } } var presentation: CommitPresentation? = null set(value) { field = value update() } var signature: VcsCommitExternalStatusPresentation.Signature? = null set(value) { field = value update() } override fun getBody(): String { val presentation = presentation ?: return "" val signature = signature @Suppress("HardCodedStringLiteral") return presentation.hashAndAuthor.let { if (signature != null) { val tooltip = signature.description?.toString() //language=html it + """<span class='signature'>&nbsp;&nbsp;&nbsp; |<icon src='sig' alt='${tooltip.orEmpty()}'/> |&nbsp;${signature.text} |</span>""".trimMargin() } else it } } init { border = JBUI.Borders.empty() } public override fun getBodyFont(): Font = FontUtil.getCommitMetadataFont() override fun update() { isVisible = presentation != null super.update() } } private class RootColorPanel(private val parent: HashAndAuthorPanel) : Wrapper(parent) { companion object { private const val ROOT_ICON_SIZE = 13 private const val ROOT_GAP = 4 } private var icon: ColorIcon? = null private var tooltipText: String? = null private val mouseMotionListener = object : MouseAdapter() { override fun mouseMoved(e: MouseEvent?) { if (IdeTooltipManager.getInstance().hasCurrent()) { IdeTooltipManager.getInstance().hideCurrent(e) return } icon?.let { icon -> tooltipText?.let { tooltipText -> VcsLogUiUtil.showTooltip(this@RootColorPanel, Point(icon.iconWidth / 2, 0), Balloon.Position.above, tooltipText) } } } } init { setVerticalSizeReferent(parent) addMouseMotionListener(mouseMotionListener) } override fun getPreferredSize(): Dimension = icon?.let { icon -> val size = super.getPreferredSize() Dimension(icon.iconWidth + JBUIScale.scale(ROOT_GAP), size.height) } ?: Dimension(0, 0) fun setRoot(rootColor: CommitDetailsPanel.RootColor?) { if (rootColor != null) { icon = JBUIScale.scaleIcon(ColorIcon(ROOT_ICON_SIZE, rootColor.color)) tooltipText = rootColor.root.path } else { icon = null tooltipText = null } } fun update() { isVisible = icon != null revalidate() repaint() } override fun getBackground(): Color = getCommitDetailsBackground() override fun paintComponent(g: Graphics) { icon?.let { icon -> val h = FontUtil.getStandardAscent(parent.bodyFont, g) val metrics = getFontMetrics(parent.bodyFont) icon.paintIcon(this, g, 0, metrics.maxAscent - h + (h - icon.iconHeight - 1) / 2) } } } fun getCommitDetailsBackground(): Color = UIUtil.getTreeBackground()
apache-2.0
5d3c0c1c1f911d9318602dd420117243
31.454054
138
0.704422
4.560197
false
false
false
false
apache/isis
incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/snapshots/knife/HTTP_ERROR_500.kt
2
13320
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.causeway.client.kroviz.snapshots.knife import org.apache.causeway.client.kroviz.snapshots.Response object HTTP_ERROR_500 : Response() { val invoke = "\$invoke" val invokeOnTarget = "\$invokeOnTarget" val preprocess = "\$preprocess" val doFilter = "\$doFilter" val ConnectionHandler = "\$ConnectionHandler" val SocketProcessor = "\$SocketProcessor" val Worker = "\$Worker" val WrappingRunnable = "\$WrappingRunnable" val Simple = "\$Simple" val DomainEventMemberExecutor = "\$DomainEventMemberExecutor" val invokeMethodOn = "\$invokeMethodOn" val toCallable = "\$toCallable" override val url = "" override val str = """{ "httpStatusCode": 500, "message": null, "detail": { "className": "java.lang.NullPointerException", "message": null, "element": [ "com.kn.ife.cfg.vm.ReleaseComparisons.create(ReleaseComparisons.java:83)", "com.kn.ife.cfg.Configurations.createCurrent(Configurations.java:319)", "com.kn.ife.cfg.vm.ReleaseComparisons.createSalogCurrent(ReleaseComparisons.java:50)", "java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)", "java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)", "java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)", "java.base/java.lang.reflect.Method.invoke(Method.java:566)", "org.apache.causeway.commons.internal.reflection._Reflect.lambda$invokeMethodOn${'$'}11(_Reflect.java:549)", "org.apache.causeway.commons.functional.Try.call(Try.java:55)", "org.apache.causeway.commons.internal.reflection._Reflect.invokeMethodOn(_Reflect.java:547)", "org.apache.causeway.core.metamodel.commons.CanonicalInvoker.invoke(CanonicalInvoker.java:120)", "org.apache.causeway.core.metamodel.commons.CanonicalInvoker.invoke(CanonicalInvoker.java:108)", "org.apache.causeway.core.metamodel.facets.actions.action.invocation.ActionInvocationFacetForDomainEventAbstract.invokeMethodElseFromCache(ActionInvocationFacetForDomainEventAbstract.java:162)", "org.apache.causeway.core.metamodel.facets.actions.action.invocation.ActionInvocationFacetForDomainEventAbstract$DomainEventMemberExecutor.execute(ActionInvocationFacetForDomainEventAbstract.java:207)", "org.apache.causeway.core.metamodel.facets.actions.action.invocation.ActionInvocationFacetForDomainEventAbstract$DomainEventMemberExecutor.execute(ActionInvocationFacetForDomainEventAbstract.java:174)", "org.apache.causeway.core.interaction.session.CausewayInteraction.executeInternal(CausewayInteraction.java:136)", "org.apache.causeway.core.interaction.session.CausewayInteraction.execute(CausewayInteraction.java:105)", "org.apache.causeway.core.runtimeservices.executor.MemberExecutorServiceDefault.invokeAction(MemberExecutorServiceDefault.java:153)", "org.apache.causeway.core.metamodel.facets.actions.action.invocation.ActionInvocationFacetForDomainEventAbstract.doInvoke(ActionInvocationFacetForDomainEventAbstract.java:131)", "org.apache.causeway.core.metamodel.facets.actions.action.invocation.ActionInvocationFacetForDomainEventAbstract.lambda$invoke${'$'}1(ActionInvocationFacetForDomainEventAbstract.java:99)", "org.apache.causeway.commons.functional.Try.call(Try.java:55)", "org.apache.causeway.core.runtimeservices.transaction.TransactionServiceSpring.callTransactional(TransactionServiceSpring.java:108)", "org.apache.causeway.applib.services.xactn.TransactionalProcessor.callWithinCurrentTransactionElseCreateNew(TransactionalProcessor.java:100)", "org.apache.causeway.core.metamodel.facets.actions.action.invocation.ActionInvocationFacetForDomainEventAbstract.invoke(ActionInvocationFacetForDomainEventAbstract.java:98)", "org.apache.causeway.core.metamodel.specloader.specimpl.ObjectActionDefault.executeInternal(ObjectActionDefault.java:421)", "org.apache.causeway.core.metamodel.specloader.specimpl.ObjectActionDefault.execute(ObjectActionDefault.java:409)", "org.apache.causeway.core.metamodel.interactions.managed.ManagedAction.invoke(ManagedAction.java:134)", "org.apache.causeway.core.metamodel.interactions.managed.ManagedAction.invoke(ManagedAction.java:141)", "org.apache.causeway.core.metamodel.interactions.managed.ActionInteraction.invokeWith(ActionInteraction.java:150)", "org.apache.causeway.viewer.restfulobjects.viewer.resources._DomainResourceHelper.invokeAction(_DomainResourceHelper.java:285)", "org.apache.causeway.viewer.restfulobjects.viewer.resources._DomainResourceHelper.invokeAction(_DomainResourceHelper.java:193)", "org.apache.causeway.viewer.restfulobjects.viewer.resources.DomainObjectResourceServerside.invokeAction(DomainObjectResourceServerside.java:770)", "java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)", "java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)", "java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)", "java.base/java.lang.reflect.Method.invoke(Method.java:566)", "org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:170)", "org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:130)", "org.jboss.resteasy.core.ResourceMethodInvoker.internalInvokeOnTarget(ResourceMethodInvoker.java:660)", "org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTargetAfterFilter(ResourceMethodInvoker.java:524)", "org.jboss.resteasy.core.ResourceMethodInvoker.lambda$invokeOnTarget${'$'}2(ResourceMethodInvoker.java:474)", "org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:364)", "org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTarget(ResourceMethodInvoker.java:476)", "org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:434)", "org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:408)", "org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:69)", "org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:492)", "org.jboss.resteasy.core.SynchronousDispatcher.lambda$invoke${'$'}4(SynchronousDispatcher.java:261)", "org.jboss.resteasy.core.SynchronousDispatcher.lambda$preprocess${'$'}0(SynchronousDispatcher.java:161)", "org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:364)", "org.jboss.resteasy.core.SynchronousDispatcher.preprocess(SynchronousDispatcher.java:164)", "org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:247)", "org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:249)", "org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:60)", "org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:55)", "javax.servlet.http.HttpServlet.service(HttpServlet.java:590)", "org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)", "org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)", "org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)", "org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)", "org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)", "org.apache.causeway.viewer.restfulobjects.viewer.webmodule.CausewayRestfulObjectsInteractionFilter.lambda$doFilter${'$'}1(CausewayRestfulObjectsInteractionFilter.java:387)", "org.apache.causeway.commons.functional.ThrowingRunnable.lambda$toCallable${'$'}0(ThrowingRunnable.java:42)", "org.apache.causeway.commons.functional.Try.call(Try.java:55)", "org.apache.causeway.core.runtimeservices.transaction.TransactionServiceSpring.callTransactional(TransactionServiceSpring.java:108)", "org.apache.causeway.applib.services.xactn.TransactionalProcessor.callWithinCurrentTransactionElseCreateNew(TransactionalProcessor.java:100)", "org.apache.causeway.applib.services.xactn.TransactionalProcessor.runWithinCurrentTransactionElseCreateNew(TransactionalProcessor.java:110)", "org.apache.causeway.viewer.restfulobjects.viewer.webmodule.CausewayRestfulObjectsInteractionFilter.lambda$doFilter${'$'}3(CausewayRestfulObjectsInteractionFilter.java:386)", "org.apache.causeway.core.runtimeservices.session.InteractionServiceDefault.runInternal(InteractionServiceDefault.java:329)", "org.apache.causeway.core.runtimeservices.session.InteractionServiceDefault.run(InteractionServiceDefault.java:272)", "org.apache.causeway.viewer.restfulobjects.viewer.webmodule.CausewayRestfulObjectsInteractionFilter.doFilter(CausewayRestfulObjectsInteractionFilter.java:383)", "org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)", "org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)", "org.apache.causeway.core.webapp.modules.logonlog.CausewayLogOnExceptionFilter.doFilter(CausewayLogOnExceptionFilter.java:60)", "org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)", "org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)", "org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:91)", "org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)", "org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)", "org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)", "org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)", "org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)", "org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)", "org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)", "org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)", "org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)", "org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)", "org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)", "org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)", "org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)", "org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)", "org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)", "org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)", "org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)", "org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360)", "org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)", "org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)", "org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:890)", "org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1743)", "org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)", "org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)", "org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)", "org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)", "java.base/java.lang.Thread.run(Thread.java:829)" ], "causedBy": null } } """ }
apache-2.0
e1e9b8bae82b7ab0af6061338a8cb097
85.493506
208
0.798724
4.004811
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepic/droid/ui/activities/SmartLockActivityBase.kt
1
6895
package org.stepic.droid.ui.activities import android.content.Intent import android.content.IntentSender import android.os.Bundle import com.google.android.gms.auth.api.Auth import com.google.android.gms.auth.api.credentials.Credential import com.google.android.gms.auth.api.credentials.CredentialRequest import com.google.android.gms.auth.api.signin.GoogleSignInOptions import com.google.android.gms.common.Scopes import com.google.android.gms.common.api.CommonStatusCodes import com.google.android.gms.common.api.GoogleApiClient import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener import com.google.android.gms.common.api.Scope import org.stepic.droid.analytic.Analytic import org.stepic.droid.base.FragmentActivityBase import org.stepic.droid.model.Credentials import timber.log.Timber abstract class SmartLockActivityBase : FragmentActivityBase() { companion object { private const val RESOLVING_ACCOUNT_KEY = "RESOLVING_ACCOUNT_KEY" private const val REQUEST_FROM_SMART_LOCK_CODE = 314 private const val REQUEST_SAVE_TO_SMART_LOCK_CODE = 356 private fun Credential.toCredentials(): Credentials = Credentials(id, password ?: "") private fun Credentials.toCredential(): Credential = Credential .Builder(login) .setPassword(password) .build() } private var resolvingWasShown = false protected var googleApiClient: GoogleApiClient? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) resolvingWasShown = savedInstanceState?.getBoolean(RESOLVING_ACCOUNT_KEY) ?: false } protected fun initGoogleApiClient(withAuth: Boolean = false, autoManage: OnConnectionFailedListener? = null) { if (checkPlayServices()) { val builder = GoogleApiClient.Builder(this) .enableAutoManage(this, autoManage) .addApi(Auth.CREDENTIALS_API) if (withAuth) { val serverClientId = config.googleServerClientId val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestScopes(Scope(Scopes.EMAIL), Scope(Scopes.PROFILE)) .requestServerAuthCode(serverClientId) .build() builder.addApi(Auth.GOOGLE_SIGN_IN_API, gso) } googleApiClient = builder.build() } } protected fun requestCredentials() { val credentialRequest = CredentialRequest.Builder() .setPasswordLoginSupported(true) .build() Auth.CredentialsApi.request(googleApiClient, credentialRequest).setResultCallback { credentialRequestResult -> if (credentialRequestResult.status.isSuccess && credentialRequestResult.credential != null) { // Successfully read the credential without any user interaction, this // means there was only a single credential and the user has auto // sign-in enabled. analytic.reportEvent(Analytic.SmartLock.READ_CREDENTIAL_WITHOUT_INTERACTION) onCredentialsRetrieved(credentialRequestResult.credential!!.toCredentials()) } else { if (credentialRequestResult.status.statusCode == CommonStatusCodes.RESOLUTION_REQUIRED) { // Prompt the user to choose a saved credential; do not show the hint // selector. try { if (!resolvingWasShown) { analytic.reportEvent(Analytic.SmartLock.PROMPT_TO_CHOOSE_CREDENTIALS) resolvingWasShown = true credentialRequestResult.status.startResolutionForResult(this, REQUEST_FROM_SMART_LOCK_CODE) } } catch (e: IntentSender.SendIntentException) { Timber.e(e, "STATUS: Failed to send resolution.") } } else { Timber.d("STATUS: Failed to send resolution.") // The user must create an account or sign in manually. } } } } protected fun requestToSaveCredentials(credentials: Credentials) { Auth.CredentialsApi.save(googleApiClient, credentials.toCredential()) .setResultCallback { status -> if (!status.isSuccess && status.hasResolution()) { analytic.reportEvent(Analytic.SmartLock.SHOW_SAVE_LOGIN) status.startResolutionForResult(this, REQUEST_SAVE_TO_SMART_LOCK_CODE) } else { analytic.reportEventWithName(Analytic.SmartLock.DISABLED_LOGIN, status.statusMessage) onCredentialsSaved() } } } protected fun requestToDeleteCredentials(credentials: Credentials) { if (googleApiClient?.isConnected == true) { Auth.CredentialsApi.delete(googleApiClient, credentials.toCredential()).setResultCallback { status -> if (status.isSuccess) { analytic.reportEvent(Analytic.SmartLock.CREDENTIAL_DELETED_SUCCESSFUL) //do not show some message because E-mail is not correct was already shown } else { analytic.reportEventWithName(Analytic.SmartLock.CREDENTIAL_DELETED_FAIL, status.statusMessage) } } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { when (requestCode) { REQUEST_FROM_SMART_LOCK_CODE -> { if (resultCode == RESULT_OK && data != null) { analytic.reportEvent(Analytic.SmartLock.PROMPT_CREDENTIAL_RETRIEVED) val credential = requireNotNull(data.getParcelableExtra<Credential>(Credential.EXTRA_KEY)) onCredentialsRetrieved(credential.toCredentials()) } } REQUEST_SAVE_TO_SMART_LOCK_CODE -> { if (resultCode == RESULT_OK) { analytic.reportEvent(Analytic.SmartLock.LOGIN_SAVED) } onCredentialsSaved() } } super.onActivityResult(requestCode, resultCode, data) } override fun onSaveInstanceState(outState: Bundle) { outState.putBoolean(RESOLVING_ACCOUNT_KEY, resolvingWasShown) super.onSaveInstanceState(outState) } protected fun signOutFromGoogle() { if (googleApiClient?.isConnected == true) { Auth.GoogleSignInApi.signOut(googleApiClient) } } protected open fun onCredentialsRetrieved(credentials: Credentials) {} protected open fun onCredentialsSaved() {} }
apache-2.0
6de1233b34b7e7d8cf5d34c3384d8dbf
42.64557
119
0.632197
5.231411
false
false
false
false
scenerygraphics/scenery
src/main/kotlin/graphics/scenery/atomicsimulations/AtomicSimulation.kt
1
8858
package graphics.scenery.atomicsimulations import graphics.scenery.Hub import graphics.scenery.Icosphere import graphics.scenery.Mesh import graphics.scenery.attribute.material.Material import graphics.scenery.utils.extensions.times import graphics.scenery.volumes.BufferedVolume import graphics.scenery.volumes.Colormap import graphics.scenery.volumes.TransferFunction import graphics.scenery.volumes.Volume import net.imglib2.type.numeric.integer.UnsignedByteType import org.joml.Vector3f /** * This class represents an atomic simulation, i.e. a simulation that works on the atomic scale. It holds * objects that represent the atoms themselves, and, depending on data source, volumetric data (e.g. the electronic * density). An object of this class can be used directly to visualize such an atomic simulation, after reading * the appropriate data, as it is a child of the Mesh class. * [name] Name of this particular visualization. * [scalingFactor] Factor to scale positions of this simulation to allow for optimal visualization. * [atomicRadius] Radius of the atoms (in Bohr); this does not correspond to a physical radius, it's * simply for visualization purposes. * [normalizeVolumetricDataTo] A value to normalize the volumetric data to. This is useful for dynamic * simulations, as elsewise each timestep will be normalized to itself. * If this value is >0, then all timesteps will be normalized to the same value * allowing for analysis of local changes. * [cubeStyle] Name of the software with which cube file was created (or comparable software). .cube is * actually a very loosely defined standard. If we don't know anything about the cube file, we * have no choice but to use Regex parsing, which impacts performance. If we know the source * of the cube file, other assumptions can be made. Only relevant if cube files are used. * [rootFolder] Name of a folder, from which all files for this atomic simulation are read. If not * empty, all file names provided to the object will be read from this directoy. This is helpful * for larger series of simulations for which the source files are always read from the same * directory. * * @author Lenz Fiedler <[email protected]> */ open class AtomicSimulation(override var name: String = "DFTSimulation", private val scalingFactor: Float, private var atomicRadius: Float, private val normalizeVolumetricDataTo: Float=-1.0f, private var cubeStyle: String = "unknown", private val rootFolder: String = "") : Mesh(name) { init { atomicRadius *= scalingFactor } /** Atoms of this simulation as spheres. */ lateinit var atoms : Array<Icosphere> protected set /** Volumetric data, e.g. electronic density.. */ lateinit var volumetricData : BufferedVolume protected set /** Simulation data, parsed from a DFT calculation output. */ val simulationData: DFTParser = DFTParser(normalizeVolumetricDataTo) /** For dynamic cases: Current timepoint. */ private var currentTimePoint : Int = 0 /** * Creates an atomic simulation object from a cube file with filename [filename], assigned to * a hub instance [hub]. * */ fun createFromCube(filename: String, hub: Hub){ if (this.rootFolder.isEmpty()) { simulationData.parseCube(filename, cubeStyle) } else { simulationData.parseCube(this.rootFolder + filename, cubeStyle) } // Visualize the atoms. atoms = Array<Icosphere>(simulationData.numberOfAtoms) { Icosphere(atomicRadius, 4) } atoms.zip(simulationData.atomicPositions).forEach { with(it.component1()){ spatial { position = scalingFactor * it.component2() } material { metallic = 0.3f roughness = 0.9f } } this.addChild(it.component1()) } // TODO: Ask @randomdefaultuser if the following line has any use // simulationData.unitCellDimensions = simulationData.unitCellDimensions // Visualize the density data. volumetricData = Volume.fromBuffer(emptyList(), simulationData.gridDimensions[0], simulationData.gridDimensions[1], simulationData.gridDimensions[2], UnsignedByteType(), hub) volumetricData.name = "volume" // Note: Volumes centered at the origin are currently offset by -2.0 in each direction // (see Volume.kt, line 338), so we're adding 2.0 here. volumetricData.spatial().position = (scalingFactor * Vector3f(simulationData.unitCellOrigin[0], simulationData.unitCellOrigin[1], simulationData.unitCellOrigin[2])).add( Vector3f(2.0f, 2.0f, 2.0f) ) volumetricData.colormap = Colormap.get("viridis") volumetricData.pixelToWorldRatio = simulationData.gridSpacings[0] * scalingFactor volumetricData.transferFunction = TransferFunction.ramp(0.0f, 0.3f, 0.5f) this.addChild(volumetricData) volumetricData.addTimepoint("t-0", simulationData.electronicDensityUByte) volumetricData.goToLastTimepoint() } /** Updates an existing atomic simulation from a cube file (for dynamic simulations). */ fun updateFromCube(filename: String){ if (this.rootFolder.isEmpty()) { simulationData.parseCube(filename, cubeStyle) } else { simulationData.parseCube(this.rootFolder + filename, cubeStyle) } // Visualize the atoms. atoms.zip(simulationData.atomicPositions).forEach { it.component1().spatial().position = scalingFactor * it.component2() } currentTimePoint++ volumetricData.addTimepoint("t-${currentTimePoint}", simulationData.electronicDensityUByte) volumetricData.goToLastTimepoint() volumetricData.purgeFirst(10, 10) } /** Updates the material of the atoms. */ fun updateAtomicMaterial(newMaterial: Material){ this.atoms.forEach { atom -> with(atom) { material { roughness = newMaterial.roughness metallic = newMaterial.metallic diffuse = newMaterial.diffuse } } } } /** * Creates a DFT simulation object from a cube file containing some volumetric data and atomic positions. * [name] Name of this particular visualization. * [scalingFactor] Factor to scale positions of this simulation to allow for optimal visualization. * [atomicRadius] Radius of the atoms (in Bohr); this does not correspond to a physical radius, it's * simply for visualization purposes. * [normalizeVolumetricDataTo] A value to normalize the volumetric data to. This is useful for dynamic * simulations, as elsewise each timestep will be normalized to itself. * If this value is >0, then all timesteps will be normalized to the same value * allowing for analysis of local changes. * [cubeStyle] Name of the software with which cube file was created (or comparable software). .cube is * actually a very loosely defined standard. If we don't know anything about the cube file, we * have no choice but to use Regex parsing, which impacts performance. If we know the source * of the cube file, other assumptions can be made. Only relevant if cube files are used. * [rootFolder] Name of a folder, from which all files for this atomic simulation are read. If not * empty, all file names provided to the object will be read from this directoy. This is helpful * for larger series of simulations for which the source files are always read from the same * directory. */ companion object { @JvmStatic fun fromCube(filename: String, hub: Hub, scalingFactor: Float, atomicRadius: Float, normalizeVolumetricDataTo:Float = -1.0f, cubeStyle: String = "unknown", rootFolder: String = ""): AtomicSimulation { val dftSimulation = AtomicSimulation(scalingFactor=scalingFactor, atomicRadius=atomicRadius, normalizeVolumetricDataTo=normalizeVolumetricDataTo, cubeStyle=cubeStyle, rootFolder = rootFolder) dftSimulation.createFromCube(filename, hub) return dftSimulation } } }
lgpl-3.0
1349c40a02ccb2195a5a34309161e130
51.414201
122
0.65613
4.674406
false
false
false
false
allotria/intellij-community
platform/platform-impl/src/com/intellij/ide/customize/CustomizeIDEWizardInteractions.kt
2
2407
// 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.ide.customize import com.intellij.ide.ApplicationInitializedListener import com.intellij.internal.statistic.eventLog.FeatureUsageData import com.intellij.internal.statistic.service.fus.collectors.FUCounterUsageLogger import com.intellij.internal.statistic.utils.getPluginInfoByDescriptor import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.extensions.PluginDescriptor object CustomizeIDEWizardInteractions { var skippedOnPage = -1 val interactions = mutableListOf<CustomizeIDEWizardInteraction>() @JvmOverloads fun record(type: CustomizeIDEWizardInteractionType, pluginDescriptor: PluginDescriptor? = null, groupId: String? = null) { interactions.add(CustomizeIDEWizardInteraction(type, System.currentTimeMillis(), pluginDescriptor, groupId)) } } enum class CustomizeIDEWizardInteractionType { WizardDisplayed, UIThemeChanged, DesktopEntryCreated, LauncherScriptCreated, BundledPluginGroupDisabled, BundledPluginGroupEnabled, BundledPluginGroupCustomized, FeaturedPluginInstalled } data class CustomizeIDEWizardInteraction( val type: CustomizeIDEWizardInteractionType, val timestamp: Long, val pluginDescriptor: PluginDescriptor?, val groupId: String? ) class CustomizeIDEWizardCollectorActivity : ApplicationInitializedListener { override fun componentsInitialized() { if (CustomizeIDEWizardInteractions.interactions.isEmpty()) return ApplicationManager.getApplication().executeOnPooledThread { if (CustomizeIDEWizardInteractions.skippedOnPage != -1) { FUCounterUsageLogger.getInstance().logEvent("customize.wizard", "remaining.pages.skipped", FeatureUsageData().addData("page", CustomizeIDEWizardInteractions.skippedOnPage)) } for (interaction in CustomizeIDEWizardInteractions.interactions) { val data = FeatureUsageData() data.addData("timestamp", interaction.timestamp) interaction.pluginDescriptor?.let { data.addPluginInfo(getPluginInfoByDescriptor(it)) } interaction.groupId?.let { data.addData("group", it) } FUCounterUsageLogger.getInstance().logEvent("customize.wizard", interaction.type.toString(), data) } } } }
apache-2.0
dbb54fd5905e861ede48208ac8f7bf98
40.517241
140
0.780224
5.110403
false
false
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/common/src/Delay.kt
1
6208
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines import kotlinx.coroutines.selects.* import kotlin.coroutines.* import kotlin.time.* /** * This dispatcher _feature_ is implemented by [CoroutineDispatcher] implementations that natively support * scheduled execution of tasks. * * Implementation of this interface affects operation of * [delay][kotlinx.coroutines.delay] and [withTimeout] functions. * * @suppress **This an internal API and should not be used from general code.** */ @InternalCoroutinesApi public interface Delay { /** @suppress **/ @Deprecated( message = "Deprecated without replacement as an internal method never intended for public use", level = DeprecationLevel.ERROR ) // Error since 1.6.0 public suspend fun delay(time: Long) { if (time <= 0) return // don't delay return suspendCancellableCoroutine { scheduleResumeAfterDelay(time, it) } } /** * Schedules resume of a specified [continuation] after a specified delay [timeMillis]. * * Continuation **must be scheduled** to resume even if it is already cancelled, because a cancellation is just * an exception that the coroutine that used `delay` might wanted to catch and process. It might * need to close some resources in its `finally` blocks, for example. * * This implementation is supposed to use dispatcher's native ability for scheduled execution in its thread(s). * In order to avoid an extra delay of execution, the following code shall be used to resume this * [continuation] when the code is already executing in the appropriate thread: * * ```kotlin * with(continuation) { resumeUndispatchedWith(Unit) } * ``` */ public fun scheduleResumeAfterDelay(timeMillis: Long, continuation: CancellableContinuation<Unit>) /** * Schedules invocation of a specified [block] after a specified delay [timeMillis]. * The resulting [DisposableHandle] can be used to [dispose][DisposableHandle.dispose] of this invocation * request if it is not needed anymore. */ public fun invokeOnTimeout(timeMillis: Long, block: Runnable, context: CoroutineContext): DisposableHandle = DefaultDelay.invokeOnTimeout(timeMillis, block, context) } /** * Suspends until cancellation, in which case it will throw a [CancellationException]. * * This function returns [Nothing], so it can be used in any coroutine, * regardless of the required return type. * * Usage example in callback adapting code: * * ```kotlin * fun currentTemperature(): Flow<Temperature> = callbackFlow { * val callback = SensorCallback { degreesCelsius: Double -> * trySend(Temperature.celsius(degreesCelsius)) * } * try { * registerSensorCallback(callback) * awaitCancellation() // Suspends to keep getting updates until cancellation. * } finally { * unregisterSensorCallback(callback) * } * } * ``` * * Usage example in (non declarative) UI code: * * ```kotlin * suspend fun showStuffUntilCancelled(content: Stuff): Nothing { * someSubView.text = content.title * anotherSubView.text = content.description * someView.visibleInScope { * awaitCancellation() // Suspends so the view stays visible. * } * } * ``` */ public suspend fun awaitCancellation(): Nothing = suspendCancellableCoroutine {} /** * Delays coroutine for a given time without blocking a thread and resumes it after a specified time. * * This suspending function is cancellable. * If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting, this function * immediately resumes with [CancellationException]. * There is a **prompt cancellation guarantee**. If the job was cancelled while this function was * suspended, it will not resume successfully. See [suspendCancellableCoroutine] documentation for low-level details. * * If you want to delay forever (until cancellation), consider using [awaitCancellation] instead. * * Note that delay can be used in [select] invocation with [onTimeout][SelectBuilder.onTimeout] clause. * * Implementation note: how exactly time is tracked is an implementation detail of [CoroutineDispatcher] in the context. * @param timeMillis time in milliseconds. */ public suspend fun delay(timeMillis: Long) { if (timeMillis <= 0) return // don't delay return suspendCancellableCoroutine sc@ { cont: CancellableContinuation<Unit> -> // if timeMillis == Long.MAX_VALUE then just wait forever like awaitCancellation, don't schedule. if (timeMillis < Long.MAX_VALUE) { cont.context.delay.scheduleResumeAfterDelay(timeMillis, cont) } } } /** * Delays coroutine for a given [duration] without blocking a thread and resumes it after the specified time. * * This suspending function is cancellable. * If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting, this function * immediately resumes with [CancellationException]. * There is a **prompt cancellation guarantee**. If the job was cancelled while this function was * suspended, it will not resume successfully. See [suspendCancellableCoroutine] documentation for low-level details. * * If you want to delay forever (until cancellation), consider using [awaitCancellation] instead. * * Note that delay can be used in [select] invocation with [onTimeout][SelectBuilder.onTimeout] clause. * * Implementation note: how exactly time is tracked is an implementation detail of [CoroutineDispatcher] in the context. */ public suspend fun delay(duration: Duration): Unit = delay(duration.toDelayMillis()) /** Returns [Delay] implementation of the given context */ internal val CoroutineContext.delay: Delay get() = get(ContinuationInterceptor) as? Delay ?: DefaultDelay /** * Convert this duration to its millisecond value. * Positive durations are coerced at least `1`. */ internal fun Duration.toDelayMillis(): Long = if (this > Duration.ZERO) inWholeMilliseconds.coerceAtLeast(1) else 0
apache-2.0
1c8586f9a344b1c90a847e6e7ef738e8
41.520548
123
0.725032
4.664162
false
false
false
false
F43nd1r/acra-backend
acrarium/src/main/kotlin/com/faendir/acra/ui/ext/HasStyle.kt
1
3153
/* * (C) Copyright 2020 Lukas Morawietz (https://github.com/F43nd1r) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.faendir.acra.ui.ext import com.vaadin.flow.component.HasStyle fun HasStyle.preventWhiteSpaceBreaking() { style["white-space"] = "nowrap" } fun HasStyle.setMargin(value: Int, unit: SizeUnit) { style["margin"] = "$value${unit.text}" } fun HasStyle.setMarginLeft(value: Double, unit: SizeUnit) { style["margin-left"] = "$value${unit.text}" } fun HasStyle.setMarginTop(value: Double, unit: SizeUnit) { style["margin-top"] = "$value${unit.text}" } fun HasStyle.setMarginRight(value: Double, unit: SizeUnit) { style["margin-right"] = "$value${unit.text}" } fun HasStyle.setMarginBottom(value: Double, unit: SizeUnit) { style["margin-bottom"] = "$value${unit.text}" } fun HasStyle.setDefaultTextStyle() { style["text-decoration"] = "none" style["color"] = "inherit" } fun HasStyle.setPadding(value: Double, unit: SizeUnit) { style["padding"] = "$value${unit.text}" } fun HasStyle.setPaddingLeft(value: Double, unit: SizeUnit) { style["padding-left"] = "$value${unit.text}" } fun HasStyle.setPaddingTop(value: Double, unit: SizeUnit) { style["padding-top"] = "$value${unit.text}" } fun HasStyle.setPaddingRight(value: Double, unit: SizeUnit) { style["padding-right"] = "$value${unit.text}" } fun HasStyle.setPaddingBottom(value: Double, unit: SizeUnit) { style["padding-bottom"] = "$value${unit.text}" } fun HasStyle.setFlexGrow(value: Int) { style["flexGrow"] = "$value" } enum class JustifyItems(val value: String) { AUTO("auto"), NORMAL("normal"), START("start"), END("end"), FLEX_START("flex-start"), FLEX_END("flex-end"), SELF_START("self-start"), SELF_END("self-end"), CENTER("center"), LEFT("left"), RIGHT("right"), BASELINE("baseline"), FIRST_BASELINE("first baseline"), LAST_BASELINE("last baseline"), STRETCH("stretch") } fun HasStyle.setJustifyItems(justifyItems: JustifyItems) { style["justify-items"] = justifyItems.value } enum class Align(val value: String) { AUTO("auto"), NORMAL("normal"), START("start"), END("end"), FLEX_START("flex-start"), FLEX_END("flex-end"), SELF_START("self-start"), SELF_END("self-end"), CENTER("center"), BASELINE("baseline"), FIRST_BASELINE("first baseline"), LAST_BASELINE("last baseline"), STRETCH("stretch") } fun HasStyle.setAlignItems(align: Align) { style["align-items"] = align.value } fun HasStyle.setAlignSelf(align: Align) { style["align-self"] = align.value }
apache-2.0
521c53bcbe3b03976be2cfa4417beceb
25.283333
75
0.671107
3.401294
false
false
false
false
mtransitapps/mtransit-for-android
src/main/java/org/mtransit/android/ui/nearby/type/NearbyAgencyTypeViewModel.kt
1
9131
package org.mtransit.android.ui.nearby.type import android.location.Location import androidx.annotation.WorkerThread import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.liveData import androidx.lifecycle.map import androidx.lifecycle.switchMap import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import org.mtransit.android.commons.LocationUtils import org.mtransit.android.commons.MTLog import org.mtransit.android.commons.provider.POIProviderContract import org.mtransit.android.data.IAgencyNearbyProperties import org.mtransit.android.data.POIManager import org.mtransit.android.datasource.DataSourcesRepository import org.mtransit.android.datasource.POIRepository import org.mtransit.android.ui.type.AgencyTypeViewModel import org.mtransit.android.ui.view.common.PairMediatorLiveData import org.mtransit.android.ui.view.common.getLiveDataDistinct import javax.inject.Inject import kotlin.math.max @HiltViewModel class NearbyAgencyTypeViewModel @Inject constructor( savedStateHandle: SavedStateHandle, private val dataSourcesRepository: DataSourcesRepository, private val poiRepository: POIRepository, ) : ViewModel(), MTLog.Loggable { companion object { private val LOG_TAG = NearbyAgencyTypeViewModel::class.java.simpleName internal const val EXTRA_TYPE_ID = "extra_type_id" private const val MIN_NEARBY_LIST_COVERAGE_IN_METERS = LocationUtils.MIN_NEARBY_LIST_COVERAGE_IN_METERS.toFloat() } override fun getLogTag(): String = typeId.value?.let { "${LOG_TAG}-$it" } ?: LOG_TAG val typeId = savedStateHandle.getLiveDataDistinct<Int?>(AgencyTypeViewModel.EXTRA_TYPE_ID) private val _allAgencies = this.dataSourcesRepository.readingAllAgenciesBase() // #onModuleChanged val typeAgencies = PairMediatorLiveData(typeId, _allAgencies).map { (typeId, allAgencies) -> val currentParams = this.params.value ?: NearbyParams() this.params.value = currentParams.copy( typeId = typeId, allAgencies = allAgencies, ) typeId?.let { dstId -> allAgencies?.filter { agency -> agency.type.id == dstId } } } fun setNearbyLocation(newNearbyLocation: Location?) { val currentLocation = params.value?.nearbyLocation if (newNearbyLocation == currentLocation) { MTLog.d(this, "setNearbyLocation() > SKIP (same)") return } val currentParams: NearbyParams = params.value ?: NearbyParams() val newAD = LocationUtils.getNewDefaultAroundDiff() if (newNearbyLocation == null) { _sizeCovered.value = 0 _distanceCoveredInMeters.value = 0f params.value = currentParams.copy( nearbyLocation = newNearbyLocation, ad = newAD, minSize = null, maxSize = null, minCoverageInMeters = null, // TODO ? lastEmptyAroundDiff = null, ) return } val minSize = params.value?.minSize ?: -1 val maxSize = params.value?.maxSize ?: -1 val minCoverageInMeters = params.value?.minCoverageInMeters ?: -1f if (minSize < 0 || maxSize < 0 || minCoverageInMeters < 0f) { _sizeCovered.value = 0 _distanceCoveredInMeters.value = 0f params.value = currentParams.copy( nearbyLocation = newNearbyLocation, minSize = LocationUtils.MIN_NEARBY_LIST, maxSize = LocationUtils.MAX_NEARBY_LIST, ad = newAD, minCoverageInMeters = LocationUtils.getAroundCoveredDistanceInMeters( newNearbyLocation.latitude, newNearbyLocation.longitude, newAD.aroundDiff ).coerceAtLeast(max(MIN_NEARBY_LIST_COVERAGE_IN_METERS, newNearbyLocation.accuracy)), // TODO ? lastEmptyAroundDiff = null, ) } } private val _sizeCovered = MutableLiveData(0) private val _distanceCoveredInMeters = MutableLiveData(0f) private val params = MutableLiveData(NearbyParams()) val nearbyPOIs: LiveData<List<POIManager>?> = params.switchMap { params -> liveData(context = viewModelScope.coroutineContext + Dispatchers.IO) { emit(getNearbyPOIs(params)) } } @WorkerThread private fun getNearbyPOIs( currentParams: NearbyParams? = null, ): List<POIManager>? { if (currentParams == null || !currentParams.isReady) { MTLog.d(this, "getNearbyPOIs() > SKIP (not ready)") return null } val typeAgencies: List<IAgencyNearbyProperties> = currentParams.typeAgencies ?: return null val nearbyLocation: Location = currentParams.nearbyLocation ?: return null val ad: LocationUtils.AroundDiff = currentParams.ad ?: return null val minCoverageInMeters: Float = currentParams.minCoverageInMeters ?: return null val minSize: Int = currentParams.minSize ?: return null val maxSize: Int = currentParams.maxSize ?: return null val area: LocationUtils.Area = currentParams.area ?: return null val maxDistance: Float = currentParams.maxDistance ?: return null val lat = nearbyLocation.latitude val lng = nearbyLocation.longitude val aroundDiff = ad.aroundDiff val nearbyPOIs = mutableListOf<POIManager>() val poiFilter = POIProviderContract.Filter.getNewAroundFilter(lat, lng, aroundDiff).apply { addExtra(POIProviderContract.POI_FILTER_EXTRA_AVOID_LOADING, true) } typeAgencies .filter { it.isInArea(area) } // TODO latter optimize && !agency.isEntirelyInside(optLastArea) .forEach { agency -> poiRepository.findPOIMs(agency.authority, poiFilter)?.let { agencyPOIs -> LocationUtils.updateDistance(agencyPOIs, lat, lng) LocationUtils.removeTooFar(agencyPOIs, maxDistance) LocationUtils.removeTooMuchWhenNotInCoverage(agencyPOIs, minCoverageInMeters, maxSize) nearbyPOIs.addAll(agencyPOIs) } } LocationUtils.removeTooMuchWhenNotInCoverage(nearbyPOIs, minCoverageInMeters, maxSize) // TODO ? this.lastEmptyAroundDiff = ad.aroundDiff if (nearbyPOIs.size < minSize && !LocationUtils.searchComplete(nearbyLocation.latitude, nearbyLocation.longitude, aroundDiff) ) { this.params.postValue( currentParams.copy( ad = LocationUtils.incAroundDiff(ad) // trigger new data load ) ) } else { _distanceCoveredInMeters.postValue(minCoverageInMeters) _sizeCovered.postValue(nearbyPOIs.size) } return nearbyPOIs } fun isLoadingMore(): Boolean { val currentParams = this.params.value ?: NearbyParams() val nearbyLocation = currentParams.nearbyLocation ?: return false val ad = currentParams.ad ?: return false val minSize = currentParams.minSize ?: return false val maxSize = currentParams.maxSize ?: return false val minCoverageInMeters = currentParams.minCoverageInMeters ?: return false if (minSize < 0 || maxSize < 0 || minCoverageInMeters < 0f) { return false } if (LocationUtils.searchComplete(nearbyLocation.latitude, nearbyLocation.longitude, ad.aroundDiff)) { return false } val sizeCovered = this._sizeCovered.value ?: 0 if (sizeCovered < minSize) { return true // already loading } val distanceCoveredInMeters = this._distanceCoveredInMeters.value ?: 0f if (distanceCoveredInMeters < minCoverageInMeters) { return true // already loading } doLoadMore() return true // now loading } private fun doLoadMore() { val currentParams = this.params.value ?: NearbyParams() this.params.value = currentParams.copy( minSize = currentParams.minSize?.let { it * 2 } ?: LocationUtils.MIN_NEARBY_LIST, maxSize = currentParams.maxSize?.let { it * 2 } ?: LocationUtils.MAX_NEARBY_LIST, minCoverageInMeters = currentParams.minCoverageInMeters?.let { it * 2f } ?: run { val nearbyLocation = currentParams.nearbyLocation val ad = currentParams.ad if (nearbyLocation == null || ad == null) -1f else { LocationUtils.getAroundCoveredDistanceInMeters(nearbyLocation.latitude, nearbyLocation.longitude, ad.aroundDiff) }.coerceAtLeast(max(MIN_NEARBY_LIST_COVERAGE_IN_METERS, nearbyLocation?.accuracy ?: 0f)) }, ad = LocationUtils.incAroundDiff(currentParams.ad ?: LocationUtils.getNewDefaultAroundDiff()) ) } }
apache-2.0
1827f9e0339488668cf40a8853aa0482
44.207921
132
0.663564
4.689779
false
false
false
false
leafclick/intellij-community
platform/platform-api/src/com/intellij/ui/tabs/impl/EditorTabPainterAdapter.kt
1
1950
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.tabs.impl import com.intellij.openapi.util.registry.Registry import com.intellij.ui.tabs.JBTabPainter import com.intellij.ui.tabs.JBTabsPosition import java.awt.Graphics import java.awt.Graphics2D import java.awt.Rectangle class EditorTabPainterAdapter : TabPainterAdapter { private val magicOffset = 1 private val painter = JBEditorTabPainter() override val tabPainter: JBTabPainter get() = painter override fun paintBackground(label: TabLabel, g: Graphics, tabs: JBTabsImpl) { val info = label.info val isSelected = info == tabs.selectedInfo val rect = Rectangle(0, 0, label.width, label.height) val g2d = g as Graphics2D if (isSelected) { painter .paintSelectedTab(tabs.position, g2d, rect, tabs.borderThickness, info.tabColor, tabs.isActiveTabs(info), tabs.isHoveredTab(label)) paintBorders(g2d, label, tabs) } else { painter.paintTab(tabs.position, g2d, rect, tabs.borderThickness, info.tabColor, tabs.isActiveTabs(info), tabs.isHoveredTab(label)) paintBorders(g2d, label, tabs) } } private fun paintBorders(g: Graphics2D, label: TabLabel, tabs: JBTabsImpl) { if(tabs.position == JBTabsPosition.top && (Registry.`is`("ide.new.editor.tabs.vertical.borders") || !tabs.isSingleRow) || (tabs.position == JBTabsPosition.bottom && Registry.`is`("ide.new.editor.tabs.vertical.borders"))) { val rect = Rectangle(0, 0, label.width, label.height) val bounds = label.bounds if (bounds.x > magicOffset) { painter.paintLeftGap(tabs.position, g, rect, tabs.borderThickness) } if (bounds.x + bounds.width < tabs.width - magicOffset) { painter.paintRightGap(tabs.position, g, rect, tabs.borderThickness) } } } }
apache-2.0
ab6e5b91e6cb622507bd4acca9650840
35.811321
140
0.700513
3.77907
false
false
false
false
nobuoka/vc-oauth-java
ktor-twitter-login/src/main/kotlin/info/vividcode/ktor/twitter/login/application/ObtainTwitterTokenService.kt
1
4625
package info.vividcode.ktor.twitter.login.application import info.vividcode.ktor.twitter.login.ClientCredential import info.vividcode.ktor.twitter.login.TemporaryCredential import info.vividcode.ktor.twitter.login.TemporaryCredentialStore import info.vividcode.ktor.twitter.login.TwitterToken import info.vividcode.ktor.twitter.login.whatwg.parseWwwFormUrlEncoded import info.vividcode.oauth.HttpRequest import info.vividcode.oauth.OAuth import info.vividcode.oauth.OAuthCredentials import info.vividcode.oauth.ProtocolParameter import info.vividcode.oauth.protocol.ParameterTransmission import kotlinx.coroutines.withContext import okhttp3.Call import okhttp3.Request import okhttp3.RequestBody import java.io.IOException import kotlin.coroutines.CoroutineContext class ObtainTwitterTokenService( private val env: Required ) { interface Required { val oauth: OAuth val httpClient: Call.Factory val httpCallContext: CoroutineContext val temporaryCredentialStore: TemporaryCredentialStore } suspend fun obtainTwitterToken( clientCredential: ClientCredential, oauthToken: String, oauthVerifier: String ): TwitterToken { val temporaryCredential = env.temporaryCredentialStore.findTemporaryCredential(oauthToken) ?: throw TemporaryCredentialNotFoundException(oauthToken) val unauthorizedRequest = Request.Builder() .method("POST", RequestBody.create(null, ByteArray(0))) .url("https://api.twitter.com/oauth/access_token") .build() val authorizedRequest = authorize( unauthorizedRequest, clientCredential, temporaryCredential, listOf(ProtocolParameter.Verifier(oauthVerifier)) ) return withContext(env.httpCallContext) { try { env.httpClient.newCall(authorizedRequest).execute() } catch (exception: IOException) { throw TwitterCallFailedException("Request couldn't be executed", exception) }.use { response -> val body = response.body?.bytes() if (!response.isSuccessful) { val percentEncoded = body?.joinToString("") { String.format("%%%02X", it) } throw TwitterCallFailedException( "Response not successful (status code : ${response.code}, " + "percent-encoded response body : $percentEncoded))" ) } if (body != null) { val pairs = parseWwwFormUrlEncoded(body).toMap() val token = pairs["oauth_token"] val tokenSecret = pairs["oauth_token_secret"] val userId = pairs["user_id"] val screenName = pairs["screen_name"] if (token == null || tokenSecret == null || userId == null || screenName == null) { val percentEncoded = body.joinToString("") { String.format("%%%02X", it) } throw TwitterCallFailedException( "Unexpected response content " + "(percent-encoded response body : $percentEncoded)" ) } else { TwitterToken(token, tokenSecret, userId, screenName) } } else { throw TwitterCallFailedException("Not expected response content (response body is null)") } } } } private fun authorize( unauthorizedRequest: Request, clientCredential: ClientCredential, temporaryCredential: TemporaryCredential, additionalProtocolParameters: List<ProtocolParameter<*>> ): Request { val httpRequest = HttpRequest(unauthorizedRequest.method, unauthorizedRequest.url.toUrl()) val protocolParameters = env.oauth.generateProtocolParametersSigningWithHmacSha1( httpRequest, clientCredentials = OAuthCredentials(clientCredential.identifier, clientCredential.sharedSecret), temporaryOrTokenCredentials = OAuthCredentials(temporaryCredential.token, temporaryCredential.secret), additionalProtocolParameters = additionalProtocolParameters ) val authorizationHeaderString = ParameterTransmission.getAuthorizationHeaderString(protocolParameters, "") return unauthorizedRequest.newBuilder().header("Authorization", authorizationHeaderString).build() } }
apache-2.0
e08244bcd7c7253e11eb0f30bba53e11
43.471154
114
0.64173
5.619684
false
false
false
false
Scliang/KQuick
core/src/main/kotlin/FullScreenActivity.kt
1
1601
package com.scliang.kquick import android.os.Bundle import android.view.View import android.view.WindowManager /** * Created by scliang on 2017/6/12. * KQuick Library UI FullScreenActivity */ abstract class FullScreenActivity<D: KData> : BaseActivity<D>() { val BAR_COLOR = 0x11000000 fun fullWindow() { window.clearFlags( WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS or WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION ) // window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, // WindowManager.LayoutParams.FLAG_FULLSCREEN) if (hasNavigationBar()) { window.decorView.systemUiVisibility = // View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_STABLE } else { window.decorView.systemUiVisibility = // View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE } // window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) window.statusBarColor = BAR_COLOR window.navigationBarColor = BAR_COLOR supportActionBar?.hide() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) fullWindow() } }
apache-2.0
d52c5cb8904ca469111dc964f8daa7bf
36.255814
87
0.617739
4.736686
false
false
false
false
mpcjanssen/simpletask-android
app/src/cloudless/java/nl/mpcjanssen/simpletask/remote/FileStore.kt
1
7639
package nl.mpcjanssen.simpletask.remote import android.Manifest import android.content.pm.PackageManager import android.os.* import androidx.core.content.ContextCompat import android.util.Log import nl.mpcjanssen.simpletask.R import nl.mpcjanssen.simpletask.TodoApplication import nl.mpcjanssen.simpletask.util.Config import nl.mpcjanssen.simpletask.util.broadcastAuthFailed import nl.mpcjanssen.simpletask.util.join import nl.mpcjanssen.simpletask.util.writeToFile import java.io.File import java.io.FilenameFilter import java.util.* import kotlin.reflect.KClass object FileStore : IFileStore { private var lastSeenRemoteId by TodoApplication.config.StringOrNullPreference(R.string.file_current_version_id) override val isOnline = true private const val TAG = "FileStore" private var observer: TodoObserver? = null init { Log.i(TAG, "onCreate") Log.i(TAG, "Default path: ${getDefaultFile().path}") observer = null } override val isEncrypted: Boolean get() = false val isAuthenticated: Boolean get() { val externManager = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { Environment.isExternalStorageManager() } else { true } return ( ContextCompat.checkSelfPermission(TodoApplication.app, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) && externManager } override fun loadTasksFromFile(file: File): List<String> { if (!isAuthenticated) { broadcastAuthFailed(TodoApplication.app.localBroadCastManager) return emptyList() } Log.i(TAG, "Loading tasks") val lines = file.readLines() Log.i(TAG, "Read ${lines.size} lines from $file") setWatching(file) lastSeenRemoteId = file.lastModified().toString() return lines } override fun needSync(file: File): Boolean { if (!isAuthenticated) { broadcastAuthFailed(TodoApplication.app.localBroadCastManager) return true } return lastSeenRemoteId != file.lastModified().toString() } override fun todoNameChanged() { lastSeenRemoteId = "" } override fun writeFile(file: File, contents: String) { if (!isAuthenticated) { broadcastAuthFailed(TodoApplication.app.localBroadCastManager) return } Log.i(TAG, "Writing file to ${file.canonicalPath}") file.writeText(contents) } override fun readFile(file: File, fileRead: (contents: String) -> Unit) { if (!isAuthenticated) { broadcastAuthFailed(TodoApplication.app.localBroadCastManager) return } Log.i(TAG, "Reading file: ${file.path}") val contents: String val lines = file.readLines() contents = join(lines, "\n") fileRead(contents) } override fun loginActivity(): KClass<*>? { return LoginScreen::class } private fun setWatching(file: File) { Log.i(TAG, "Observer: adding folder watcher on ${file.parent}") val obs = observer if (obs != null && file.canonicalPath == obs.fileName) { Log.w(TAG, "Observer: already watching: ${file.canonicalPath}") return } else if (obs != null) { Log.w(TAG, "Observer: already watching different path: ${obs.fileName}") obs.ignoreEvents(true) obs.stopWatching() observer = null } observer = TodoObserver(file) Log.i(TAG, "Observer: modifying done") } override fun saveTasksToFile(file: File, lines: List<String>, eol: String) : File { if (!isAuthenticated) { broadcastAuthFailed(TodoApplication.app.localBroadCastManager) return file } Log.i(TAG, "Saving tasks to file: ${file.path}") val obs = observer obs?.ignoreEvents(true) writeFile(file, lines.joinToString(eol) + eol) obs?.delayedStartListen(1000) lastSeenRemoteId = file.lastModified().toString() return file } override fun appendTaskToFile(file: File, lines: List<String>, eol: String) { if (!isAuthenticated) { broadcastAuthFailed(TodoApplication.app.localBroadCastManager) return } Log.i(TAG, "Appending ${lines.size} tasks to ${file.path}") file.appendText(lines.joinToString(eol) + eol) } override fun logout() { } override fun getDefaultFile(): File { return File(TodoApplication.app.getExternalFilesDir(null), "todo.txt") } override fun loadFileList(file: File, txtOnly: Boolean): List<FileEntry> { if (!isAuthenticated) { broadcastAuthFailed(TodoApplication.app.localBroadCastManager) return emptyList() } val result = ArrayList<FileEntry>() if (file.canonicalPath == "/") { TodoApplication.app.getExternalFilesDir(null)?.let { result.add(FileEntry(it, true)) } } val filter = FilenameFilter { dir, filename -> val sel = File(dir,filename) if (!sel.canRead()) false else { if (sel.isDirectory) { result.add(FileEntry(File(filename), true)) } else { !txtOnly || filename.toLowerCase(Locale.getDefault()).endsWith(".txt") result.add(FileEntry(File(filename), false)) } } } // Run the file applyFilter for side effects file.list(filter) return result } class TodoObserver(val file: File) : FileObserver(file.canonicalPath) { private val tag = "FileWatchService" val fileName : String = file.canonicalPath private var ignoreEvents: Boolean = false private val handler: Handler private val delayedEnable = Runnable { Log.i(tag, "Observer: Delayed enabling events for: $fileName ") ignoreEvents(false) } init { this.startWatching() Log.i(tag, "Observer: creating observer on: $fileName") this.ignoreEvents = false this.handler = Handler(Looper.getMainLooper()) } fun ignoreEvents(ignore: Boolean) { Log.i(tag, "Observer: observing events on $fileName? ignoreEvents: $ignore") this.ignoreEvents = ignore } override fun onEvent(event: Int, eventPath: String?) { if (eventPath != null && eventPath == fileName) { Log.d(tag, "Observer event: $fileName:$event") if (event == CLOSE_WRITE || event == MODIFY || event == MOVED_TO) { if (ignoreEvents) { Log.i(tag, "Observer: ignored event on: $fileName") } else { Log.i(tag, "File changed {}$fileName") FileStore.remoteTodoFileChanged() } } } } fun delayedStartListen(ms: Int) { // Cancel any running timers handler.removeCallbacks(delayedEnable) // Reschedule Log.i(tag, "Observer: Adding delayed enabling to todoQueue") handler.postDelayed(delayedEnable, ms.toLong()) } } }
gpl-3.0
abf1cc4965c2a5bf1e407763c3d6cc5c
32.358079
115
0.585548
4.801383
false
false
false
false
JuliusKunze/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/serialization/DescriptorTable.kt
2
2913
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.backend.konan.serialization import kotlin.properties.Delegates import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.ir.descriptors.IrBuiltIns import org.jetbrains.kotlin.ir.declarations.IrFunction import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.serialization.deserialization.NameResolver import org.jetbrains.kotlin.serialization.ProtoBuf import org.jetbrains.kotlin.serialization.ProtoBuf.QualifiedNameTable.QualifiedName import org.jetbrains.kotlin.backend.konan.llvm.isExported import org.jetbrains.kotlin.backend.konan.llvm.typeInfoSymbolName import org.jetbrains.kotlin.backend.konan.llvm.symbolName import org.jetbrains.kotlin.backend.konan.llvm.localHash internal fun DeclarationDescriptor.symbolName(): String = when (this) { is FunctionDescriptor -> this.symbolName is PropertyDescriptor -> this.symbolName is ClassDescriptor -> this.typeInfoSymbolName else -> error("Unexpected exported descriptor: $this") } internal val DeclarationDescriptor.uniqId get() = this.symbolName().localHash.value // TODO: We don't manage id clashes anyhow now. class DescriptorTable(val builtIns: IrBuiltIns) { val table = mutableMapOf<DeclarationDescriptor, Long>() var currentIndex = 0L init { builtIns.irBuiltInDescriptors.forEach { table.put(it, it.uniqId) } } fun indexByValue(value: DeclarationDescriptor): Long { val index = table.getOrPut(value) { if (!value.isExported() || value is TypeParameterDescriptor) { currentIndex++ } else { value.uniqId } } return index } } class IrDeserializationDescriptorIndex(irBuiltIns: IrBuiltIns) { val map = mutableMapOf<Long, DeclarationDescriptor>() init { irBuiltIns.irBuiltInDescriptors.forEach { map.put(it.uniqId, it) } } } val IrBuiltIns.irBuiltInDescriptors get() = listOf<FunctionDescriptor>( this.eqeqeq, this.eqeq, this.lt0, this.lteq0, this.gt0, this.gteq0, this.throwNpe, this.booleanNot, this.noWhenBranchMatchedException, this.enumValueOf)
apache-2.0
829404591747314160fc1d2a66007179
29.34375
83
0.703742
4.373874
false
false
false
false
hannesa2/AndroidSlidingUpPanel
library/src/main/java/com/sothree/slidinguppanel/ViewDragHelper.kt
1
58285
/* * Copyright (C) 2013 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. */ @file:Suppress("unused") package com.sothree.slidinguppanel import android.content.Context import android.view.* import android.view.animation.Interpolator import android.widget.OverScroller import java.util.* /** * ViewDragHelper is a utility class for writing custom ViewGroups. It offers a number * of useful operations and state tracking for allowing a user to drag and reposition * views within their parent ViewGroup. */ @Suppress("MemberVisibilityCanBePrivate") open class ViewDragHelper private constructor(context: Context, forParent: ViewGroup, interpolator: Interpolator?, cb: Callback) { /** * Retrieve the current drag state of this helper. This will return one of * [.STATE_IDLE], [.STATE_DRAGGING] or [.STATE_SETTLING]. * * @return The current drag state */ // Current drag state; idle, dragging or settling var viewDragState = 0 private set /** * @return The minimum distance in pixels that the user must travel to initiate a drag */ // Distance to travel before a drag may begin var touchSlop: Int private set /** * @return The ID of the pointer currently dragging the captured view, * or [.INVALID_POINTER]. */ // Last known position/pointer tracking var activePointerId = INVALID_POINTER private set private var initialMotionX: FloatArray? = null private var initialMotionY: FloatArray? = null private var lastMotionX: FloatArray? = null private var lastMotionY: FloatArray? = null private var initialEdgesTouched: IntArray = IntArray(0) private var edgeDragsInProgress: IntArray = IntArray(0) private var edgeDragsLocked: IntArray = IntArray(0) private var pointersDown = 0 private var velocityTracker: VelocityTracker? = null private val maxVelocity: Float /** * Return the currently configured minimum velocity. Any flings with a magnitude less * than this value in pixels per second. Callback methods accepting a velocity will receive * zero as a velocity value if the real detected velocity was below this threshold. * * @return the minimum velocity that will be detected */ /** * Set the minimum velocity that will be detected as having a magnitude greater than zero * in pixels per second. Callback methods accepting a velocity will be clamped appropriately. * * @param minVelocity Minimum velocity to detect */ var minVelocity: Float /** * Return the size of an edge. This is the range in pixels along the edges of this view * that will actively detect edge touches or drags if edge tracking is enabled. * * @return The size of an edge in pixels * @see .setEdgeTrackingEnabled */ private val edgeSize: Int private var trackingEdges = 0 private val mScroller: OverScroller private val callback: Callback = cb /** * @return The currently captured view, or null if no view has been captured. */ var capturedView: View? = null private set private var releaseInProgress = false private val parentView: ViewGroup = forParent /** * Apps should use ViewDragHelper.create() to get a new instance. * This will allow VDH to use internal compatibility implementations for different * platform versions. * If the interpolator is null, the default interpolator will be used. */ init { val vc = ViewConfiguration.get(context) val density = context.resources.displayMetrics.density edgeSize = (EDGE_SIZE * density + 0.5f).toInt() touchSlop = vc.scaledTouchSlop maxVelocity = vc.scaledMaximumFlingVelocity.toFloat() minVelocity = vc.scaledMinimumFlingVelocity.toFloat() mScroller = OverScroller(context, interpolator ?: sInterpolator) } /** * A Callback is used as a communication channel with the ViewDragHelper back to the * parent view using it. `on*`methods are invoked on siginficant events and several * accessor methods are expected to provide the ViewDragHelper with more information * about the state of the parent view upon request. The callback also makes decisions * governing the range and draggability of child views. */ abstract class Callback { /** * Called when the drag state changes. See the `STATE_*` constants * for more information. * * @param state The new drag state * @see .STATE_IDLE * * @see .STATE_DRAGGING * * @see .STATE_SETTLING */ open fun onViewDragStateChanged(state: Int) {} /** * Called when the captured view's position changes as the result of a drag or settle. * * @param changedView View whose position changed * @param left New X coordinate of the left edge of the view * @param top New Y coordinate of the top edge of the view * @param dx Change in X position from the last call * @param dy Change in Y position from the last call */ open fun onViewPositionChanged(changedView: View?, left: Int, top: Int, dx: Int, dy: Int) {} /** * Called when a child view is captured for dragging or settling. The ID of the pointer * currently dragging the captured view is supplied. If activePointerId is * identified as [.INVALID_POINTER] the capture is programmatic instead of * pointer-initiated. * * @param capturedChild Child view that was captured * @param activePointerId Pointer id tracking the child capture */ open fun onViewCaptured(capturedChild: View?, activePointerId: Int) {} /** * Called when the child view is no longer being actively dragged. * The fling velocity is also supplied, if relevant. The velocity values may * be clamped to system minimums or maximums. * * * * Calling code may decide to fling or otherwise release the view to let it * settle into place. It should do so using [.settleCapturedViewAt] * or [.flingCapturedView]. If the Callback invokes * one of these methods, the ViewDragHelper will enter [.STATE_SETTLING] * and the view capture will not fully end until it comes to a complete stop. * If neither of these methods is invoked before `onViewReleased` returns, * the view will stop in place and the ViewDragHelper will return to * [.STATE_IDLE]. * * @param releasedChild The captured child view now being released * @param xvel X velocity of the pointer as it left the screen in pixels per second. * @param yvel Y velocity of the pointer as it left the screen in pixels per second. */ open fun onViewReleased(releasedChild: View?, xvel: Float, yvel: Float) {} /** * Called when one of the subscribed edges in the parent view has been touched * by the user while no child view is currently captured. * * @param edgeFlags A combination of edge flags describing the edge(s) currently touched * @param pointerId ID of the pointer touching the described edge(s) * @see .EDGE_LEFT * * @see .EDGE_TOP * * @see .EDGE_RIGHT * * @see .EDGE_BOTTOM */ fun onEdgeTouched(edgeFlags: Int, pointerId: Int) = Unit /** * Called when the given edge may become locked. This can happen if an edge drag * was preliminarily rejected before beginning, but after [.onEdgeTouched] * was called. This method should return true to lock this edge or false to leave it * unlocked. The default behavior is to leave edges unlocked. * * @param edgeFlags A combination of edge flags describing the edge(s) locked * @return true to lock the edge, false to leave it unlocked */ fun onEdgeLock(edgeFlags: Int) = false /** * Called when the user has started a deliberate drag away from one * of the subscribed edges in the parent view while no child view is currently captured. * * @param edgeFlags A combination of edge flags describing the edge(s) dragged * @param pointerId ID of the pointer touching the described edge(s) * @see .EDGE_LEFT * * @see .EDGE_TOP * * @see .EDGE_RIGHT * * @see .EDGE_BOTTOM */ fun onEdgeDragStarted(edgeFlags: Int, pointerId: Int) = Unit /** * Called to determine the Z-order of child views. * * @param index the ordered position to query for * @return index of the view that should be ordered at position `index` */ fun getOrderedChildIndex(index: Int) = index /** * Return the magnitude of a draggable child view's horizontal range of motion in pixels. * This method should return 0 for views that cannot move horizontally. * * @param child Child view to check * @return range of horizontal motion in pixels */ fun getViewHorizontalDragRange(child: View?) = 0 /** * Return the magnitude of a draggable child view's vertical range of motion in pixels. * This method should return 0 for views that cannot move vertically. * * @param child Child view to check * @return range of vertical motion in pixels */ open fun getViewVerticalDragRange(child: View?) = 0 /** * Called when the user's input indicates that they want to capture the given child view * with the pointer indicated by pointerId. The callback should return true if the user * is permitted to drag the given view with the indicated pointer. * * * * ViewDragHelper may call this method multiple times for the same view even if * the view is already captured; this indicates that a new pointer is trying to take * control of the view. * * * * If this method returns true, a call to [.onViewCaptured] * will follow if the capture is successful. * * @param child Child the user is attempting to capture * @param pointerId ID of the pointer attempting the capture * @return true if capture should be allowed, false otherwise */ abstract fun tryCaptureView(child: View?, pointerId: Int): Boolean /** * Restrict the motion of the dragged child view along the horizontal axis. * The default implementation does not allow horizontal motion; the extending * class must override this method and provide the desired clamping. * * @param child Child view being dragged * @param left Attempted motion along the X axis * @param dx Proposed change in position for left * @return The new clamped position for left */ fun clampViewPositionHorizontal(child: View?, left: Int, dx: Int) = 0 /** * Restrict the motion of the dragged child view along the vertical axis. * The default implementation does not allow vertical motion; the extending * class must override this method and provide the desired clamping. * * @param child Child view being dragged * @param top Attempted motion along the Y axis * @param dy Proposed change in position for top * @return The new clamped position for top */ open fun clampViewPositionVertical(child: View?, top: Int, dy: Int) = 0 } private val setIdleRunnable = Runnable { setDragState(STATE_IDLE) } /** * Enable edge tracking for the selected edges of the parent view. * The callback's [Callback.onEdgeTouched] and * [Callback.onEdgeDragStarted] methods will only be invoked * for edges for which edge tracking has been enabled. * * @param edgeFlags Combination of edge flags describing the edges to watch * @see .EDGE_LEFT * * @see .EDGE_TOP * * @see .EDGE_RIGHT * * @see .EDGE_BOTTOM */ fun setEdgeTrackingEnabled(edgeFlags: Int) { trackingEdges = edgeFlags } /** * Capture a specific child view for dragging within the parent. The callback will be notified * but [Callback.tryCaptureView] will not be asked permission to * capture this view. * * @param childView Child view to capture * @param activePointerId ID of the pointer that is dragging the captured child view */ fun captureChildView(childView: View, activePointerId: Int) { require(!(childView.parent !== parentView)) { "captureChildView: parameter must be a descendant of the ViewDragHelper's tracked parent view ($parentView)" } capturedView = childView this.activePointerId = activePointerId callback.onViewCaptured(childView, activePointerId) setDragState(STATE_DRAGGING) } /** * The result of a call to this method is equivalent to * [.processTouchEvent] receiving an ACTION_CANCEL event. */ fun cancel() { activePointerId = INVALID_POINTER clearMotionHistory() if (velocityTracker != null) { velocityTracker!!.recycle() velocityTracker = null } } /** * [.cancel], but also abort all motion in progress and snap to the end of any * animation. */ fun abort() { cancel() if (viewDragState == STATE_SETTLING) { val oldX = mScroller.currX val oldY = mScroller.currY mScroller.abortAnimation() val newX = mScroller.currX val newY = mScroller.currY callback.onViewPositionChanged(capturedView, newX, newY, newX - oldX, newY - oldY) } setDragState(STATE_IDLE) } /** * Animate the view `child` to the given (left, top) position. * If this method returns true, the caller should invoke [.continueSettling] * on each subsequent frame to continue the motion until it returns false. If this method * returns false there is no further work to do to complete the movement. * * * * This operation does not count as a capture event, though [.getCapturedView] * will still report the sliding view while the slide is in progress. * * @param child Child view to capture and animate * @param finalLeft Final left position of child * @param finalTop Final top position of child * @return true if animation should continue through [.continueSettling] calls */ fun smoothSlideViewTo(child: View?, finalLeft: Int, finalTop: Int): Boolean { capturedView = child activePointerId = INVALID_POINTER return forceSettleCapturedViewAt(finalLeft, finalTop, 0, 0) } /** * Settle the captured view at the given (left, top) position. * The appropriate velocity from prior motion will be taken into account. * If this method returns true, the caller should invoke [.continueSettling] * on each subsequent frame to continue the motion until it returns false. If this method * returns false there is no further work to do to complete the movement. * * @param finalLeft Settled left edge position for the captured view * @param finalTop Settled top edge position for the captured view * @return true if animation should continue through [.continueSettling] calls */ fun settleCapturedViewAt(finalLeft: Int, finalTop: Int): Boolean { check(releaseInProgress) { "Cannot settleCapturedViewAt outside of a call to " + "Callback#onViewReleased" } return forceSettleCapturedViewAt( finalLeft, finalTop, velocityTracker!!.getXVelocity(activePointerId).toInt(), velocityTracker!!.getYVelocity(activePointerId).toInt() ) } /** * Settle the captured view at the given (left, top) position. * * @param finalLeft Target left position for the captured view * @param finalTop Target top position for the captured view * @param xvel Horizontal velocity * @param yvel Vertical velocity * @return true if animation should continue through [.continueSettling] calls */ private fun forceSettleCapturedViewAt(finalLeft: Int, finalTop: Int, xvel: Int, yvel: Int): Boolean { val startLeft = capturedView!!.left val startTop = capturedView!!.top val dx = finalLeft - startLeft val dy = finalTop - startTop if (dx == 0 && dy == 0) { // Nothing to do. Send callbacks, be done. mScroller.abortAnimation() setDragState(STATE_IDLE) return false } val duration = computeSettleDuration(capturedView, dx, dy, xvel, yvel) mScroller.startScroll(startLeft, startTop, dx, dy, duration) setDragState(STATE_SETTLING) return true } private fun computeSettleDuration(child: View?, dx: Int, dy: Int, inputXvel: Int, inputYvel: Int): Int { var xvel = inputXvel var yvel = inputYvel xvel = clampMag(xvel, minVelocity.toInt(), maxVelocity.toInt()) yvel = clampMag(yvel, minVelocity.toInt(), maxVelocity.toInt()) val absDx = Math.abs(dx) val absDy = Math.abs(dy) val absXVel = Math.abs(xvel) val absYVel = Math.abs(yvel) val addedVel = absXVel + absYVel val addedDistance = absDx + absDy val xWeight = if (xvel != 0) absXVel.toFloat() / addedVel else absDx.toFloat() / addedDistance val yWeight = if (yvel != 0) absYVel.toFloat() / addedVel else absDy.toFloat() / addedDistance val xDuration = computeAxisDuration(dx, xvel, callback.getViewHorizontalDragRange(child)) val yDuration = computeAxisDuration(dy, yvel, callback.getViewVerticalDragRange(child)) return (xDuration * xWeight + yDuration * yWeight).toInt() } private fun computeAxisDuration(delta: Int, inputVelocity: Int, motionRange: Int): Int { var velocity = inputVelocity if (delta == 0) { return 0 } val width = parentView.width val halfWidth = width / 2 val distanceRatio = Math.min(1f, Math.abs(delta).toFloat() / width) val distance = halfWidth + halfWidth * distanceInfluenceForSnapDuration(distanceRatio) val duration: Int velocity = Math.abs(velocity) duration = if (velocity > 0) { 4 * Math.round(1000 * Math.abs(distance / velocity)) } else { val range = Math.abs(delta).toFloat() / motionRange ((range + 1) * BASE_SETTLE_DURATION).toInt() } return Math.min(duration, MAX_SETTLE_DURATION) } /** * Clamp the magnitude of value for absMin and absMax. * If the value is below the minimum, it will be clamped to zero. * If the value is above the maximum, it will be clamped to the maximum. * * @param value Value to clamp * @param absMin Absolute value of the minimum significant value to return * @param absMax Absolute value of the maximum value to return * @return The clamped value with the same sign as `value` */ private fun clampMag(value: Int, absMin: Int, absMax: Int): Int { val absValue = Math.abs(value) if (absValue < absMin) return 0 return if (absValue > absMax) if (value > 0) absMax else -absMax else value } /** * Clamp the magnitude of value for absMin and absMax. * If the value is below the minimum, it will be clamped to zero. * If the value is above the maximum, it will be clamped to the maximum. * * @param value Value to clamp * @param absMin Absolute value of the minimum significant value to return * @param absMax Absolute value of the maximum value to return * @return The clamped value with the same sign as `value` */ private fun clampMag(value: Float, absMin: Float, absMax: Float): Float { val absValue = Math.abs(value) if (absValue < absMin) return 0f return if (absValue > absMax) if (value > 0) absMax else -absMax else value } private fun distanceInfluenceForSnapDuration(value: Float): Float { var f = value f -= 0.5f // center the values about 0. f *= (0.3f * Math.PI / 2.0f).toFloat() return Math.sin(f.toDouble()).toFloat() } /** * Settle the captured view based on standard free-moving fling behavior. * The caller should invoke [.continueSettling] on each subsequent frame * to continue the motion until it returns false. * * @param minLeft Minimum X position for the view's left edge * @param minTop Minimum Y position for the view's top edge * @param maxLeft Maximum X position for the view's left edge * @param maxTop Maximum Y position for the view's top edge */ fun flingCapturedView(minLeft: Int, minTop: Int, maxLeft: Int, maxTop: Int) { check(releaseInProgress) { "Cannot flingCapturedView outside of a call to " + "Callback#onViewReleased" } mScroller.fling( capturedView!!.left, capturedView!!.top, velocityTracker!!.getXVelocity(activePointerId).toInt(), velocityTracker!!.getYVelocity(activePointerId).toInt(), minLeft, maxLeft, minTop, maxTop ) setDragState(STATE_SETTLING) } /** * Move the captured settling view by the appropriate amount for the current time. * If `continueSettling` returns true, the caller should call it again * on the next frame to continue. * * @param deferCallbacks true if state callbacks should be deferred via posted message. * Set this to true if you are calling this method from * [android.view.View.computeScroll] or similar methods * invoked as part of layout or drawing. * @return true if settle is still in progress */ fun continueSettling(deferCallbacks: Boolean): Boolean { // Make sure, there is a captured view if (capturedView == null) { return false } if (viewDragState == STATE_SETTLING) { var keepGoing = mScroller.computeScrollOffset() val x = mScroller.currX val y = mScroller.currY val dx = x - capturedView!!.left val dy = y - capturedView!!.top if (!keepGoing && dy != 0) { //fix #525 //Invalid drag state capturedView!!.top = 0 return true } if (dx != 0) { capturedView!!.offsetLeftAndRight(dx) } if (dy != 0) { capturedView!!.offsetTopAndBottom(dy) } if (dx != 0 || dy != 0) { callback.onViewPositionChanged(capturedView, x, y, dx, dy) } if (keepGoing && x == mScroller.finalX && y == mScroller.finalY) { // Close enough. The interpolator/scroller might think we're still moving // but the user sure doesn't. mScroller.abortAnimation() keepGoing = mScroller.isFinished } if (!keepGoing) { if (deferCallbacks) { parentView.post(setIdleRunnable) } else { setDragState(STATE_IDLE) } } } return viewDragState == STATE_SETTLING } /** * Like all callback events this must happen on the UI thread, but release * involves some extra semantics. During a release (mReleaseInProgress) * is the only time it is valid to call [.settleCapturedViewAt] * or [.flingCapturedView]. */ private fun dispatchViewReleased(xvel: Float, yvel: Float) { releaseInProgress = true callback.onViewReleased(capturedView, xvel, yvel) releaseInProgress = false if (viewDragState == STATE_DRAGGING) { // onViewReleased didn't call a method that would have changed this. Go idle. setDragState(STATE_IDLE) } } private fun clearMotionHistory() { if (initialMotionX == null) { return } Arrays.fill(initialMotionX, 0f) Arrays.fill(initialMotionY, 0f) Arrays.fill(lastMotionX, 0f) Arrays.fill(lastMotionY, 0f) Arrays.fill(initialEdgesTouched, 0) Arrays.fill(edgeDragsInProgress, 0) Arrays.fill(edgeDragsLocked, 0) pointersDown = 0 } private fun clearMotionHistory(pointerId: Int) { if (initialMotionX == null || initialMotionX!!.size <= pointerId) { return } initialMotionX!![pointerId] = 0f initialMotionY!![pointerId] = 0f lastMotionX!![pointerId] = 0f lastMotionY!![pointerId] = 0f initialEdgesTouched[pointerId] = 0 edgeDragsInProgress[pointerId] = 0 edgeDragsLocked[pointerId] = 0 pointersDown = pointersDown and (1 shl pointerId).inv() } private fun ensureMotionHistorySizeForId(pointerId: Int) { if (initialMotionX == null || initialMotionX!!.size <= pointerId) { val imx = FloatArray(pointerId + 1) val imy = FloatArray(pointerId + 1) val lmx = FloatArray(pointerId + 1) val lmy = FloatArray(pointerId + 1) val iit = IntArray(pointerId + 1) val edip = IntArray(pointerId + 1) val edl = IntArray(pointerId + 1) if (initialMotionX != null) { System.arraycopy(initialMotionX!!, 0, imx, 0, initialMotionX!!.size) System.arraycopy(initialMotionY!!, 0, imy, 0, initialMotionY!!.size) System.arraycopy(lastMotionX!!, 0, lmx, 0, lastMotionX!!.size) System.arraycopy(lastMotionY!!, 0, lmy, 0, lastMotionY!!.size) System.arraycopy(initialEdgesTouched, 0, iit, 0, initialEdgesTouched.size) System.arraycopy(edgeDragsInProgress, 0, edip, 0, edgeDragsInProgress.size) System.arraycopy(edgeDragsLocked, 0, edl, 0, edgeDragsLocked.size) } initialMotionX = imx initialMotionY = imy lastMotionX = lmx lastMotionY = lmy initialEdgesTouched = iit edgeDragsInProgress = edip edgeDragsLocked = edl } } private fun saveInitialMotion(x: Float, y: Float, pointerId: Int) { ensureMotionHistorySizeForId(pointerId) lastMotionX!![pointerId] = x initialMotionX!![pointerId] = lastMotionX!![pointerId] lastMotionY!![pointerId] = y initialMotionY!![pointerId] = lastMotionY!![pointerId] initialEdgesTouched[pointerId] = getEdgesTouched(x.toInt(), y.toInt()) pointersDown = pointersDown or (1 shl pointerId) } private fun saveLastMotion(ev: MotionEvent) { val pointerCount = ev.pointerCount for (i in 0 until pointerCount) { val pointerId = ev.getPointerId(i) val x = ev.getX(i) val y = ev.getY(i) // Sometimes we can try and save last motion for a pointer never recorded in initial motion. In this case we just discard it. if (lastMotionX != null && lastMotionY != null && lastMotionX!!.size > pointerId && lastMotionY!!.size > pointerId) { lastMotionX!![pointerId] = x lastMotionY!![pointerId] = y } } } /** * Check if the given pointer ID represents a pointer that is currently down (to the best * of the ViewDragHelper's knowledge). * * * * The state used to report this information is populated by the methods * [.shouldInterceptTouchEvent] or * [.processTouchEvent]. If one of these methods has not * been called for all relevant MotionEvents to track, the information reported * by this method may be stale or incorrect. * * @param pointerId pointer ID to check; corresponds to IDs provided by MotionEvent * @return true if the pointer with the given ID is still down */ fun isPointerDown(pointerId: Int): Boolean { return pointersDown and 1 shl pointerId != 0 } fun setDragState(state: Int) { if (viewDragState != state) { viewDragState = state callback.onViewDragStateChanged(state) if (viewDragState == STATE_IDLE) { capturedView = null } } } /** * Attempt to capture the view with the given pointer ID. The callback will be involved. * This will put us into the "dragging" state. If we've already captured this view with * this pointer this method will immediately return true without consulting the callback. * * @param toCapture View to capture * @param pointerId Pointer to capture with * @return true if capture was successful */ fun tryCaptureViewForDrag(toCapture: View?, pointerId: Int): Boolean { if (toCapture === capturedView && activePointerId == pointerId) { // Already done! return true } if (toCapture != null && callback.tryCaptureView(toCapture, pointerId)) { activePointerId = pointerId captureChildView(toCapture, pointerId) return true } return false } /** * Tests scrollability within child views of v given a delta of dx. * * @param v View to test for horizontal scrollability * @param checkV Whether the view v passed should itself be checked for scrollability (true), * or just its children (false). * @param dx Delta scrolled in pixels along the X axis * @param dy Delta scrolled in pixels along the Y axis * @param x X coordinate of the active touch point * @param y Y coordinate of the active touch point * @return true if child views of v can be scrolled by delta of dx. */ protected fun canScroll(v: View, checkV: Boolean, dx: Int, dy: Int, x: Int, y: Int): Boolean { if (v is ViewGroup) { val scrollX = v.getScrollX() val scrollY = v.getScrollY() val count = v.childCount // Count backwards - let topmost views consume scroll distance first. for (i in count - 1 downTo 0) { // TODO: Add versioned support here for transformed views. // This will not work for transformed views in Honeycomb+ val child = v.getChildAt(i) if (x + scrollX >= child.left && x + scrollX < child.right && y + scrollY >= child.top && y + scrollY < child.bottom && canScroll( child, true, dx, dy, x + scrollX - child.left, y + scrollY - child.top ) ) { return true } } } return checkV && (v.canScrollHorizontally(-dx) || v.canScrollVertically(-dy)) } /** * Check if this event as provided to the parent view's onInterceptTouchEvent should * cause the parent to intercept the touch event stream. * * @param ev MotionEvent provided to onInterceptTouchEvent * @return true if the parent view should return true from onInterceptTouchEvent */ fun shouldInterceptTouchEvent(ev: MotionEvent): Boolean { val action = ev.action val actionIndex = ev.actionIndex if (action == MotionEvent.ACTION_DOWN) { // Reset things for a new event stream, just in case we didn't get // the whole previous stream. cancel() } if (velocityTracker == null) { velocityTracker = VelocityTracker.obtain() } velocityTracker!!.addMovement(ev) when (action) { MotionEvent.ACTION_DOWN -> { val x = ev.x val y = ev.y val pointerId = ev.getPointerId(0) saveInitialMotion(x, y, pointerId) val toCapture = findTopChildUnder(x.toInt(), y.toInt()) // Catch a settling view if possible. if (toCapture === capturedView && viewDragState == STATE_SETTLING) { tryCaptureViewForDrag(toCapture, pointerId) } val edgesTouched = initialEdgesTouched[pointerId] if (edgesTouched and trackingEdges != 0) { callback.onEdgeTouched(edgesTouched and trackingEdges, pointerId) } } MotionEvent.ACTION_POINTER_DOWN -> { val pointerId = ev.getPointerId(actionIndex) val x = ev.getX(actionIndex) val y = ev.getY(actionIndex) saveInitialMotion(x, y, pointerId) // A ViewDragHelper can only manipulate one view at a time. if (viewDragState == STATE_IDLE) { val edgesTouched = initialEdgesTouched[pointerId] if (edgesTouched and trackingEdges != 0) { callback.onEdgeTouched(edgesTouched and trackingEdges, pointerId) } } else if (viewDragState == STATE_SETTLING) { // Catch a settling view if possible. val toCapture = findTopChildUnder(x.toInt(), y.toInt()) if (toCapture === capturedView) { tryCaptureViewForDrag(toCapture, pointerId) } } } MotionEvent.ACTION_MOVE -> { // First to cross a touch slop over a draggable view wins. Also report edge drags. val pointerCount = ev.pointerCount var i = 0 while (i < pointerCount && initialMotionX != null && initialMotionY != null) { val pointerId = ev.getPointerId(i) if (pointerId >= initialMotionX!!.size || pointerId >= initialMotionY!!.size) { i++ continue } val x = ev.getX(i) val y = ev.getY(i) val dx = x - initialMotionX!![pointerId] val dy = y - initialMotionY!![pointerId] reportNewEdgeDrags(dx, dy, pointerId) if (viewDragState == STATE_DRAGGING) { // Callback might have started an edge drag break } val toCapture = findTopChildUnder( initialMotionX!![pointerId].toInt(), initialMotionY!![pointerId].toInt() ) if (toCapture != null && checkTouchSlop(toCapture, dx, dy) && tryCaptureViewForDrag(toCapture, pointerId) ) { break } i++ } saveLastMotion(ev) } MotionEvent.ACTION_POINTER_UP -> { val pointerId = ev.getPointerId(actionIndex) clearMotionHistory(pointerId) } MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { cancel() } } return viewDragState == STATE_DRAGGING } /** * Process a touch event received by the parent view. This method will dispatch callback events * as needed before returning. The parent view's onTouchEvent implementation should call this. * * @param ev The touch event received by the parent view */ fun processTouchEvent(ev: MotionEvent) { val action = ev.action val actionIndex = ev.actionIndex if (action == MotionEvent.ACTION_DOWN) { // Reset things for a new event stream, just in case we didn't get // the whole previous stream. cancel() } if (velocityTracker == null) { velocityTracker = VelocityTracker.obtain() } velocityTracker!!.addMovement(ev) when (action) { MotionEvent.ACTION_DOWN -> { val x = ev.x val y = ev.y val pointerId = ev.getPointerId(0) val toCapture = findTopChildUnder(x.toInt(), y.toInt()) saveInitialMotion(x, y, pointerId) // Since the parent is already directly processing this touch event, // there is no reason to delay for a slop before dragging. // Start immediately if possible. tryCaptureViewForDrag(toCapture, pointerId) val edgesTouched = initialEdgesTouched[pointerId] if (edgesTouched and trackingEdges != 0) { callback.onEdgeTouched(edgesTouched and trackingEdges, pointerId) } } MotionEvent.ACTION_POINTER_DOWN -> { val pointerId = ev.getPointerId(actionIndex) val x = ev.getX(actionIndex) val y = ev.getY(actionIndex) saveInitialMotion(x, y, pointerId) // A ViewDragHelper can only manipulate one view at a time. if (viewDragState == STATE_IDLE) { // If we're idle we can do anything! Treat it like a normal down event. val toCapture = findTopChildUnder(x.toInt(), y.toInt()) tryCaptureViewForDrag(toCapture, pointerId) val edgesTouched = initialEdgesTouched[pointerId] if (edgesTouched and trackingEdges != 0) { callback.onEdgeTouched(edgesTouched and trackingEdges, pointerId) } } else if (isCapturedViewUnder(x.toInt(), y.toInt())) { // We're still tracking a captured view. If the same view is under this // point, we'll swap to controlling it with this pointer instead. // (This will still work if we're "catching" a settling view.) tryCaptureViewForDrag(capturedView, pointerId) } } MotionEvent.ACTION_MOVE -> { if (viewDragState == STATE_DRAGGING) { val index = ev.findPointerIndex(activePointerId) val x = ev.getX(index) val y = ev.getY(index) val idx = (x - lastMotionX!![activePointerId]).toInt() val idy = (y - lastMotionY!![activePointerId]).toInt() dragTo(capturedView!!.left + idx, capturedView!!.top + idy, idx, idy) saveLastMotion(ev) } else { // Check to see if any pointer is now over a draggable view. val pointerCount = ev.pointerCount var i = 0 while (i < pointerCount) { val pointerId = ev.getPointerId(i) val x = ev.getX(i) val y = ev.getY(i) val dx = x - initialMotionX!![pointerId] val dy = y - initialMotionY!![pointerId] reportNewEdgeDrags(dx, dy, pointerId) if (viewDragState == STATE_DRAGGING) { // Callback might have started an edge drag. break } val toCapture = findTopChildUnder( initialMotionX!![pointerId].toInt(), initialMotionY!![pointerId].toInt() ) if (checkTouchSlop(toCapture, dx, dy) && tryCaptureViewForDrag(toCapture, pointerId) ) { break } i++ } saveLastMotion(ev) } } MotionEvent.ACTION_POINTER_UP -> { val pointerId = ev.getPointerId(actionIndex) if (viewDragState == STATE_DRAGGING && pointerId == activePointerId) { // Try to find another pointer that's still holding on to the captured view. var newActivePointer = INVALID_POINTER val pointerCount = ev.pointerCount var i = 0 while (i < pointerCount) { val id = ev.getPointerId(i) if (id == activePointerId) { // This one's going away, skip. i++ continue } val x = ev.getX(i) val y = ev.getY(i) if (findTopChildUnder(x.toInt(), y.toInt()) === capturedView && tryCaptureViewForDrag(capturedView, id) ) { newActivePointer = activePointerId break } i++ } if (newActivePointer == INVALID_POINTER) { // We didn't find another pointer still touching the view, release it. releaseViewForPointerUp() } } clearMotionHistory(pointerId) } MotionEvent.ACTION_UP -> { if (viewDragState == STATE_DRAGGING) { releaseViewForPointerUp() } cancel() } MotionEvent.ACTION_CANCEL -> { if (viewDragState == STATE_DRAGGING) { dispatchViewReleased(0f, 0f) } cancel() } } } private fun reportNewEdgeDrags(dx: Float, dy: Float, pointerId: Int) { var dragsStarted = 0 if (checkNewEdgeDrag(dx, dy, pointerId, EDGE_LEFT)) { dragsStarted = dragsStarted or EDGE_LEFT } if (checkNewEdgeDrag(dy, dx, pointerId, EDGE_TOP)) { dragsStarted = dragsStarted or EDGE_TOP } if (checkNewEdgeDrag(dx, dy, pointerId, EDGE_RIGHT)) { dragsStarted = dragsStarted or EDGE_RIGHT } if (checkNewEdgeDrag(dy, dx, pointerId, EDGE_BOTTOM)) { dragsStarted = dragsStarted or EDGE_BOTTOM } if (dragsStarted != 0) { edgeDragsInProgress[pointerId] = edgeDragsInProgress[pointerId] or dragsStarted callback.onEdgeDragStarted(dragsStarted, pointerId) } } private fun checkNewEdgeDrag(delta: Float, odelta: Float, pointerId: Int, edge: Int): Boolean { val absDelta = Math.abs(delta) val absODelta = Math.abs(odelta) if (initialEdgesTouched[pointerId] and edge != edge || trackingEdges and edge == 0 || edgeDragsLocked[pointerId] and edge == edge || edgeDragsInProgress[pointerId] and edge == edge || absDelta <= touchSlop && absODelta <= touchSlop ) { return false } if (absDelta < absODelta * 0.5f && callback.onEdgeLock(edge)) { edgeDragsLocked[pointerId] = edgeDragsLocked[pointerId] or edge return false } return edgeDragsInProgress[pointerId] and edge == 0 && absDelta > touchSlop } /** * Check if we've crossed a reasonable touch slop for the given child view. * If the child cannot be dragged along the horizontal or vertical axis, motion * along that axis will not count toward the slop check. * * @param child Child to check * @param dx Motion since initial position along X axis * @param dy Motion since initial position along Y axis * @return true if the touch slop has been crossed */ private fun checkTouchSlop(child: View?, dx: Float, dy: Float): Boolean { if (child == null) { return false } val checkHorizontal = callback.getViewHorizontalDragRange(child) > 0 val checkVertical = callback.getViewVerticalDragRange(child) > 0 if (checkHorizontal && checkVertical) { return dx * dx + dy * dy > touchSlop * touchSlop } else if (checkHorizontal) { return Math.abs(dx) > touchSlop } else if (checkVertical) { return Math.abs(dy) > touchSlop } return false } /** * Check if any pointer tracked in the current gesture has crossed * the required slop threshold. * * * * This depends on internal state populated by * [.shouldInterceptTouchEvent] or * [.processTouchEvent]. You should only rely on * the results of this method after all currently available touch data * has been provided to one of these two methods. * * @param directions Combination of direction flags, see [.DIRECTION_HORIZONTAL], * [.DIRECTION_VERTICAL], [.DIRECTION_ALL] * @return true if the slop threshold has been crossed, false otherwise */ fun checkTouchSlop(directions: Int): Boolean { val count = initialMotionX!!.size for (i in 0 until count) { if (checkTouchSlop(directions, i)) { return true } } return false } /** * Check if the specified pointer tracked in the current gesture has crossed * the required slop threshold. * * * * This depends on internal state populated by * [.shouldInterceptTouchEvent] or * [.processTouchEvent]. You should only rely on * the results of this method after all currently available touch data * has been provided to one of these two methods. * * @param directions Combination of direction flags, see [.DIRECTION_HORIZONTAL], * [.DIRECTION_VERTICAL], [.DIRECTION_ALL] * @param pointerId ID of the pointer to slop check as specified by MotionEvent * @return true if the slop threshold has been crossed, false otherwise */ fun checkTouchSlop(directions: Int, pointerId: Int): Boolean { if (!isPointerDown(pointerId)) { return false } val checkHorizontal = directions and DIRECTION_HORIZONTAL == DIRECTION_HORIZONTAL val checkVertical = directions and DIRECTION_VERTICAL == DIRECTION_VERTICAL val dx = lastMotionX!![pointerId] - initialMotionX!![pointerId] val dy = lastMotionY!![pointerId] - initialMotionY!![pointerId] if (checkHorizontal && checkVertical) { return dx * dx + dy * dy > touchSlop * touchSlop } else if (checkHorizontal) { return Math.abs(dx) > touchSlop } else if (checkVertical) { return Math.abs(dy) > touchSlop } return false } /** * Check if any of the edges specified were initially touched in the currently active gesture. * If there is no currently active gesture this method will return false. * * @param edges Edges to check for an initial edge touch. See [.EDGE_LEFT], * [.EDGE_TOP], [.EDGE_RIGHT], [.EDGE_BOTTOM] and * [.EDGE_ALL] * @return true if any of the edges specified were initially touched in the current gesture */ fun isEdgeTouched(edges: Int): Boolean { val count = initialEdgesTouched.size for (i in 0 until count) { if (isEdgeTouched(edges, i)) { return true } } return false } /** * Check if any of the edges specified were initially touched by the pointer with * the specified ID. If there is no currently active gesture or if there is no pointer with * the given ID currently down this method will return false. * * @param edges Edges to check for an initial edge touch. See [.EDGE_LEFT], * [.EDGE_TOP], [.EDGE_RIGHT], [.EDGE_BOTTOM] and * [.EDGE_ALL] * @return true if any of the edges specified were initially touched in the current gesture */ fun isEdgeTouched(edges: Int, pointerId: Int): Boolean { return isPointerDown(pointerId) && initialEdgesTouched[pointerId] and edges != 0 } val isDragging: Boolean get() = viewDragState == STATE_DRAGGING private fun releaseViewForPointerUp() { velocityTracker!!.computeCurrentVelocity(1000, maxVelocity) val xvel = clampMag( velocityTracker!!.getXVelocity(activePointerId), minVelocity, maxVelocity ) val yvel = clampMag( velocityTracker!!.getYVelocity(activePointerId), minVelocity, maxVelocity ) dispatchViewReleased(xvel, yvel) } private fun dragTo(left: Int, top: Int, dx: Int, dy: Int) { var clampedX = left var clampedY = top val oldLeft = capturedView!!.left val oldTop = capturedView!!.top if (dx != 0) { clampedX = callback.clampViewPositionHorizontal(capturedView, left, dx) capturedView!!.offsetLeftAndRight(clampedX - oldLeft) } if (dy != 0) { clampedY = callback.clampViewPositionVertical(capturedView, top, dy) capturedView!!.offsetTopAndBottom(clampedY - oldTop) } if (dx != 0 || dy != 0) { val clampedDx = clampedX - oldLeft val clampedDy = clampedY - oldTop callback.onViewPositionChanged( capturedView, clampedX, clampedY, clampedDx, clampedDy ) } } /** * Determine if the currently captured view is under the given point in the * parent view's coordinate system. If there is no captured view this method * will return false. * * @param x X position to test in the parent's coordinate system * @param y Y position to test in the parent's coordinate system * @return true if the captured view is under the given point, false otherwise */ fun isCapturedViewUnder(x: Int, y: Int): Boolean { return isViewUnder(capturedView, x, y) } /** * Determine if the supplied view is under the given point in the * parent view's coordinate system. * * @param view Child view of the parent to hit test * @param x X position to test in the parent's coordinate system * @param y Y position to test in the parent's coordinate system * @return true if the supplied view is under the given point, false otherwise */ fun isViewUnder(view: View?, x: Int, y: Int): Boolean { return if (view == null) { false } else x >= view.left && x < view.right && y >= view.top && y < view.bottom } /** * Find the topmost child under the given point within the parent view's coordinate system. * The child order is determined using [Callback.getOrderedChildIndex]. * * @param x X position to test in the parent's coordinate system * @param y Y position to test in the parent's coordinate system * @return The topmost child view under (x, y) or null if none found. */ fun findTopChildUnder(x: Int, y: Int): View? { val childCount = parentView.childCount for (i in childCount - 1 downTo 0) { val child = parentView.getChildAt(callback.getOrderedChildIndex(i)) if (x >= child.left && x < child.right && y >= child.top && y < child.bottom) { return child } } return null } private fun getEdgesTouched(x: Int, y: Int): Int { var result = 0 if (x < parentView.left + edgeSize) result = result or EDGE_LEFT if (y < parentView.top + edgeSize) result = result or EDGE_TOP if (x > parentView.right - edgeSize) result = result or EDGE_RIGHT if (y > parentView.bottom - edgeSize) result = result or EDGE_BOTTOM return result } companion object { /** * A null/invalid pointer ID. */ const val INVALID_POINTER = -1 /** * A view is not currently being dragged or animating as a result of a fling/snap. */ const val STATE_IDLE = 0 /** * A view is currently being dragged. The position is currently changing as a result * of user input or simulated user input. */ const val STATE_DRAGGING = 1 /** * A view is currently settling into place as a result of a fling or * predefined non-interactive motion. */ const val STATE_SETTLING = 2 /** * Edge flag indicating that the left edge should be affected. */ const val EDGE_LEFT = 1 shl 0 /** * Edge flag indicating that the right edge should be affected. */ const val EDGE_RIGHT = 1 shl 1 /** * Edge flag indicating that the top edge should be affected. */ const val EDGE_TOP = 1 shl 2 /** * Edge flag indicating that the bottom edge should be affected. */ const val EDGE_BOTTOM = 1 shl 3 /** * Edge flag set indicating all edges should be affected. */ const val EDGE_ALL = EDGE_LEFT or EDGE_TOP or EDGE_RIGHT or EDGE_BOTTOM /** * Indicates that a check should occur along the horizontal axis */ const val DIRECTION_HORIZONTAL = 1 shl 0 /** * Indicates that a check should occur along the vertical axis */ const val DIRECTION_VERTICAL = 1 shl 1 /** * Indicates that a check should occur along all axes */ const val DIRECTION_ALL = DIRECTION_HORIZONTAL or DIRECTION_VERTICAL private const val EDGE_SIZE = 20 // dp private const val BASE_SETTLE_DURATION = 256 // ms private const val MAX_SETTLE_DURATION = 600 // ms /** * Interpolator defining the animation curve for mScroller */ private val sInterpolator = Interpolator { input -> var t = input t -= 1.0f t * t * t * t * t + 1.0f } /** * Factory method to create a new ViewDragHelper. * * @param forParent Parent view to monitor * @param cb Callback to provide information and receive events * @return a new ViewDragHelper instance */ fun create(forParent: ViewGroup, cb: Callback): ViewDragHelper { return ViewDragHelper(forParent.context, forParent, null, cb) } /** * Factory method to create a new ViewDragHelper with the specified interpolator. * * @param forParent Parent view to monitor * @param interpolator interpolator for scroller * @param cb Callback to provide information and receive events * @return a new ViewDragHelper instance */ fun create(forParent: ViewGroup, interpolator: Interpolator?, cb: Callback): ViewDragHelper { return ViewDragHelper(forParent.context, forParent, interpolator, cb) } /** * Factory method to create a new ViewDragHelper. * * @param forParent Parent view to monitor * @param sensitivity Multiplier for how sensitive the helper should be about detecting * the start of a drag. Larger values are more sensitive. 1.0f is normal. * @param cb Callback to provide information and receive events * @return a new ViewDragHelper instance */ fun create(forParent: ViewGroup, sensitivity: Float, cb: Callback): ViewDragHelper { val helper = create(forParent, cb) helper.touchSlop = (helper.touchSlop * (1 / sensitivity)).toInt() return helper } /** * Factory method to create a new ViewDragHelper with the specified interpolator. * * @param forParent Parent view to monitor * @param sensitivity Multiplier for how sensitive the helper should be about detecting * the start of a drag. Larger values are more sensitive. 1.0f is normal. * @param interpolator interpolator for scroller * @param cb Callback to provide information and receive events * @return a new ViewDragHelper instance */ @JvmStatic fun create(forParent: ViewGroup, sensitivity: Float, interpolator: Interpolator?, cb: Callback): ViewDragHelper { val helper = create(forParent, interpolator, cb) helper.touchSlop = (helper.touchSlop * (1 / sensitivity)).toInt() return helper } } }
apache-2.0
1ec9822ea2c5153c100b52329e0fe443
40.513533
191
0.593755
4.777851
false
false
false
false
StephenVinouze/SpotifyReceiver
app/src/main/java/com/wopata/spotifyreceiver/receivers/SpotifyBroadcastReceiver.kt
1
2073
package com.wopata.spotifyreceiver.receivers import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import com.wopata.spotifyreceiver.models.Track /** * Created by stephenvinouze on 22/02/2017. */ class SpotifyBroadcastReceiver: BroadcastReceiver() { companion object { private val SPOTIFY_PACKAGE = "com.spotify.music" private val METADATA_CHANGED = SPOTIFY_PACKAGE + ".metadatachanged" private val PLAYBACK_STATE_CHANGED = SPOTIFY_PACKAGE + ".playbackstatechanged" private val QUEUE_CHANGED = SPOTIFY_PACKAGE + ".queuechanged" fun intentFilter(): IntentFilter { val intentFilter = IntentFilter() intentFilter.addAction(METADATA_CHANGED) intentFilter.addAction(PLAYBACK_STATE_CHANGED) intentFilter.addAction(QUEUE_CHANGED) return intentFilter } } interface OnSpotifyEventListener { fun onMetadataChanged(track: Track) fun onPlaybackChanged(track: Track) fun onQueueChanged() } private val track = Track() var eventCallback: OnSpotifyEventListener? = null override fun onReceive(context: Context, intent: Intent) { when (intent.action) { METADATA_CHANGED -> { track.trackId = intent.getStringExtra("id") track.artistName = intent.getStringExtra("artist") track.albumName = intent.getStringExtra("album") track.trackName = intent.getStringExtra("track") track.trackLength = intent.getIntExtra("length", 0) eventCallback?.onMetadataChanged(track) } PLAYBACK_STATE_CHANGED -> { track.playing = intent.getBooleanExtra("playing", false) track.playbackPosition = intent.getIntExtra("playbackPosition", 0) eventCallback?.onPlaybackChanged(track) } QUEUE_CHANGED -> eventCallback?.onQueueChanged() } } }
apache-2.0
2115e22ea0f682bace6a2adcfe1b6652
34.758621
86
0.652677
4.983173
false
false
false
false
Nunnery/MythicDrops
src/test/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/utils/TierUtilTest.kt
1
3915
/* * This file is part of MythicDrops, licensed under the MIT License. * * Copyright (C) 2020 Richard Harrah * * 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.tealcube.minecraft.bukkit.mythicdrops.utils import com.tealcube.minecraft.bukkit.mythicdrops.api.settings.SettingsManager import com.tealcube.minecraft.bukkit.mythicdrops.api.tiers.TierManager import com.tealcube.minecraft.bukkit.mythicdrops.settings.MythicSettingsManager import com.tealcube.minecraft.bukkit.mythicdrops.tiers.MythicTier import com.tealcube.minecraft.bukkit.mythicdrops.tiers.MythicTierManager import io.mockk.every import io.mockk.junit5.MockKExtension import io.mockk.mockk import org.assertj.core.api.Assertions.assertThat import org.bukkit.Location import org.bukkit.World import org.bukkit.configuration.file.YamlConfiguration import org.bukkit.entity.EntityType import org.bukkit.entity.LivingEntity import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(MockKExtension::class) internal class TierUtilTest { companion object { val creatureSpawningYaml5_0_0 = YamlConfiguration() } lateinit var settingsManager: SettingsManager lateinit var tierManager: TierManager @BeforeEach fun setup() { val creatureSpawningYaml5_0_0Text = this.javaClass.classLoader.getResource("creatureSpawning_5_0_0.yml")?.readText() ?: "" creatureSpawningYaml5_0_0.loadFromString(creatureSpawningYaml5_0_0Text) val exoticTier = MythicTier(name = "exotic", weight = 0.9) val legendaryTier = MythicTier(name = "legendary", weight = 0.1) settingsManager = MythicSettingsManager().apply { loadCreatureSpawningSettingsFromConfiguration(creatureSpawningYaml5_0_0) } tierManager = MythicTierManager().apply { add(exoticTier) add(legendaryTier) } } @Test fun `does getTierForEntity pick heavier tier 800 times out of 1000`() { val wither = mockk<LivingEntity>() val world = mockk<World>() every { world.spawnLocation } returns Location(world, 0.0, 0.0, 0.0) every { wither.type } returns EntityType.WITHER every { wither.location } returns Location(world, 0.0, 0.0, 0.0) every { wither.world } returns world val selectedTiers = mutableMapOf<String, Int>() repeat(1000) { val selectedTier = TierUtil.getTierForLivingEntity(wither, settingsManager.creatureSpawningSettings, tierManager) selectedTier?.let { tier -> selectedTiers[tier.name] = selectedTiers.getOrDefault(tier.name, 0) + 1 } } assertThat(selectedTiers["exotic"]).isGreaterThanOrEqualTo(800) assertThat(selectedTiers["legendary"]).isLessThanOrEqualTo(200) } }
mit
910984c2f918c4ccaf6c01ad85676771
42.5
110
0.733078
4.292763
false
false
false
false
google/intellij-community
python/testSrc/com/jetbrains/python/sdk/PySdkPathsTest.kt
5
14118
// 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.jetbrains.python.sdk import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.runWriteActionAndWait import com.intellij.openapi.module.Module import com.intellij.openapi.projectRoots.ProjectJdkTable import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.impl.ProjectJdkImpl import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.ApplicationRule import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.VfsTestUtil import com.intellij.testFramework.assertions.Assertions.assertThat import com.intellij.testFramework.replaceService import com.intellij.testFramework.rules.ProjectModelRule import com.jetbrains.python.PyNames import com.jetbrains.python.PythonMockSdk import com.jetbrains.python.PythonPluginDisposable import com.jetbrains.python.configuration.PyConfigurableInterpreterList import com.jetbrains.python.psi.LanguageLevel import com.jetbrains.python.psi.PyUtil import org.jetbrains.annotations.NotNull import org.junit.ClassRule import org.junit.Rule import org.junit.Test class PySdkPathsTest { companion object { @JvmField @ClassRule val appRule = ApplicationRule() } @Rule @JvmField val projectModel = ProjectModelRule() @Test fun sysPathEntryIsExcludedPath() { val sdk = PythonMockSdk.create() val excluded = createInSdkRoot(sdk, "my_excluded") val included = createInSdkRoot(sdk, "my_included") sdk.putUserData(PythonSdkType.MOCK_SYS_PATH_KEY, listOf(sdk.homePath, excluded.path, included.path)) mockPythonPluginDisposable() runWriteActionAndWait { sdk.getOrCreateAdditionalData() }.apply { setExcludedPathsFromVirtualFiles(setOf(excluded)) } updateSdkPaths(sdk) val rootProvider = sdk.rootProvider val sdkRoots = rootProvider.getFiles(OrderRootType.CLASSES) assertThat(sdkRoots).contains(included) assertThat(sdkRoots).doesNotContain(excluded) assertThat(rootProvider.getFiles(OrderRootType.SOURCES)).isEmpty() } @Test fun userAddedIsModuleRoot() { val (module, moduleRoot) = createModule() val sdk = PythonMockSdk.create().also { module.pythonSdk = it } mockPythonPluginDisposable() runWriteActionAndWait { sdk.getOrCreateAdditionalData() }.apply { setAddedPathsFromVirtualFiles(setOf(moduleRoot)) } updateSdkPaths(sdk) checkRoots(sdk, module, listOf(moduleRoot), emptyList()) assertThat(getPathsToTransfer(sdk)).doesNotContain(moduleRoot) } @Test fun sysPathEntryIsModuleRoot() { val (module, moduleRoot) = createModule() val sdk = PythonMockSdk.create().also { module.pythonSdk = it } sdk.putUserData(PythonSdkType.MOCK_SYS_PATH_KEY, listOf(sdk.homePath, moduleRoot.path)) mockPythonPluginDisposable() updateSdkPaths(sdk) checkRoots(sdk, module, listOf(moduleRoot), emptyList()) assertThat(getPathsToTransfer(sdk)).doesNotContain(moduleRoot) } @Test fun userAddedInModuleAndSdkInModuleButUserAddedNotInSdk() { val (module, moduleRoot) = createModule() val sdkPath = createVenvStructureInModule(moduleRoot).path val userAddedPath = createSubdir(moduleRoot) val sdk = PythonMockSdk.create(sdkPath).also { module.pythonSdk = it } mockPythonPluginDisposable() runWriteActionAndWait { sdk.getOrCreateAdditionalData() }.apply { setAddedPathsFromVirtualFiles(setOf(userAddedPath)) } updateSdkPaths(sdk) checkRoots(sdk, module, listOf(moduleRoot, userAddedPath), emptyList()) val simpleSdk = PythonMockSdk.create().also { removeTransferredRoots(module, sdk) module.pythonSdk = it } updateSdkPaths(simpleSdk) checkRoots(simpleSdk, module, listOf(moduleRoot), emptyList()) } @Test fun userAddedViaEditableSdkWithSharedData() { // emulates com.jetbrains.python.configuration.PythonSdkDetailsDialog.ShowPathButton.actionPerformed val (module, moduleRoot) = createModule() val sdkPath = createVenvStructureInModule(moduleRoot).path val userAddedPath = createSubdir(moduleRoot) val pythonVersion = LanguageLevel.getDefault().toPythonVersion() val sdk = ProjectJdkImpl( "Mock ${PyNames.PYTHON_SDK_ID_NAME} $pythonVersion", PythonSdkType.getInstance(), "$sdkPath/bin/python", pythonVersion ) .also { module.pythonSdk = it } sdk.putUserData(PythonSdkType.MOCK_PY_VERSION_KEY, pythonVersion) mockPythonPluginDisposable() runWriteActionAndWait { sdk.getOrCreateAdditionalData() } runWriteActionAndWait { ProjectJdkTable.getInstance().addJdk(sdk) } val editableSdk = PyConfigurableInterpreterList.getInstance(projectModel.project).model.findSdk(sdk.name) editableSdk!!.putUserData(PythonSdkType.MOCK_PY_VERSION_KEY, pythonVersion) Disposer.register(projectModel.project, editableSdk as Disposable) // --- ADD path --- val sdkModificator = editableSdk.sdkModificator (sdkModificator.sdkAdditionalData as PythonSdkAdditionalData).setAddedPathsFromVirtualFiles(setOf(userAddedPath)) runWriteActionAndWait { sdkModificator.commitChanges() } updateSdkPaths(editableSdk) updateSdkPaths(sdk) // since editableSdk was created after additional data had been created for sdk, they share the same data checkRoots(sdk, module, listOf(moduleRoot, userAddedPath), emptyList()) // --- REMOVE path --- val sdkModificator2 = editableSdk.sdkModificator (sdkModificator2.sdkAdditionalData as PythonSdkAdditionalData).setAddedPathsFromVirtualFiles(emptySet()) runWriteActionAndWait { sdkModificator2.commitChanges() } updateSdkPaths(editableSdk) updateSdkPaths(sdk) // since editableSdk was created after additional data had been created for sdk, they share the same data checkRoots(sdk, module, listOf(moduleRoot), emptyList()) runWriteActionAndWait { ProjectJdkTable.getInstance().removeJdk(sdk) } } @Test fun userAddedViaEditableSdkWithoutSharedData() { // emulates com.jetbrains.python.configuration.PythonSdkDetailsDialog.ShowPathButton.actionPerformed val (module, moduleRoot) = createModule() val sdkPath = createVenvStructureInModule(moduleRoot).path val userAddedPath = createSubdir(moduleRoot) val pythonVersion = LanguageLevel.getDefault().toPythonVersion() val sdk = ProjectJdkImpl( "Mock ${PyNames.PYTHON_SDK_ID_NAME} $pythonVersion", PythonSdkType.getInstance(), "$sdkPath/bin/python", pythonVersion ) .also { module.pythonSdk = it } sdk.putUserData(PythonSdkType.MOCK_PY_VERSION_KEY, pythonVersion) runWriteActionAndWait { ProjectJdkTable.getInstance().addJdk(sdk) } val editableSdk = PyConfigurableInterpreterList.getInstance(projectModel.project).model.findSdk(sdk.name) editableSdk!!.putUserData(PythonSdkType.MOCK_PY_VERSION_KEY, pythonVersion) Disposer.register(projectModel.project, editableSdk as Disposable) // --- ADD path --- val sdkModificator = editableSdk.sdkModificator assertThat(sdkModificator.sdkAdditionalData).isNull() mockPythonPluginDisposable() sdkModificator.sdkAdditionalData = PythonSdkAdditionalData(null).apply { setAddedPathsFromVirtualFiles(setOf(userAddedPath)) } runWriteActionAndWait { sdkModificator.commitChanges() } updateSdkPaths(editableSdk) runWriteActionAndWait { ProjectJdkTable.getInstance().updateJdk(sdk, editableSdk) } updateSdkPaths(sdk) checkRoots(sdk, module, listOf(moduleRoot, userAddedPath), emptyList()) // --- REMOVE path --- val sdkModificator2 = editableSdk.sdkModificator (sdkModificator2.sdkAdditionalData as PythonSdkAdditionalData).setAddedPathsFromVirtualFiles(emptySet()) runWriteActionAndWait { sdkModificator2.commitChanges() } updateSdkPaths(editableSdk) updateSdkPaths(sdk) // after updateJdk call editableSdk and sdk share the same data checkRoots(sdk, module, listOf(moduleRoot), emptyList()) runWriteActionAndWait { ProjectJdkTable.getInstance().removeJdk(sdk) } } @Test fun sysPathEntryInModuleAndSdkInModuleButEntryNotInSdk() { val (module, moduleRoot) = createModule() val sdkPath = createVenvStructureInModule(moduleRoot).path val entryPath = createSubdir(moduleRoot) val sdk = PythonMockSdk.create(sdkPath).also { module.pythonSdk = it } sdk.putUserData(PythonSdkType.MOCK_SYS_PATH_KEY, listOf(sdk.homePath, entryPath.path)) mockPythonPluginDisposable() updateSdkPaths(sdk) checkRoots(sdk, module, listOf(moduleRoot, entryPath), emptyList()) // Subsequent updates should keep already set up source roots updateSdkPaths(sdk) checkRoots(sdk, module, listOf(moduleRoot, entryPath), emptyList()) val simpleSdk = PythonMockSdk.create().also { removeTransferredRoots(module, sdk) module.pythonSdk = it } updateSdkPaths(simpleSdk) checkRoots(simpleSdk, module, listOf(moduleRoot), emptyList()) } @Test fun userAddedInSdkAndSdkInModule() { val (module, moduleRoot) = createModule() val sdkDir = createVenvStructureInModule(moduleRoot) val userAddedPath = createSubdir(sdkDir) val sdk = PythonMockSdk.create(sdkDir.path).also { module.pythonSdk = it } mockPythonPluginDisposable() runWriteActionAndWait { sdk.getOrCreateAdditionalData() }.apply { setAddedPathsFromVirtualFiles(setOf(userAddedPath)) } updateSdkPaths(sdk) checkRoots(sdk, module, listOf(moduleRoot), listOf(userAddedPath)) } @Test fun sysPathEntryInSdkAndSdkInModule() { val (module, moduleRoot) = createModule() val sdkDir = createVenvStructureInModule(moduleRoot) val entryPath = createSubdir(sdkDir) val sdk = PythonMockSdk.create(sdkDir.path).also { module.pythonSdk = it } sdk.putUserData(PythonSdkType.MOCK_SYS_PATH_KEY, listOf(sdk.homePath, entryPath.path)) updateSdkPaths(sdk) checkRoots(sdk, module, listOf(moduleRoot), listOf(entryPath)) } @Test fun sysPathEntryOutsideSdkAndModule1ButInsideModule2() { val (module1, moduleRoot1) = createModule("m1") val (module2, moduleRoot2) = createModule("m2") val sdkDir = createVenvStructureInModule(moduleRoot1) val entryPath1 = createSubdir(moduleRoot1) val entryPath2 = createSubdir(moduleRoot2) val sdk = PythonMockSdk.create(sdkDir.path).also { module1.pythonSdk = it module2.pythonSdk = it } sdk.putUserData(PythonSdkType.MOCK_SYS_PATH_KEY, listOf(sdk.homePath, entryPath1.path, entryPath2.path)) mockPythonPluginDisposable() updateSdkPaths(sdk) checkRoots(sdk, module1, listOf(moduleRoot1, entryPath1, entryPath2), emptyList()) checkRoots(sdk, module2, listOf(moduleRoot2, entryPath1, entryPath2), emptyList()) val simpleSdk = PythonMockSdk.create().also { removeTransferredRoots(module1, sdk) module1.pythonSdk = it removeTransferredRoots(module2, sdk) module2.pythonSdk = it } updateSdkPaths(simpleSdk) checkRoots(simpleSdk, module1, listOf(moduleRoot1), emptyList()) checkRoots(simpleSdk, module2, listOf(moduleRoot2), emptyList()) } private fun createModule(name: String = "module"): Pair<Module, VirtualFile> { val moduleRoot = LocalFileSystem.getInstance().refreshAndFindFileByIoFile( FileUtil.createTempDirectory("my", "project", false) )!!.also { deleteOnTearDown(it) } val module = projectModel.createModule(name) assertThat(PyUtil.getSourceRoots(module)).isEmpty() module.rootManager.modifiableModel.apply { addContentEntry(moduleRoot) runWriteActionAndWait { commit() } } assertThat(PyUtil.getSourceRoots(module)).containsOnly(moduleRoot) return module to moduleRoot } private fun createVenvStructureInModule(moduleRoot: VirtualFile): VirtualFile { return runWriteActionAndWait { val venv = moduleRoot.createChildDirectory(this, "venv") venv.createChildData(this, "pyvenv.cfg") // see PythonSdkUtil.getVirtualEnvRoot val bin = venv.createChildDirectory(this, "bin") bin.createChildData(this, "python") venv } } private fun createSubdir(dir: VirtualFile): VirtualFile { return runWriteActionAndWait { dir.createChildDirectory(this, "mylib") } } private fun mockPythonPluginDisposable() { ApplicationManager.getApplication().replaceService(PythonPluginDisposable::class.java, PythonPluginDisposable(), projectModel.project) Disposer.register(projectModel.project, PythonPluginDisposable.getInstance()) } private fun updateSdkPaths(sdk: @NotNull Sdk) { PythonSdkUpdater.updateVersionAndPathsSynchronouslyAndScheduleRemaining(sdk, projectModel.project) ApplicationManager.getApplication().invokeAndWait { PlatformTestUtil.dispatchAllInvocationEventsInIdeEventQueue() } } private fun checkRoots(sdk: Sdk, module: Module, moduleRoots: List<VirtualFile>, sdkRoots: List<VirtualFile>) { assertThat(PyUtil.getSourceRoots(module)).containsExactlyInAnyOrder(*moduleRoots.toTypedArray()) val rootProvider = sdk.rootProvider val classes = rootProvider.getFiles(OrderRootType.CLASSES) assertThat(classes).containsAll(sdkRoots) assertThat(classes).doesNotContain(*moduleRoots.toTypedArray()) assertThat(rootProvider.getFiles(OrderRootType.SOURCES)).isEmpty() } private fun createInSdkRoot(sdk: Sdk, relativePath: String): VirtualFile { return runWriteActionAndWait { VfsUtil.createDirectoryIfMissing(sdk.homeDirectory!!.parent.parent, relativePath) }.also { deleteOnTearDown(it) } } private fun deleteOnTearDown(file: VirtualFile) { Disposer.register(projectModel.project) { VfsTestUtil.deleteFile(file) } } }
apache-2.0
e9c01cbd9014d9b257be78bec19a2b42
35.202564
158
0.761439
4.551257
false
true
false
false
Flank/flank
test_runner/src/test/kotlin/ftl/run/status/PrinterTestUtil.kt
1
856
package ftl.run.status object PrinterTestUtil { const val time = "time" val changes1 = listOf( ExecutionStatus.Change( name = "name1", previous = ExecutionStatus(), current = ExecutionStatus(state = "state0"), time = time ), ExecutionStatus.Change( name = "name2", previous = ExecutionStatus(), current = ExecutionStatus(state = "state0"), time = time ) ) val changes2 = changes1.mapIndexed { index, it -> it.copy( previous = it.current, current = it.current.copy(state = "state${index % 2}") ) } } fun String.filterMockk() = filterLines { !contains("io.mockk") } private fun String.filterLines(f: String.() -> Boolean) = lineSequence().filter(f).joinToString("\n")
apache-2.0
034237ff20deb4904eae0a754ed6343b
29.571429
101
0.554907
4.389744
false
false
false
false
siosio/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/findUsages/KotlinElementDescriptionProvider.kt
1
10073
// 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.findUsages import com.intellij.codeInsight.highlighting.HighlightUsagesDescriptionLocation import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.ElementDescriptionLocation import com.intellij.psi.ElementDescriptionProvider import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import com.intellij.refactoring.util.CommonRefactoringUtil import com.intellij.refactoring.util.RefactoringDescriptionLocation import com.intellij.usageView.UsageViewLongNameLocation import com.intellij.usageView.UsageViewShortNameLocation import com.intellij.usageView.UsageViewTypeLocation import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.idea.KotlinIndependentBundle import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.util.string.collapseSpaces import org.jetbrains.kotlin.name.FqNameUnsafe import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType open class KotlinElementDescriptionProviderBase : ElementDescriptionProvider { private tailrec fun KtNamedDeclaration.parentForFqName(): KtNamedDeclaration? { val parent = getStrictParentOfType<KtNamedDeclaration>() ?: return null if (parent is KtProperty && parent.isLocal) return parent.parentForFqName() return parent } private fun KtNamedDeclaration.name() = nameAsName ?: Name.special("<no name provided>") private fun KtNamedDeclaration.fqName(): FqNameUnsafe { containingClassOrObject?.let { if (it is KtObjectDeclaration && it.isCompanion()) { return it.fqName().child(name()) } return FqNameUnsafe("${it.name()}.${name()}") } val internalSegments = generateSequence(this) { it.parentForFqName() } .filterIsInstance<KtNamedDeclaration>() .map { it.name ?: "<no name provided>" } .toList() .asReversed() val packageSegments = containingKtFile.packageFqName.pathSegments() return FqNameUnsafe((packageSegments + internalSegments).joinToString(".")) } private fun KtTypeReference.renderShort(): String { return accept( object : KtVisitor<String, Unit>() { private val visitor get() = this override fun visitTypeReference(typeReference: KtTypeReference, data: Unit): String { val typeText = typeReference.typeElement?.accept(this, data) ?: "???" return if (typeReference.hasParentheses()) "($typeText)" else typeText } override fun visitDynamicType(type: KtDynamicType, data: Unit) = type.text override fun visitFunctionType(type: KtFunctionType, data: Unit): String { return buildString { type.receiverTypeReference?.let { append(it.accept(visitor, data)).append('.') } type.parameters.joinTo(this, prefix = "(", postfix = ")") { it.accept(visitor, data) } append(" -> ") append(type.returnTypeReference?.accept(visitor, data) ?: "???") } } override fun visitNullableType(nullableType: KtNullableType, data: Unit): String { val innerTypeText = nullableType.innerType?.accept(this, data) ?: return "???" return "$innerTypeText?" } override fun visitSelfType(type: KtSelfType, data: Unit) = type.text override fun visitUserType(type: KtUserType, data: Unit): String { return buildString { append(type.referencedName ?: "???") val arguments = type.typeArguments if (arguments.isNotEmpty()) { arguments.joinTo(this, prefix = "<", postfix = ">") { it.typeReference?.accept(visitor, data) ?: it.text } } } } override fun visitParameter(parameter: KtParameter, data: Unit) = parameter.typeReference?.accept(this, data) ?: "???" }, Unit ) } //TODO: Implement in FIR protected open val PsiElement.isRenameJavaSyntheticPropertyHandler get() = false protected open val PsiElement.isRenameKotlinPropertyProcessor get() = false override fun getElementDescription(element: PsiElement, location: ElementDescriptionLocation): String? { val shouldUnwrap = location !is UsageViewShortNameLocation && location !is UsageViewLongNameLocation val targetElement = if (shouldUnwrap) element.unwrapped ?: element else element fun elementKind() = when (targetElement) { is KtClass -> if (targetElement.isInterface()) KotlinIndependentBundle.message("find.usages.interface") else KotlinIndependentBundle.message("find.usages.class") is KtObjectDeclaration -> if (targetElement.isCompanion()) KotlinIndependentBundle.message("find.usages.companion.object") else KotlinIndependentBundle.message("find.usages.object") is KtNamedFunction -> KotlinIndependentBundle.message("find.usages.function") is KtPropertyAccessor -> KotlinIndependentBundle.message( "find.usages.for.property", (if (targetElement.isGetter) KotlinIndependentBundle.message("find.usages.getter") else KotlinIndependentBundle.message("find.usages.setter")) ) + " " is KtFunctionLiteral -> KotlinIndependentBundle.message("find.usages.lambda") is KtPrimaryConstructor, is KtSecondaryConstructor -> KotlinIndependentBundle.message("find.usages.constructor") is KtProperty -> if (targetElement.isLocal) KotlinIndependentBundle.message("find.usages.variable") else KotlinIndependentBundle.message("find.usages.property") is KtTypeParameter -> KotlinIndependentBundle.message("find.usages.type.parameter") is KtParameter -> KotlinIndependentBundle.message("find.usages.parameter") is KtDestructuringDeclarationEntry -> KotlinIndependentBundle.message("find.usages.variable") is KtTypeAlias -> KotlinIndependentBundle.message("find.usages.type.alias") is KtLabeledExpression -> KotlinIndependentBundle.message("find.usages.label") is KtImportAlias -> KotlinIndependentBundle.message("find.usages.import.alias") is KtLightClassForFacade -> KotlinIndependentBundle.message("find.usages.facade.class") else -> { //TODO Implement in FIR when { targetElement.isRenameJavaSyntheticPropertyHandler -> KotlinIndependentBundle.message("find.usages.property") targetElement.isRenameKotlinPropertyProcessor -> KotlinIndependentBundle.message("find.usages.property.accessor") else -> null } } } val namedElement = if (targetElement is KtPropertyAccessor) { targetElement.parent as? KtProperty } else targetElement as? PsiNamedElement @Suppress("FoldInitializerAndIfToElvis") if (namedElement == null) { return if (targetElement is KtElement) "'" + StringUtil.shortenTextWithEllipsis( targetElement.text.collapseSpaces(), 53, 0 ) + "'" else null } if (namedElement.language != KotlinLanguage.INSTANCE) return null return when (location) { is UsageViewTypeLocation -> elementKind() is UsageViewShortNameLocation, is UsageViewLongNameLocation -> namedElement.name is RefactoringDescriptionLocation -> { val kind = elementKind() ?: return null if (namedElement !is KtNamedDeclaration) return null val renderFqName = location.includeParent() && namedElement !is KtTypeParameter && namedElement !is KtParameter && namedElement !is KtConstructor<*> val desc = when (namedElement) { is KtFunction -> { val baseText = buildString { append(namedElement.name ?: "") namedElement.valueParameters.joinTo(this, prefix = "(", postfix = ")") { (if (it.isVarArg) "vararg " else "") + (it.typeReference?.renderShort() ?: "") } namedElement.receiverTypeReference?.let { append(" on ").append(it.renderShort()) } } val parentFqName = if (renderFqName) namedElement.fqName().parent() else null if (parentFqName?.isRoot != false) baseText else "${parentFqName.asString()}.$baseText" } else -> (if (renderFqName) namedElement.fqName().asString() else namedElement.name) ?: "" } "$kind ${CommonRefactoringUtil.htmlEmphasize(desc)}" } is HighlightUsagesDescriptionLocation -> { val kind = elementKind() ?: return null if (namedElement !is KtNamedDeclaration) return null "$kind ${namedElement.name}" } else -> null } } }
apache-2.0
81869bcf5f7feda49142b510ca0eb3d7
49.873737
158
0.61918
5.825911
false
false
false
false