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
WilliamHester/Breadit-2
app/app/src/main/java/me/williamhester/reddit/ui/adapters/ContentAdapter.kt
1
3615
package me.williamhester.reddit.ui.adapters import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import java.lang.ref.WeakReference import me.williamhester.reddit.R import me.williamhester.reddit.html.HtmlParser import me.williamhester.reddit.models.Submission import me.williamhester.reddit.models.TextComment import me.williamhester.reddit.ui.ContentClickCallbacks import me.williamhester.reddit.ui.VotableCallbacks import me.williamhester.reddit.ui.viewholders.ContentViewHolder import me.williamhester.reddit.ui.viewholders.SubmissionImageViewHolder import me.williamhester.reddit.ui.viewholders.SubmissionLinkViewHolder import me.williamhester.reddit.ui.viewholders.SubmissionViewHolder import me.williamhester.reddit.ui.viewholders.TextCommentViewHolder /** A dynamic adapter that displays the appropriate Reddit content. */ abstract class ContentAdapter internal constructor( internal var layoutInflater: LayoutInflater, val htmlParser: HtmlParser, contentClickCallbacks: ContentClickCallbacks, clickListener: VotableCallbacks ) : RecyclerView.Adapter<ContentViewHolder<*>>() { protected val contentCallbacks: WeakReference<ContentClickCallbacks> = WeakReference(contentClickCallbacks) protected val clickListener: WeakReference<VotableCallbacks> = WeakReference(clickListener) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ContentViewHolder<*> { val v: View when (viewType) { SUBMISSION_LINK -> { v = layoutInflater.inflate(R.layout.row_submission_link, parent, false) return SubmissionLinkViewHolder(v, clickListener.get()!!) } SUBMISSION_IMAGE -> { v = layoutInflater.inflate(R.layout.row_submission_image, parent, false) return SubmissionImageViewHolder(v, contentCallbacks.get()!!, clickListener.get()!!) } SUBMISSION -> { v = layoutInflater.inflate(R.layout.row_submission, parent, false) return SubmissionViewHolder(v, clickListener.get()!!) } TEXT_COMMENT -> { v = layoutInflater.inflate(R.layout.row_comment, parent, false) return TextCommentViewHolder(v, htmlParser, clickListener.get()!!) } else -> throw UnsupportedViewTypeException() } } override fun onBindViewHolder(holder: ContentViewHolder<*>, position: Int) { when (getItemViewType(position)) { SUBMISSION_IMAGE, SUBMISSION_LINK, SUBMISSION -> { val subViewHolder = holder as SubmissionViewHolder subViewHolder.itemView.tag = position subViewHolder.setContent(getItemForPosition(position) as Submission) } TEXT_COMMENT -> { val textCommentViewHolder = holder as TextCommentViewHolder textCommentViewHolder.itemView.tag = position textCommentViewHolder.setContent(getItemForPosition(position) as TextComment) } } } override fun getItemViewType(position: Int): Int { val o = getItemForPosition(position) if (o is Submission) { val sub = o if (sub.previewUrl != null) { return SUBMISSION_IMAGE } if (!sub.isSelf) { return SUBMISSION_LINK } return SUBMISSION } if (o is TextComment) { return TEXT_COMMENT } return -1 } abstract fun getItemForPosition(position: Int): Any class UnsupportedViewTypeException : Exception() companion object { private val SUBMISSION = 1 private val SUBMISSION_IMAGE = 2 private val SUBMISSION_LINK = 3 private val TEXT_COMMENT = 10 } }
apache-2.0
36acd30ba538dcbf64189c39e3dcfca3
34.792079
92
0.733887
4.670543
false
false
false
false
saffih/ElmDroid
app/src/main/java/saffih/elmdroid/sms/child/SmsChild.kt
1
2627
/* * By Saffi Hartal, 2017. * 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 saffih.elmdroid.sms.child import android.content.Context import android.os.Handler import android.os.Looper import android.telephony.SmsManager import android.telephony.SmsMessage import android.widget.Toast import saffih.elmdroid.StateChild //import saffih.elmdroid.sms.toast sealed class Msg { companion object { fun received(received: List<SmsMessage>) = Msg.Received(received) } class Init : Msg() data class Received(val received: List<SmsMessage>) : Msg() } class Model data class MSms(val address: String, val text: String) abstract class SmsChild(val me: Context) : StateChild<Model, Msg>() { abstract fun onSmsArrived(sms: List<SmsMessage>) val smsReceiver = SMSReceiverAdapter( hook = { arr: Array<out SmsMessage?> -> dispatch(Msg.received(arr.filterNotNull())) }) // for services override fun onCreate() { smsReceiver.meRegister(me) } override fun onDestroy() { smsReceiver.meUnregister(me) } override fun init(): Model { dispatch(Msg.Init()) return Model() } override fun update(msg: Msg, model: Model): Model { return when (msg) { is Msg.Init -> { model } is Msg.Received -> { onSmsArrived(msg.received) model } } } val smsManager = SmsManager.getDefault() fun sendSms(data: MSms) { smsManager.sendTextMessage( data.address, null, data.text, null, null) } } fun SmsChild.toast(txt: String, duration: Int = Toast.LENGTH_SHORT) { val handler = Handler(Looper.getMainLooper()) handler.post({ Toast.makeText(me, txt, duration).show() }) }
apache-2.0
4c6d0313217476c5888c90168c7fa21c
26.652632
98
0.657785
4.079193
false
false
false
false
McMoonLakeDev/MoonLake
API/src/main/kotlin/com/mcmoonlake/api/packet/PacketOutExplosion.kt
1
2810
/* * Copyright (C) 2016-Present The MoonLake ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mcmoonlake.api.packet import com.mcmoonlake.api.block.BlockPosition import com.mcmoonlake.api.orFalse data class PacketOutExplosion( var x: Double, var y: Double, var z: Double, var radius: Float, var affectedPositions: MutableList<BlockPosition>?, var velocityX: Float, var velocityY: Float, var velocityZ: Float ) : PacketOutBukkitAbstract("PacketPlayOutExplosion") { @Deprecated("") constructor() : this(.0, .0, .0, 0f, null, 0f, 0f, 0f) override fun read(data: PacketBuffer) { x = data.readFloat().toDouble() y = data.readFloat().toDouble() z = data.readFloat().toDouble() radius = data.readFloat() val size = data.readInt() if(size > 0) { affectedPositions = ArrayList(size) val offsetX = x.toInt() val offsetY = y.toInt() val offsetZ = z.toInt() (0 until size).forEach { val blockX = data.readByte() + offsetX val blockY = data.readByte() + offsetY val blockZ = data.readByte() + offsetZ affectedPositions?.add(BlockPosition(blockX, blockY, blockZ)) } } velocityX = data.readFloat() velocityY = data.readFloat() velocityZ = data.readFloat() } override fun write(data: PacketBuffer) { data.writeFloat(x.toFloat()) data.writeFloat(y.toFloat()) data.writeFloat(z.toFloat()) data.writeFloat(radius) data.writeInt(affectedPositions?.size ?: 0) if(affectedPositions?.isNotEmpty().orFalse()) { val offsetX = x.toInt() val offsetY = y.toInt() val offsetZ = z.toInt() affectedPositions?.forEach { data.writeByte(it.x - offsetX) data.writeByte(it.y - offsetY) data.writeByte(it.z - offsetZ) } } data.writeFloat(velocityX) data.writeFloat(velocityY) data.writeFloat(velocityZ) } }
gpl-3.0
1dea5560799247177475f54f00f8ee14
34.125
77
0.612811
4.343122
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/hierarchy/calls/callees/kotlinLocalClass/main0.kt
13
574
class KA { val name = "A" fun foo(s: String): String = "A: $s" } fun packageFun(s: String): String = s val packageVal = "" fun client() { class <caret>T { val bar = run { val localVal = packageFun("") KA().foo(KA().name) JA().foo(JA().name) packageFun(localVal) } fun bar() { KA().foo(KA().name) JA().foo(JA().name) } } fun localFun(s: String): String = packageFun(s) KA().foo(KA().name) JA().foo(JA().name) localFun(packageVal) }
apache-2.0
62682baff4bc6284b0eaa8ce57b13ff9
16.96875
51
0.468641
3.242938
false
false
false
false
fwcd/kotlin-language-server
shared/src/main/kotlin/org/javacs/kt/util/StringUtils.kt
1
3509
package org.javacs.kt.util /** * Computes a string distance using a slightly modified * variant of the SIFT4 algorithm in linear time. * Note that the function is asymmetric with respect to * its two input strings and thus is not a metric in the * mathematical sense. * * Based on the JavaScript implementation from * https://siderite.dev/blog/super-fast-and-accurate-string-distance.html/ * * @param candidate The first string * @param pattern The second string * @param maxOffset The number of characters to search for matching letters */ fun stringDistance(candidate: CharSequence, pattern: CharSequence, maxOffset: Int = 4): Int = when { candidate.length == 0 -> pattern.length pattern.length == 0 -> candidate.length else -> { val candidateLength = candidate.length val patternLength = pattern.length var iCandidate = 0 var iPattern = 0 var longestCommonSubsequence = 0 var localCommonSubstring = 0 while (iCandidate < candidateLength && iPattern < patternLength) { if (candidate[iCandidate] == pattern[iPattern]) { localCommonSubstring++ } else { longestCommonSubsequence += localCommonSubstring localCommonSubstring = 0 if (iCandidate != iPattern) { // Using max to bypass the need for computer transpositions ("ab" vs "ba") val iMax = Math.max(iCandidate, iPattern) iCandidate = iMax iPattern = iMax if (iMax >= Math.min(candidateLength, patternLength)) { break } } searchWindow@ for (i in 0 until maxOffset) { when { (iCandidate + i) < candidateLength -> { if (candidate[iCandidate + i] == pattern[iPattern]) { iCandidate += i localCommonSubstring++ break@searchWindow } } (iPattern + i) < patternLength -> { if (candidate[iCandidate] == pattern[iPattern + i]) { iPattern += i localCommonSubstring++ break@searchWindow } } else -> break@searchWindow } } } iCandidate++ iPattern++ } longestCommonSubsequence += localCommonSubstring Math.max(candidateLength, patternLength) - longestCommonSubsequence } } /** Checks whether the candidate contains the pattern in order. */ fun containsCharactersInOrder(candidate: CharSequence, pattern: CharSequence, caseSensitive: Boolean): Boolean { var iCandidate = 0 var iPattern = 0 while (iCandidate < candidate.length && iPattern < pattern.length) { var patternChar = pattern[iPattern] var testChar = candidate[iCandidate] if (!caseSensitive) { patternChar = Character.toLowerCase(patternChar) testChar = Character.toLowerCase(testChar) } if (patternChar == testChar) { iPattern++ } iCandidate++ } return iPattern == pattern.length }
mit
83320858934d1d7312ce2ab75f813f47
35.175258
112
0.538045
5.308623
false
false
false
false
ilya-g/intellij-markdown
src/org/intellij/markdown/parser/sequentialparsers/impl/BacktickParser.kt
1
2362
package org.intellij.markdown.parser.sequentialparsers.impl import org.intellij.markdown.MarkdownElementTypes import org.intellij.markdown.MarkdownTokenTypes import org.intellij.markdown.parser.sequentialparsers.SequentialParser import org.intellij.markdown.parser.sequentialparsers.SequentialParserUtil import org.intellij.markdown.parser.sequentialparsers.TokensCache import java.util.* class BacktickParser : SequentialParser { override fun parse(tokens: TokensCache, rangesToGlue: Collection<IntRange>): SequentialParser.ParsingResult { val result = SequentialParser.ParsingResult() val indices = SequentialParserUtil.textRangesToIndices(rangesToGlue) val delegateIndices = ArrayList<Int>() var i = 0 while (i < indices.size) { val iterator = tokens.ListIterator(indices, i) if (iterator.type == MarkdownTokenTypes.BACKTICK || iterator.type == MarkdownTokenTypes.ESCAPED_BACKTICKS) { val j = findOfSize(tokens, indices, i + 1, getLength(iterator, true)) if (j != -1) { result.withNode(SequentialParser.Node(indices[i]..indices[j] + 1, MarkdownElementTypes.CODE_SPAN)) i = j + 1 continue } } delegateIndices.add(indices[i]) ++i } return result.withFurtherProcessing(SequentialParserUtil.indicesToTextRanges(delegateIndices)) } private fun findOfSize(tokens: TokensCache, indices: List<Int>, from: Int, length: Int): Int { for (i in from..indices.size - 1) { val iterator = tokens.ListIterator(indices, i) if (iterator.type != MarkdownTokenTypes.BACKTICK && iterator.type != MarkdownTokenTypes.ESCAPED_BACKTICKS) { continue } if (getLength(iterator, false) == length) { return i } } return -1 } private fun getLength(info: TokensCache.Iterator, canEscape: Boolean): Int { val tokenText = info.text var toSubtract = 0 if (info.type == MarkdownTokenTypes.ESCAPED_BACKTICKS) { if (canEscape) { toSubtract = 2 } else { toSubtract = 1 } } return tokenText.length - toSubtract } }
apache-2.0
65b81cccf1ad9c04c53c60ee1d85d402
34.787879
120
0.626164
4.830266
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/util/AppOpener.kt
1
13734
package jp.juggler.subwaytooter.util import android.app.Activity import android.content.ComponentName import android.content.Intent import android.content.SharedPreferences import android.net.Uri import androidx.browser.customtabs.CustomTabColorSchemeParams import androidx.browser.customtabs.CustomTabsIntent import jp.juggler.subwaytooter.ActCallback import jp.juggler.subwaytooter.ActMain import jp.juggler.subwaytooter.R import jp.juggler.subwaytooter.action.conversationLocal import jp.juggler.subwaytooter.action.conversationOtherInstance import jp.juggler.subwaytooter.action.tagDialog import jp.juggler.subwaytooter.action.userProfile import jp.juggler.subwaytooter.api.entity.* import jp.juggler.subwaytooter.api.entity.TootStatus.Companion.findStatusIdFromUrl import jp.juggler.subwaytooter.api.entity.TootTag.Companion.findHashtagFromUrl import jp.juggler.subwaytooter.pref.PrefB import jp.juggler.subwaytooter.pref.pref import jp.juggler.subwaytooter.span.LinkInfo import jp.juggler.subwaytooter.table.SavedAccount import jp.juggler.util.* // Subway Tooterの「アプリ設定/挙動/リンクを開く際にCustom Tabsを使わない」をONにして // 投稿のコンテキストメニューの「トゥートへのアクション/Webページを開く」「ユーザへのアクション/Webページを開く」を使うと // 投げたインテントをST自身が受け取って「次のアカウントから開く」ダイアログが出て // 「Webページを開く」をまた押すと無限ループしてダイアログの影が徐々に濃くなりそのうち壊れる // これを避けるには、投稿やトゥートを開く際に bpDontUseCustomTabs がオンならST以外のアプリを列挙したアプリ選択ダイアログを出すしかない private val log = LogCategory("AppOpener") // 例外を出す private fun Activity.openBrowserExcludeMe(intent: Intent) { // if (intent.component == null) { // val cn = PrefS.spWebBrowser(pref).cn() // if (cn?.exists(this) == true) { // intent.component = cn // } // } ActCallback.setUriFromApp(intent.data) startActivity(intent) // // // このアプリのパッケージ名 // val myName = packageName // // val filter: (ResolveInfo) -> Boolean = { // when { // it.activityInfo.packageName == myName -> false // !it.activityInfo.exported -> false // // // Huaweiの謎Activityのせいでうまく働かないことがある // -1 != it.activityInfo.packageName.indexOf("com.huawei.android.internal") -> false // // // 標準アプリが設定されていない場合、アプリを選択するためのActivityが出てくる場合がある // it.activityInfo.packageName == "android" -> false // it.activityInfo.javaClass.name.startsWith("com.android.internal") -> false // it.activityInfo.javaClass.name.startsWith("com.android.systemui") -> false // // // たぶんChromeとかfirefoxとか // else -> true // } // } // // // resolveActivity がこのアプリ以外のActivityを返すなら、それがベストなんだろう // // ただしAndroid M以降はMATCH_DEFAULT_ONLYだと「常時」が設定されてないとnullを返す // val ri = packageManager!!.resolveActivity( // intent, // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // PackageManager.MATCH_ALL // } else { // PackageManager.MATCH_DEFAULT_ONLY // } // )?.takeIf(filter) // // return when { // // ri != null -> { // intent.setClassName(ri.activityInfo.packageName, ri.activityInfo.name) // log.d("startActivityExcludeMyApp(1) $intent") // startActivity(intent, startAnimationBundle) // true // } // // else -> DlgAppPicker( // this, // intent, // autoSelect = true, // filter = filter, // addCopyAction = false // ) { // try { // intent.component = it.cn() // log.d("startActivityExcludeMyApp(2) $intent") // startActivity(intent, startAnimationBundle) // } catch (ex: Throwable) { // log.trace(ex) // showToast(ex, "can't open. ${intent.data}") // } // }.show() // } // } catch (ex: Throwable) { // log.trace(ex) // showToast(ex, "can't open. ${intent.data}") // } } fun Activity.openBrowser(uri: Uri?) { uri ?: return try { openBrowserExcludeMe( Intent(Intent.ACTION_VIEW, uri).apply { addCategory(Intent.CATEGORY_BROWSABLE) } ) } catch (ex: Throwable) { log.trace(ex) showToast(ex, "can't open. ${intent.data}") } } fun Activity.openBrowser(url: String?) = openBrowser(url.mayUri()) // Chrome Custom Tab を開く fun Activity.openCustomTab(url: String?, pref: SharedPreferences = pref()) { url ?: return if (url.isEmpty()) { showToast(false, "URL is empty string.") return } if (PrefB.bpDontUseCustomTabs(pref)) { openBrowser(url) return } try { // 例外を出す fun startCustomTabIntent(cn: ComponentName?) = CustomTabsIntent.Builder() .setDefaultColorSchemeParams( CustomTabColorSchemeParams.Builder() .setToolbarColor(attrColor(R.attr.colorPrimary)) .build() ) .setShowTitle(true) .build() .let { log.w("startCustomTabIntent ComponentName=$cn") openBrowserExcludeMe( it.intent.also { intent -> if (cn != null) intent.component = cn intent.data = url.toUri() }, ) } if (url.startsWith("http") && PrefB.bpPriorChrome(pref)) { try { // 初回はChrome指定で試す val cn = ComponentName( "com.android.chrome", "com.google.android.apps.chrome.Main" ) startCustomTabIntent(cn) return } catch (ex2: Throwable) { log.e(ex2, "openCustomTab: missing chrome. retry to other application.") } } // Chromeがないようなのでcomponent指定なしでリトライ startCustomTabIntent(null) } catch (ex: Throwable) { log.trace(ex) val scheme = url.mayUri()?.scheme ?: url showToast(true, "can't open browser app for $scheme") } } fun Activity.openCustomTab(ta: TootAttachment) = openCustomTab(ta.getLargeUrl(pref())) fun openCustomTab( activity: ActMain, pos: Int, url: String, accessInfo: SavedAccount? = null, tagList: ArrayList<String>? = null, allowIntercept: Boolean = true, whoRef: TootAccountRef? = null, linkInfo: LinkInfo? = null, ) { try { log.d("openCustomTab: $url") val whoAcct = if (whoRef != null) { accessInfo?.getFullAcct(whoRef.get()) } else { null } if (allowIntercept && accessInfo != null) { // ハッシュタグはいきなり開くのではなくメニューがある val tagInfo = url.findHashtagFromUrl() if (tagInfo != null) { activity.tagDialog( accessInfo, pos, url, Host.parse(tagInfo.second), tagInfo.first, tagList, whoAcct ) return } val statusInfo = url.findStatusIdFromUrl() if (statusInfo != null) { when { // fedibirdの参照のURLだった && 閲覧アカウントが参照を扱える // 参照カラムを開く statusInfo.statusId != null && statusInfo.isReference && TootInstance.getCached(accessInfo)?.canUseReference == true -> activity.conversationLocal( pos, accessInfo, statusInfo.statusId, isReference = statusInfo.isReference, ) // 疑似アカウント? // 別サーバ? // ステータスIDがない?(Pleroma) accessInfo.isNA || !accessInfo.matchHost(statusInfo.host) || statusInfo.statusId == null -> activity.conversationOtherInstance( pos, statusInfo.url, statusInfo.statusId, statusInfo.host, statusInfo.statusId, isReference = statusInfo.isReference, ) else -> activity.conversationLocal( pos, accessInfo, statusInfo.statusId, isReference = statusInfo.isReference, ) } return } // opener.linkInfo をチェックしてメンションを判別する val mention = linkInfo?.mention if (mention != null) { val fullAcct = getFullAcctOrNull(mention.acct, mention.url, accessInfo) if (fullAcct != null) { if (fullAcct.host != null) { when (fullAcct.host.ascii) { "github.com", "twitter.com", -> activity.openCustomTab(mention.url) "gmail.com" -> activity.openBrowser("mailto:${fullAcct.pretty}") else -> activity.userProfile( pos, accessInfo, // FIXME nullが必要なケースがあったっけなかったっけ… acct = fullAcct, userUrl = mention.url, originalUrl = url, ) } return } } } // ユーザページをアプリ内で開く var m = TootAccount.reAccountUrl.matcher(url) if (m.find()) { val host = m.groupEx(1)!! val user = m.groupEx(2)!!.decodePercent() val instance = m.groupEx(3)?.decodePercent()?.notEmpty() // https://misskey.xyz/@[email protected] // https://misskey.xyz/@[email protected] if (instance != null) { val instanceHost = Host.parse(instance) when (instanceHost.ascii) { "github.com", "twitter.com" -> { activity.openCustomTab("https://$instance/$user") } "gmail.com" -> { activity.openBrowser("mailto:$user@$instance") } else -> { activity.userProfile( pos, null, // Misskeyだと疑似アカが必要なんだっけ…? acct = Acct.parse(user, instanceHost), userUrl = "https://$instance/@$user", originalUrl = url, ) } } } else { activity.userProfile( pos, accessInfo, Acct.parse(user, host), url ) } return } m = TootAccount.reAccountUrl2.matcher(url) if (m.find()) { val host = m.groupEx(1)!! val user = m.groupEx(2)!!.decodePercent() activity.userProfile( pos, accessInfo, Acct.parse(user, host), url, ) return } } activity.openCustomTab(url) } catch (ex: Throwable) { log.trace(ex) log.e(ex, "openCustomTab failed. $url") } }
apache-2.0
f1233d60453db5d6363f033ad6962e32
34.159544
99
0.466593
4.430017
false
false
false
false
DemonWav/MinecraftDevIntelliJ
src/main/kotlin/com/demonwav/mcdev/platform/mixin/inspection/MixinAnnotationAttributeInspection.kt
1
1696
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.inspection import com.demonwav.mcdev.util.annotationFromNameValuePair import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.JavaElementVisitor import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiAnnotationMemberValue import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiNameValuePair abstract class MixinAnnotationAttributeInspection( private val annotation: List<String>, private val attribute: String? ) : MixinInspection() { constructor(annotation: String, attribute: String?) : this(listOf(annotation), attribute) protected abstract fun visitAnnotationAttribute( annotation: PsiAnnotation, value: PsiAnnotationMemberValue, holder: ProblemsHolder ) final override fun buildVisitor(holder: ProblemsHolder): PsiElementVisitor = Visitor(holder) private inner class Visitor(private val holder: ProblemsHolder) : JavaElementVisitor() { override fun visitNameValuePair(pair: PsiNameValuePair) { if ( pair.name != attribute && (attribute != null || pair.name != PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME) ) { return } val psiAnnotation = pair.annotationFromNameValuePair ?: return if (psiAnnotation.qualifiedName !in annotation) { return } val value = pair.value ?: return visitAnnotationAttribute(psiAnnotation, value, this.holder) } } }
mit
4cf49474c49dc9cbac9f95102670e814
29.836364
96
0.692217
5.186544
false
false
false
false
paplorinc/intellij-community
plugins/git4idea/src/git4idea/rebase/GitRewordOperation.kt
4
8722
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.rebase import com.intellij.notification.NotificationAction import com.intellij.notification.NotificationType import com.intellij.openapi.diagnostic.Attachment import com.intellij.openapi.diagnostic.logger 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.progress.util.BackgroundTaskUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vcs.VcsNotifier import com.intellij.openapi.vcs.VcsNotifier.STANDARD_NOTIFICATION import com.intellij.openapi.vcs.changes.ChangeListManagerImpl import com.intellij.util.containers.MultiMap import com.intellij.vcs.log.Hash import com.intellij.vcs.log.VcsCommitMetadata import git4idea.branch.GitRebaseParams import git4idea.checkin.GitCheckinEnvironment import git4idea.commands.Git import git4idea.commands.GitCommand import git4idea.commands.GitLineHandler import git4idea.config.GitConfigUtil import git4idea.config.GitVersionSpecialty import git4idea.findProtectedRemoteBranchContainingCommit import git4idea.history.GitLogUtil import git4idea.rebase.GitRebaseEntry.Action.PICK import git4idea.rebase.GitRebaseEntry.Action.REWORD import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryChangeListener import git4idea.reset.GitResetMode import java.io.File import java.io.IOException class GitRewordOperation(private val repository: GitRepository, private val commit: VcsCommitMetadata, private val newMessage: String) { init { repository.update() } private val LOG = logger<GitRewordOperation>() private val project = repository.project private val notifier = VcsNotifier.getInstance(project) private val initialHeadPosition = repository.currentRevision!! private var headAfterReword: String? = null private var rewordedCommit: Hash? = null fun execute() { var reworded = false if (canRewordViaAmend()) { reworded = rewordViaAmend() } if (!reworded) { reworded = rewordViaRebase() } if (reworded) { headAfterReword = repository.currentRevision rewordedCommit = findNewHashOfRewordedCommit(headAfterReword!!) notifySuccess() ChangeListManagerImpl.getInstanceImpl(project).replaceCommitMessage(commit.fullMessage, newMessage) } } private fun canRewordViaAmend() = isLatestCommit() && GitVersionSpecialty.CAN_AMEND_WITHOUT_FILES.existsIn(project) private fun isLatestCommit() = commit.id.asString() == initialHeadPosition private fun rewordViaRebase(): Boolean { val rebaseEditor = GitAutomaticRebaseEditor(project, commit.root, entriesEditor = { list -> injectRewordAction(list) }, plainTextEditor = { editorText -> supplyNewMessage(editorText) }) val params = GitRebaseParams.editCommits(commit.parents.first().asString(), rebaseEditor, true) val indicator = ProgressManager.getInstance().progressIndicator ?: EmptyProgressIndicator() val spec = GitRebaseSpec.forNewRebase(project, params, listOf(repository), indicator) val rewordProcess = RewordProcess(spec) rewordProcess.rebase() return rewordProcess.succeeded } private fun rewordViaAmend(): Boolean { val handler = GitLineHandler(project, repository.root, GitCommand.COMMIT) val messageFile: File try { messageFile = GitCheckinEnvironment.createCommitMessageFile(project, repository.root, newMessage) } catch(e: IOException) { LOG.warn("Couldn't create message file", e) return false } handler.addParameters("--amend") handler.addParameters("-F", messageFile.absolutePath) handler.addParameters("--only") // without any files: to amend only the message val result = Git.getInstance().runCommand(handler) repository.update() if (result.success()) { return true } else { LOG.warn("Couldn't reword via amend: " + result.errorOutputAsJoinedString) return false } } internal fun undo() { val possibility = checkUndoPossibility() val errorTitle = "Can't Undo Reword" when (possibility) { is UndoPossibility.HeadMoved -> notifier.notifyError(errorTitle, "Repository has already been changed") is UndoPossibility.PushedToProtectedBranch -> notifier.notifyError(errorTitle, "Commit has already been pushed to ${possibility.branch}") is UndoPossibility.Error -> notifier.notifyError(errorTitle, "") else -> doUndo() } } private fun doUndo() { val res = Git.getInstance().reset(repository, GitResetMode.KEEP, initialHeadPosition) repository.update() if (!res.success()) { notifier.notifyError("Undo Reword Failed", res.errorOutputAsHtmlString) } } private fun injectRewordAction(list: List<GitRebaseEntry>): List<GitRebaseEntry> { return list.map { entry -> if (entry.action == PICK && commit.id.asString().startsWith(entry.commit)) GitRebaseEntry(REWORD, entry.commit, entry.subject) else entry } } private fun supplyNewMessage(editorText: String): String { if (editorText.startsWith(commit.fullMessage)) { // there are comments after the proposed message return newMessage } else { LOG.error("Unexpected editor content. Charset: ${GitConfigUtil.getCommitEncoding(project, commit.root)}", Attachment("actual.txt", editorText), Attachment("expected.txt", commit.fullMessage)) throw IllegalStateException("Unexpected editor content") } } private fun findNewHashOfRewordedCommit(newHead: String): Hash? { val newCommitsRange = "${commit.parents.first().asString()}..$newHead" val newCommits = GitLogUtil.collectMetadata(project, repository.root, false, newCommitsRange).commits if (newCommits.isEmpty()) { LOG.error("Couldn't find commits after reword in range $newCommitsRange") return null } val newCommit = newCommits.find { commit.author == it.author && commit.authorTime == it.authorTime && StringUtil.equalsIgnoreWhitespaces(it.fullMessage, newMessage) } if (newCommit == null) { LOG.error("Couldn't find the reworded commit in range $newCommitsRange") return null } return newCommit.id } private fun checkUndoPossibility(): UndoPossibility { repository.update() if (repository.currentRevision != headAfterReword) { return UndoPossibility.HeadMoved } if (rewordedCommit == null) { LOG.error("Couldn't find the reworded commit") return UndoPossibility.Error } val protectedBranch = findProtectedRemoteBranchContainingCommit(repository, rewordedCommit!!) if (protectedBranch != null) return UndoPossibility.PushedToProtectedBranch(protectedBranch) return UndoPossibility.Possible } private fun notifySuccess() { val notification = STANDARD_NOTIFICATION.createNotification("Reworded Successfully", "", NotificationType.INFORMATION, null) notification.addAction(NotificationAction.createSimple("Undo") { notification.expire() undoInBackground() }) val connection = project.messageBus.connect() notification.whenExpired { connection.disconnect() } connection.subscribe(GitRepository.GIT_REPO_CHANGE, GitRepositoryChangeListener { it: GitRepository -> if (it == repository) { BackgroundTaskUtil.executeOnPooledThread(repository, Runnable { if (checkUndoPossibility() !== UndoPossibility.Possible) notification.expire() }) } }) notifier.notify(notification) } private fun undoInBackground() { ProgressManager.getInstance().run(object : Task.Backgroundable(project, "Undoing Reword") { override fun run(indicator: ProgressIndicator) { undo() } }) } private sealed class UndoPossibility { object Possible : UndoPossibility() object HeadMoved : UndoPossibility() class PushedToProtectedBranch(val branch: String) : UndoPossibility() object Error : UndoPossibility() } private inner class RewordProcess(spec: GitRebaseSpec) : GitRebaseProcess(project, spec, null) { var succeeded = false override fun notifySuccess(successful: MutableMap<GitRepository, GitSuccessfulRebase>, skippedCommits: MultiMap<GitRepository, GitRebaseUtils.CommitInfo>) { succeeded = true } } }
apache-2.0
f6b33eaf351e7e280c90627e05aa9a57
37.258772
140
0.728847
4.624602
false
false
false
false
paplorinc/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/GithubPullRequestsBusyStateTrackerImpl.kt
1
1616
// 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.github.pullrequest.data import com.intellij.openapi.Disposable import com.intellij.util.EventDispatcher import com.intellij.util.containers.ContainerUtil import org.jetbrains.annotations.CalledInAny import org.jetbrains.annotations.CalledInAwt import java.util.* class GithubPullRequestsBusyStateTrackerImpl : GithubPullRequestsBusyStateTracker { private val busySet = ContainerUtil.newConcurrentSet<Long>() private val busyChangeEventDispatcher = EventDispatcher.create(GithubPullRequestBusyStateListener::class.java) @CalledInAwt override fun acquire(pullRequest: Long): Boolean { val ok = busySet.add(pullRequest) if (ok) busyChangeEventDispatcher.multicaster.busyStateChanged(pullRequest) return ok } @CalledInAwt override fun release(pullRequest: Long) { val ok = busySet.remove(pullRequest) if (ok) busyChangeEventDispatcher.multicaster.busyStateChanged(pullRequest) } @CalledInAny override fun isBusy(pullRequest: Long) = busySet.contains(pullRequest) @CalledInAwt override fun addPullRequestBusyStateListener(disposable: Disposable, listener: (Long) -> Unit) = busyChangeEventDispatcher.addListener(object : GithubPullRequestBusyStateListener { override fun busyStateChanged(pullRequest: Long) { listener(pullRequest) } }, disposable) private interface GithubPullRequestBusyStateListener : EventListener { fun busyStateChanged(pullRequest: Long) } }
apache-2.0
644803d3331d2d475d43f90d9b5b4697
36.604651
140
0.793936
4.823881
false
false
false
false
RuneSuite/client
plugins/src/main/java/org/runestar/client/plugins/customfonts/CustomFonts.kt
1
4864
package org.runestar.client.plugins.customfonts import org.kxtra.swing.graphics.use import org.kxtra.swing.image.BufferedImage import org.kxtra.swing.image.DataBufferByte import org.kxtra.swing.image.createCompatibleWritableRaster import org.runestar.client.api.forms.FontForm import org.runestar.client.api.plugins.DisposablePlugin import org.runestar.client.cacheids.FontId import org.runestar.client.raw.CLIENT import org.runestar.client.raw.access.XArchive import org.runestar.client.raw.access.XFont import org.runestar.client.raw.access.XFontName import org.runestar.client.raw.access.XComponent import org.runestar.client.api.plugins.PluginSettings import java.awt.Font import java.awt.FontMetrics import java.awt.image.BufferedImage import java.nio.ByteBuffer import javax.imageio.ImageTypeSpecifier class CustomFonts : DisposablePlugin<CustomFonts.Settings>() { private val CHARS = charset("cp1252").decode(ByteBuffer.wrap(ByteArray(256) { it.toByte() })) override val defaultSettings = Settings() override val name = "Custom Fonts" private lateinit var oldFontMap: HashMap<*, *> override fun onStart() { oldFontMap = HashMap(CLIENT.fontsMap) val fonts = HashMap<Int, XFont>() val metrics = HashMap<Int, ByteArray>() for (fr in settings.fonts) { val f = fr.font.value val fm = CLIENT.canvas.getFontMetrics(f) val bm = binaryMetrics(fm) metrics[fr.id] = bm fonts[fr.id] = rasterize(f, fm, bm) } for (e in fonts) { fontName(e.key)?.let { CLIENT.fontsMap[it] = e.value } } reloadPrimaryFonts() add(XComponent.getFont.enter.subscribe { it.returned = fonts[it.instance.fontId] ?: return@subscribe it.skipBody = true }) add(XArchive.takeFile.exit.subscribe { if (it.instance != CLIENT.archive13) return@subscribe it.returned = metrics[it.arguments[0] as Int] ?: return@subscribe }) } override fun onStop() { CLIENT.fontsMap = oldFontMap reloadPrimaryFonts() } private fun fontName(fontId: Int): XFontName? { return when (fontId) { FontId.P11_FULL -> CLIENT.fontName_plain11 FontId.P12_FULL -> CLIENT.fontName_plain12 FontId.B12_FULL -> CLIENT.fontName_bold12 FontId.VERDANA_11PT_REGULAR -> CLIENT.fontName_verdana11 FontId.VERDANA_13PT_REGULAR -> CLIENT.fontName_verdana13 FontId.VERDANA_15PT_REGULAR -> CLIENT.fontName_verdana15 else -> null } } private fun reloadPrimaryFonts() { CLIENT.fontPlain11 = CLIENT.fontsMap[CLIENT.fontName_plain11] as XFont CLIENT.fontPlain12 = CLIENT.fontsMap[CLIENT.fontName_plain12] as XFont CLIENT.fontBold12 = CLIENT.fontsMap[CLIENT.fontName_bold12] as XFont } private fun rasterize(f: Font, fm: FontMetrics, bm: ByteArray): XFont { val maxAscent = fm.maxAscent val maxDescent = fm.maxDescent val bearings = IntArray(CHARS.length) val widths = IntArray(CHARS.length) val width = fm.maxAdvance widths.fill(width) val heights = IntArray(CHARS.length) val height = maxAscent + maxDescent heights.fill(height) val data = ByteArray(width * height) val cm = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_BYTE_GRAY).colorModel val wr = cm.createCompatibleWritableRaster(width, height, DataBufferByte(data)) val img = BufferedImage(cm, wr) val pixels = arrayOfNulls<ByteArray>(CHARS.length) CHARS.forEachIndexed { i, c -> if (excludeChar(c)) return@forEachIndexed img.createGraphics().use { g -> g.font = f g.drawString(c.toString(), 0, maxAscent) } pixels[i] = data.clone() data.fill(0) } return CLIENT._Font_( bm, bearings, bearings, widths, heights, null, pixels ) } private fun excludeChar(c: Char): Boolean = c.isISOControl() || c == 160.toChar() private fun binaryMetrics(fm: FontMetrics): ByteArray { val bm = ByteArray(CHARS.length + 1) CHARS.forEachIndexed { i, c -> if (excludeChar(c)) return@forEachIndexed bm[i] = fm.charWidth(c).toByte() } bm[CHARS.length] = fm.maxAscent.toByte() return bm } class Settings( val fonts: List<FontReplace> = listOf(FontReplace(FontId.P12_FULL, FontForm(Font.SANS_SERIF, FontForm.Style.PLAIN, 12f))) ) : PluginSettings() { class FontReplace(val id: Int, val font: FontForm) } }
mit
f07b9c9348acf2dbd0a13d581577de85
32.784722
133
0.634663
3.98036
false
false
false
false
indianpoptart/RadioControl
RadioControl/app/src/main/java/com/nikhilparanjape/radiocontrol/fragments/BatteryFragment.kt
1
1092
package com.nikhilparanjape.radiocontrol.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.nikhilparanjape.radiocontrol.R import com.nikhilparanjape.radiocontrol.adapters.RecyclerAdapter /** * Created by Nikhil on 07/31/2018. * * @author Nikhil Paranjape * * */ class BatteryFragment : Fragment() { private var batteryTrouble = arrayOf("Blacklist", "Crisis", "Gotham", "Banshee", "Breaking Bad") override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val rootView = inflater.inflate(R.layout.battery_fragment, container, false) val rv = rootView.findViewById<RecyclerView>(R.id.batteryRV) rv.layoutManager = LinearLayoutManager(this.activity) val adapter = RecyclerAdapter(batteryTrouble) rv.adapter = adapter return rootView } }
gpl-3.0
c25918f960680d5f7074491d9d84fdc7
28.513514
116
0.760073
4.439024
false
false
false
false
google/intellij-community
plugins/settings-repository/src/actions/SyncAction.kt
3
2399
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.settingsRepository.actions import com.intellij.notification.NotificationGroupManager import com.intellij.notification.NotificationType import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import kotlinx.coroutines.runBlocking import org.jetbrains.settingsRepository.LOG import org.jetbrains.settingsRepository.SyncType import org.jetbrains.settingsRepository.icsManager import org.jetbrains.settingsRepository.icsMessage internal val NOTIFICATION_GROUP = NotificationGroupManager.getInstance().getNotificationGroup("Settings Repository") internal sealed class SyncAction(private val syncType: SyncType) : DumbAwareAction() { override fun getActionUpdateThread() = ActionUpdateThread.BGT override fun update(e: AnActionEvent) { if (ApplicationManager.getApplication().isUnitTestMode) { return } val repositoryManager = icsManager.repositoryManager e.presentation.isEnabledAndVisible = (repositoryManager.isRepositoryExists() && repositoryManager.hasUpstream()) || (syncType == SyncType.MERGE && icsManager.readOnlySourcesManager.repositories.isNotEmpty()) } override fun actionPerformed(event: AnActionEvent) { runBlocking { syncAndNotify(syncType, event.project) } } } private suspend fun syncAndNotify(syncType: SyncType, project: Project?) { try { val message = if (icsManager.syncManager.sync(syncType, project)) { icsMessage("sync.done.message") } else { icsMessage("sync.up.to.date.message") } NOTIFICATION_GROUP.createNotification(message, NotificationType.INFORMATION).notify(project) } catch (e: Exception) { LOG.warn(e) NOTIFICATION_GROUP.createNotification(icsMessage("sync.rejected.title"), e.message ?: icsMessage("sync.internal.error"), NotificationType.ERROR).notify(project) } } internal class MergeAction : SyncAction(SyncType.MERGE) internal class ResetToTheirsAction : SyncAction(SyncType.OVERWRITE_LOCAL) internal class ResetToMyAction : SyncAction(SyncType.OVERWRITE_REMOTE)
apache-2.0
cffd5b13fcf6f616834b15871c6494a0
40.362069
164
0.783243
4.987526
false
false
false
false
cd1/motofretado
app/src/main/java/com/gmail/cristiandeives/motofretado/ViewMapPresenterLoader.kt
1
1039
package com.gmail.cristiandeives.motofretado import android.content.Context import android.support.annotation.MainThread import android.support.v4.content.Loader import android.util.Log @MainThread internal class ViewMapPresenterLoader(context: Context) : Loader<ViewMapMvp.Presenter>(context) { companion object { private val TAG = ViewMapPresenterLoader::class.java.simpleName } private var mPresenter: ViewMapMvp.Presenter? = null override fun onStartLoading() { Log.v(TAG, "> onStartLoading()") if (mPresenter == null) { forceLoad() } else { deliverResult(mPresenter) } Log.v(TAG, "< onStartLoading()") } override fun onForceLoad() { Log.v(TAG, "> onForceLoad()") mPresenter = ViewMapPresenter(context) deliverResult(mPresenter) Log.v(TAG, "< onForceLoad()") } override fun onReset() { Log.v(TAG, "> onReset()") mPresenter = null Log.v(TAG, "< onReset()") } }
gpl-3.0
2f7d1128f61361da7332c279c442f607
22.636364
97
0.633301
4.311203
false
false
false
false
square/okio
okio/src/unixMain/kotlin/okio/-UnixPosixVariant.kt
1
6642
/* * Copyright (C) 2020 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 okio import kotlinx.cinterop.ByteVar import kotlinx.cinterop.CPointer import kotlinx.cinterop.CValuesRef import kotlinx.cinterop.UnsafeNumber import kotlinx.cinterop.allocArray import kotlinx.cinterop.convert import kotlinx.cinterop.memScoped import kotlinx.cinterop.toKString import okio.Path.Companion.toPath import okio.internal.toPath import platform.posix.DEFFILEMODE import platform.posix.ENOENT import platform.posix.FILE import platform.posix.O_CREAT import platform.posix.O_EXCL import platform.posix.O_RDWR import platform.posix.PATH_MAX import platform.posix.S_IFLNK import platform.posix.S_IFMT import platform.posix.errno import platform.posix.fdopen import platform.posix.fileno import platform.posix.fopen import platform.posix.free import platform.posix.getenv import platform.posix.mkdir import platform.posix.open import platform.posix.pread import platform.posix.pwrite import platform.posix.readlink import platform.posix.realpath import platform.posix.remove import platform.posix.rename import platform.posix.stat import platform.posix.symlink import platform.posix.timespec internal actual val PLATFORM_TEMPORARY_DIRECTORY: Path get() { val tmpdir = getenv("TMPDIR") if (tmpdir != null) return tmpdir.toKString().toPath() return "/tmp".toPath() } internal actual val PLATFORM_DIRECTORY_SEPARATOR = "/" internal actual fun PosixFileSystem.variantDelete(path: Path, mustExist: Boolean) { val result = remove(path.toString()) if (result != 0) { if (errno == ENOENT) { if (mustExist) throw FileNotFoundException("no such file: $path") else return } throw errnoToIOException(errno) } } @OptIn(UnsafeNumber::class) internal actual fun PosixFileSystem.variantMkdir(dir: Path): Int { return mkdir(dir.toString(), 0b111111111u.convert() /* octal 777 */) } internal actual fun PosixFileSystem.variantCanonicalize(path: Path): Path { // Note that realpath() fails if the file doesn't exist. val fullpath = realpath(path.toString(), null) ?: throw errnoToIOException(errno) try { return Buffer().writeNullTerminated(fullpath).toPath(normalize = true) } finally { free(fullpath) } } internal actual fun PosixFileSystem.variantMove( source: Path, target: Path ) { val result = rename(source.toString(), target.toString()) if (result != 0) { throw errnoToIOException(errno) } } internal actual fun PosixFileSystem.variantSource(file: Path): Source { val openFile: CPointer<FILE> = fopen(file.toString(), "r") ?: throw errnoToIOException(errno) return FileSource(openFile) } internal actual fun PosixFileSystem.variantSink(file: Path, mustCreate: Boolean): Sink { val openFile: CPointer<FILE> = fopen(file.toString(), if (mustCreate) "wx" else "w") ?: throw errnoToIOException(errno) return FileSink(openFile) } internal actual fun PosixFileSystem.variantAppendingSink(file: Path, mustExist: Boolean): Sink { // There is a `r+` flag which we could have used to force existence of [file] but this flag // doesn't allow opening for appending, and we don't currently have a way to move the cursor to // the end of the file. We are then forcing existence non-atomically. if (mustExist && !exists(file)) throw IOException("$file doesn't exist.") val openFile: CPointer<FILE> = fopen(file.toString(), "a") ?: throw errnoToIOException(errno) return FileSink(openFile) } internal actual fun PosixFileSystem.variantOpenReadOnly(file: Path): FileHandle { val openFile: CPointer<FILE> = fopen(file.toString(), "r") ?: throw errnoToIOException(errno) return UnixFileHandle(false, openFile) } internal actual fun PosixFileSystem.variantOpenReadWrite( file: Path, mustCreate: Boolean, mustExist: Boolean ): FileHandle { // Note that we're using open() followed by fdopen() rather than fopen() because this way we // can pass exactly the flags we want. Note that there's no string mode that opens for reading // and writing that creates if necessary. ("a+" has features but can't do random access). val flags = when { mustCreate && mustExist -> throw IllegalArgumentException("Cannot require mustCreate and mustExist at the same time.") mustCreate -> O_RDWR or O_CREAT or O_EXCL mustExist -> O_RDWR else -> O_RDWR or O_CREAT } val fid = open(file.toString(), flags, DEFFILEMODE) if (fid == -1) throw errnoToIOException(errno) // Use 'r+' to get reading and writing on the FILE, which is all we need. val openFile = fdopen(fid, "r+") ?: throw errnoToIOException(errno) return UnixFileHandle(true, openFile) } internal actual fun PosixFileSystem.variantCreateSymlink(source: Path, target: Path) { if (source.parent == null || !exists(source.parent!!)) { throw IOException("parent directory does not exist: ${source.parent}") } if (exists(source)) { throw IOException("already exists: $source") } val result = symlink(target.toString(), source.toString()) if (result != 0) { throw errnoToIOException(errno) } } @OptIn(UnsafeNumber::class) internal fun variantPread( file: CPointer<FILE>, target: CValuesRef<*>, byteCount: Int, offset: Long ): Int = pread(fileno(file), target, byteCount.convert(), offset).convert() @OptIn(UnsafeNumber::class) internal fun variantPwrite( file: CPointer<FILE>, source: CValuesRef<*>, byteCount: Int, offset: Long ): Int = pwrite(fileno(file), source, byteCount.convert(), offset).convert() @OptIn(UnsafeNumber::class) internal val timespec.epochMillis: Long get() = tv_sec * 1000L + tv_sec / 1_000_000L @OptIn(UnsafeNumber::class) internal fun symlinkTarget(stat: stat, path: Path): Path? { if (stat.st_mode.toInt() and S_IFMT != S_IFLNK) return null // `path` is a symlink, let's resolve its target. memScoped { val buffer = allocArray<ByteVar>(PATH_MAX) val byteCount = readlink(path.toString(), buffer, PATH_MAX.convert()) if (byteCount.convert<Int>() == -1) { throw errnoToIOException(errno) } return buffer.toKString().toPath() } }
apache-2.0
0f93446ffca30a3f56dd50bab0c6e584
31.719212
97
0.733966
3.773864
false
false
false
false
fluidsonic/fluid-json
coding/sources-jvm/JsonDecoder.kt
1
3892
package io.fluidsonic.json import java.io.* public interface JsonDecoder<out Context : JsonCodingContext> : JsonReader { public val context: Context override fun readValue(): Any = readValueOfType() public fun <Value : Any> readValueOfType(valueType: JsonCodingType<Value>): Value public companion object { public fun builder(): BuilderForCodecs<JsonCodingContext> = BuilderForCodecsImpl(context = JsonCodingContext.empty) public fun <Context : JsonCodingContext> builder(context: Context): BuilderForCodecs<Context> = BuilderForCodecsImpl(context = context) public interface Builder<out Context : JsonCodingContext> { public fun build(): JsonDecoder<Context> } public interface BuilderForCodecs<out Context : JsonCodingContext> { public fun codecs( vararg providers: JsonCodecProvider<Context>, base: JsonCodecProvider<JsonCodingContext>? = JsonCodecProvider.extended ): BuilderForSource<Context> = codecs(providers = providers.toList(), base = base) public fun codecs( providers: Iterable<JsonCodecProvider<Context>>, base: JsonCodecProvider<JsonCodingContext>? = JsonCodecProvider.extended ): BuilderForSource<Context> } private class BuilderForCodecsImpl<out Context : JsonCodingContext>( private val context: Context ) : BuilderForCodecs<Context> { override fun codecs( providers: Iterable<JsonCodecProvider<Context>>, base: JsonCodecProvider<JsonCodingContext>? ) = BuilderForSourceImpl( context = context, codecProvider = JsonCodecProvider(base?.let { providers + it } ?: providers) ) } public interface BuilderForSource<out Context : JsonCodingContext> { public fun source(source: JsonReader): Builder<Context> public fun source(source: Reader): Builder<Context> = source(JsonReader.build(source)) public fun source(source: String): Builder<Context> = source(StringReader(source)) } private class BuilderForSourceImpl<out Context : JsonCodingContext>( private val context: Context, private val codecProvider: JsonCodecProvider<Context> ) : BuilderForSource<Context> { override fun source(source: JsonReader) = BuilderImpl( context = context, codecProvider = codecProvider, source = source ) } private class BuilderImpl<out Context : JsonCodingContext>( private val context: Context, private val codecProvider: JsonCodecProvider<Context>, private val source: JsonReader ) : Builder<Context> { override fun build() = StandardDecoder( context = context, codecProvider = codecProvider, source = source ) } } } public fun JsonDecoder<*>.invalidPropertyError(property: String, details: String): Nothing = schemaError("Invalid value for property '$property': $details") public fun JsonDecoder<*>.invalidValueError(details: String): Nothing = schemaError("Invalid value: $details") public fun JsonDecoder<*>.missingPropertyError(property: String): Nothing = schemaError("Missing value for property '$property'") public fun JsonDecoder<*>.parsingError(message: String): Nothing = throw JsonException.Parsing( message = message, offset = offset, path = path ) public fun JsonDecoder<*>.readValueOrNull(): Any? = if (nextToken != JsonToken.nullValue) readValue() else readNull() public inline fun <reified Value : Any> JsonDecoder<*>.readValueOfType(): Value = readValueOfType(jsonCodingType()) public inline fun <reified Value : Any> JsonDecoder<*>.readValueOfTypeOrNull(): Value? = readValueOfTypeOrNull(jsonCodingType()) public fun <Value : Any> JsonDecoder<*>.readValueOfTypeOrNull(valueType: JsonCodingType<Value>): Value? = readOrNull { readValueOfType(valueType) } public fun JsonDecoder<*>.schemaError(message: String): Nothing = throw JsonException.Schema( message = message, offset = offset, path = path )
apache-2.0
2d5ed66f5689b5ed4931e4ef19727b9e
24.774834
105
0.735868
4.373034
false
false
false
false
DeflatedPickle/Quiver
filepanel/src/main/kotlin/com/deflatedpickle/quiver/filepanel/dialog/AssignProgramDialog.kt
1
5140
/* Copyright (c) 2021 DeflatedPickle under the MIT license */ package com.deflatedpickle.quiver.filepanel.dialog import com.deflatedpickle.marvin.util.OSUtil import com.deflatedpickle.quiver.Quiver import com.deflatedpickle.quiver.filepanel.api.Program import com.deflatedpickle.undulation.DocumentAdapter import com.deflatedpickle.undulation.constraints.FillHorizontalFinishLine import com.deflatedpickle.undulation.constraints.StickEast import com.deflatedpickle.undulation.extensions.toPatternFilter import com.deflatedpickle.undulation.util.Filters import com.deflatedpickle.undulation.widget.ButtonField import com.deflatedpickle.undulation.widget.taginput.TagInput import org.jdesktop.swingx.JXLabel import org.jdesktop.swingx.JXTextField import org.oxbow.swingbits.dialog.task.TaskDialog import java.awt.GridBagLayout import java.awt.Window import java.io.File import javax.swing.BorderFactory import javax.swing.JFileChooser import javax.swing.JPanel import javax.swing.JScrollPane import javax.swing.JSeparator import javax.swing.SwingUtilities import javax.swing.text.PlainDocument class AssignProgramDialog( window: Window, ) : TaskDialog(window, "Assign Program") { companion object { fun open(window: Window): Program? { val dialog = AssignProgramDialog(window) dialog.extensionsEntry.field.text = Quiver.selectedFile!!.extension dialog.isVisible = true if (dialog.result == StandardCommand.OK) { if (dialog.extensionsEntry.field.text.isNotBlank()) { dialog.extensionsEntry.tags.add(dialog.extensionsEntry.field.text) } return Program( dialog.nameEntry.text, dialog.locationEntry.field.text.substringBeforeLast("/"), dialog.locationEntry.field.text.substringAfterLast("/"), dialog.argsEntry.text, dialog.extensionsEntry.tags ) } return null } } private fun validationCheck() = nameEntry.text != "" && locationEntry.field.text.let { val dir = File(it.substringBeforeLast("/")) val program = it.substringAfterLast("/") val file = dir.resolve(program) it != "" && dir.exists() && dir.isDirectory && program != "" && file.exists() && file.isFile } && (extensionsEntry.tags.isNotEmpty() || extensionsEntry.field.text.isNotBlank()) val nameEntry: JXTextField = JXTextField("Name").apply { toolTipText = "The name to assign to this program" (document as PlainDocument).documentFilter = Filters.FILE this.document.addDocumentListener( DocumentAdapter { fireValidationFinished(validationCheck()) } ) SwingUtilities.invokeLater { fireValidationFinished(validationCheck()) } } val locationEntry: ButtonField = ButtonField( "Location", "The location of the program", OSUtil.getOS().toPatternFilter(), "Open" ) { val directoryChooser = JFileChooser( it.field.text ).apply { fileSelectionMode = JFileChooser.FILES_ONLY isAcceptAllFileFilterUsed = false } val openResult = directoryChooser.showOpenDialog(window) if (openResult == JFileChooser.APPROVE_OPTION) { it.field.text = directoryChooser.selectedFile.absolutePath } }.apply { this.field.document.addDocumentListener( DocumentAdapter { fireValidationFinished(validationCheck()) } ) } val argsEntry: JXTextField = JXTextField("Args").apply { toolTipText = "The arguments the command will receive" text = "{file}" } val extensionsEntry: TagInput = TagInput().apply { addChangeListener { fireValidationFinished(validationCheck()) } } init { setCommands( StandardCommand.OK, StandardCommand.CANCEL ) fixedComponent = JScrollPane( JPanel().apply { isOpaque = false layout = GridBagLayout() add(JXLabel("Name:"), StickEast) add(nameEntry, FillHorizontalFinishLine) add(JXLabel("Location:"), StickEast) add(locationEntry, FillHorizontalFinishLine) add(JSeparator(), FillHorizontalFinishLine) add(JXLabel("Args:"), StickEast) add(argsEntry, FillHorizontalFinishLine) add(JSeparator(), FillHorizontalFinishLine) add(JXLabel("Extensions:"), StickEast) add(extensionsEntry, FillHorizontalFinishLine) } ).apply { isOpaque = false viewport.isOpaque = false border = BorderFactory.createEmptyBorder() } } }
mit
a9be43cd9d6369096cb0a85c54f993be
32.16129
86
0.61751
5.014634
false
false
false
false
zdary/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/PackageScope.kt
1
1199
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls internal sealed class PackageScope(open val scopeName: String) : Comparable<PackageScope> { @get:Nls abstract val displayName: String override fun compareTo(other: PackageScope): Int = scopeName.compareTo(other.scopeName) object Missing : PackageScope("") { @Nls override val displayName = PackageSearchBundle.message("packagesearch.ui.missingScope") @NonNls override fun toString() = "[Missing scope]" } data class Named(override val scopeName: String) : PackageScope(scopeName) { init { require(scopeName.isNotBlank()) { "A Named scope name cannot be blank." } } @Nls override val displayName = scopeName @NonNls override fun toString() = scopeName } companion object { fun from(rawScope: String?): PackageScope { if (rawScope.isNullOrBlank()) return Missing return Named(rawScope.trim()) } } }
apache-2.0
2a9aa5cf8d7e0daec528d23c78149f98
26.883721
95
0.675563
4.995833
false
false
false
false
leafclick/intellij-community
plugins/github/src/org/jetbrains/plugins/github/AbstractGithubUrlGroupingAction.kt
1
2820
// 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.github import com.intellij.openapi.actionSystem.* import com.intellij.openapi.components.service import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import git4idea.repo.GitRemote import git4idea.repo.GitRepository import org.jetbrains.plugins.github.util.GithubGitHelper import org.jetbrains.plugins.github.util.GithubUrlUtil import javax.swing.Icon /** * Visible and enabled if there's at least one possible github remote url ([GithubGitHelper]). * If there's only one url - it will be used for action, otherwise child actions will be created for each url. */ abstract class AbstractGithubUrlGroupingAction(text: String?, description: String?, icon: Icon?) : ActionGroup(text, description, icon), DumbAware { final override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = isEnabledAndVisible(e) } protected open fun isEnabledAndVisible(e: AnActionEvent): Boolean { val project = e.getData(CommonDataKeys.PROJECT) if (project == null || project.isDefault) return false return service<GithubGitHelper>().havePossibleRemotes(project) } final override fun getChildren(e: AnActionEvent?): Array<AnAction> { val project = e?.getData(CommonDataKeys.PROJECT) ?: return AnAction.EMPTY_ARRAY val coordinates = service<GithubGitHelper>().getPossibleRemoteUrlCoordinates(project) return if (coordinates.size > 1) { coordinates.map { object : DumbAwareAction(it.remote.name + ": " + GithubUrlUtil.removeProtocolPrefix(it.url)) { override fun actionPerformed(e: AnActionEvent) { actionPerformed(e, project, it.repository, it.remote, it.url) } } }.toTypedArray() } else AnAction.EMPTY_ARRAY } final override fun actionPerformed(e: AnActionEvent) { val project = e.getData(CommonDataKeys.PROJECT) ?: return val coordinates = service<GithubGitHelper>().getPossibleRemoteUrlCoordinates(project) coordinates.singleOrNull()?.let { actionPerformed(e, project, it.repository, it.remote, it.url) } } abstract fun actionPerformed(e: AnActionEvent, project: Project, repository: GitRepository, remote: GitRemote, remoteUrl: String) final override fun canBePerformed(context: DataContext): Boolean { val project = context.getData(CommonDataKeys.PROJECT) ?: return false val coordinates = service<GithubGitHelper>().getPossibleRemoteUrlCoordinates(project) return coordinates.size == 1 } final override fun isPopup(): Boolean = true final override fun disableIfNoVisibleChildren(): Boolean = false }
apache-2.0
150fdf1f0ad09b32e83291cd91f81430
40.485294
140
0.755319
4.630542
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/multiDecl/VarCapturedInFunctionLiteral.kt
5
226
class A { operator fun component1() = 1 operator fun component2() = 2 } fun box() : String { var (a, b) = A() val local = { a = 3 } local() return if (a == 3 && b == 2) "OK" else "fail" }
apache-2.0
7f097c5f88210a14cd71bd3c9168698f
14.133333
49
0.464602
3.054054
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/coroutines/intLikeVarSpilling/complicatedMerge.kt
2
715
// WITH_RUNTIME // WITH_COROUTINES import helpers.* import kotlin.coroutines.experimental.* import kotlin.coroutines.experimental.intrinsics.* class Controller { suspend fun suspendHere(): Unit = suspendCoroutineOrReturn { x -> x.resume(Unit) COROUTINE_SUSPENDED } } fun builder(c: suspend Controller.() -> Unit) { c.startCoroutine(Controller(), EmptyContinuation) } fun foo() = true private var booleanResult = false fun setBooleanRes(x: Boolean) { booleanResult = x } fun box(): String { builder { val x = true val y = false suspendHere() setBooleanRes(if (foo()) x else y) } if (!booleanResult) return "fail 1" return "OK" }
apache-2.0
4232e5f4e633944cf815b6880d91a5a2
18.861111
69
0.65035
4.039548
false
false
false
false
blokadaorg/blokada
android5/app/src/main/java/service/TranslationService.kt
1
3470
/* * This file is part of Blokada. * * 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 https://mozilla.org/MPL/2.0/. * * Copyright © 2021 Blocka AB. All rights reserved. * * @author Karol Gusak ([email protected]) */ package service import androidx.core.os.LocaleListCompat import com.akexorcist.localizationactivity.ui.LocalizationActivity import repository.TranslationRepository import repository.getFirstSupportedLocale import repository.getTranslationRepository import ui.utils.cause import utils.Logger import java.util.* object TranslationService { private val log = Logger("Translation") /** * Localization lib we use puts a limitation on us, that it requires Activity to be started to * provide actual user locale. So, we default to English for before that moment. This may lead * to wrong strings in some scenarios (I imagine: a notification while Activity is not started). * * Also check the comment in TranslationRepository's LocaleListCompat. */ private var locale: Locale = Locale.ROOT private lateinit var repo: TranslationRepository private var initialized = false private val untranslated = mutableListOf<Localised>() fun setup() { log.v("Translation service set up, locale: $locale") initialized = true reload(skipUpdatingActivity = true) } fun setLocale(locale: String?) { try { this.locale = Locale.forLanguageTag(locale!!) } catch (ex: NullPointerException) { // Just use default this.locale = findDefaultLocale() } catch (ex: Exception) { log.w("Could not use configured locale: $locale".cause(ex)) this.locale = findDefaultLocale() } log.v("Setting locale to: ${this.locale}") reload() } private fun findDefaultLocale(): Locale { val supported = LocaleListCompat.getAdjustedDefault() log.v("Supported locales are: ${supported.toLanguageTags()} (size: ${supported.size()})") return supported.getFirstSupportedLocale() } fun getLocale(): Locale { return locale } fun get(string: Localised): String { return repo.getText(string) ?: run { if (!untranslated.contains(string)) { // Show warning once per string log.w("No translation for: $string") untranslated.add(string) } if (!EnvironmentService.isPublicBuild()) "@$string@" else string } } private fun reload(skipUpdatingActivity: Boolean = false) { if (initialized) { log.v("Reloading translations repositories") if (!skipUpdatingActivity) applyLocaleToActivity() repo = getTranslationRepository(this.locale) } } private fun applyLocaleToActivity() { try { val ctx = ContextService.requireContext() as LocalizationActivity ctx.setLanguage(locale) log.v("Applied locale to activity") } catch (ex: Exception) { log.e("Could not apply locale to activity".cause(ex)) } } } /// Localised are strings that are supposed to be localised (translated) typealias Localised = String fun Localised.tr(): String { return TranslationService.get(this) }
mpl-2.0
dca24c578f5209d7b47b183aed93926d
30.545455
100
0.649467
4.594702
false
false
false
false
MGaetan89/Kolumbus
kolumbus/src/main/kotlin/io/kolumbus/adapter/TableInfoAdapter.kt
1
2327
/* * Copyright (C) 2016 MGaetan89 * * 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.kolumbus.adapter import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import io.kolumbus.R import io.realm.RealmModel import io.realm.annotations.PrimaryKey import java.lang.reflect.Field import java.lang.reflect.ParameterizedType class TableInfoAdapter(val fields: List<Field>, val instance: RealmModel) : RecyclerView.Adapter<TableInfoAdapter.ViewHolder>() { override fun getItemCount() = this.fields.size override fun onBindViewHolder(holder: ViewHolder, position: Int) { val field = this.fields[position].apply { this.isAccessible = true } val genericType = field.genericType val value = field.get(this.instance) holder.name.text = if (field.isAnnotationPresent(PrimaryKey::class.java)) "#${field.name}" else field.name holder.type.text = if (genericType is ParameterizedType) { val subType = genericType.actualTypeArguments[0] as Class<Any> "${field.type.simpleName}<${subType.simpleName}>" } else { field.type.simpleName } holder.value.text = when (field.type) { String::class.java -> if (value != null) "\"$value\"" else "null" else -> value?.toString() ?: "null" } } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder? { val view = LayoutInflater.from(parent?.context).inflate(R.layout.kolumbus_adapter_table_info, parent, false) return ViewHolder(view) } class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val name = view.findViewById(R.id.field_name) as TextView val type = view.findViewById(R.id.field_type) as TextView val value = view.findViewById(R.id.field_default_value) as TextView } }
apache-2.0
1c3067c42f97bfb84fe55431a6a3ba0f
34.8
129
0.748174
3.771475
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/sam/constructors/samWrappersDifferentFiles.kt
2
498
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_RUNTIME // FILE: 1/wrapped.kt fun getWrapped1(): Runnable { val f = { } return Runnable(f) } // FILE: 2/wrapped2.kt fun getWrapped2(): Runnable { val f = { } return Runnable(f) } // FILE: box.kt fun box(): String { val class1 = getWrapped1().javaClass val class2 = getWrapped2().javaClass return if (class1 != class2) "OK" else "Same class: $class1" }
apache-2.0
cab4b1a6bf941d15c4673e501987f29a
18.153846
72
0.640562
3.276316
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/stdlib/collections/ReversedViewsTest/testBehavior.kt
2
3278
import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue import kotlin.test.* fun <T> compare(expected: T, actual: T, block: CompareContext<T>.() -> Unit) { CompareContext(expected, actual).block() } class CompareContext<out T>(public val expected: T, public val actual: T) { public fun equals(message: String = "") { assertEquals(expected, actual, message) } public fun <P> propertyEquals(message: String = "", getter: T.() -> P) { assertEquals(expected.getter(), actual.getter(), message) } public fun propertyFails(getter: T.() -> Unit) { assertFailEquals({ expected.getter() }, { actual.getter() }) } public fun <P> compareProperty(getter: T.() -> P, block: CompareContext<P>.() -> Unit) { compare(expected.getter(), actual.getter(), block) } private fun assertFailEquals(expected: () -> Unit, actual: () -> Unit) { val expectedFail = assertFails(expected) val actualFail = assertFails(actual) //assertEquals(expectedFail != null, actualFail != null) assertTypeEquals(expectedFail, actualFail) } } fun <T> CompareContext<List<T>>.listBehavior() { equalityBehavior() collectionBehavior() compareProperty({ listIterator() }, { listIteratorBehavior() }) compareProperty({ listIterator(0) }, { listIteratorBehavior() }) propertyFails { listIterator(-1) } propertyFails { listIterator(size + 1) } for (index in expected.indices) propertyEquals { this[index] } propertyFails { this[size] } propertyEquals { indexOf(elementAtOrNull(0)) } propertyEquals { lastIndexOf(elementAtOrNull(0)) } propertyFails { subList(0, size + 1) } propertyFails { subList(-1, 0) } propertyEquals { subList(0, size) } } fun <T> CompareContext<T>.equalityBehavior(objectName: String = "") { val prefix = objectName + if (objectName.isNotEmpty()) "." else "" equals(objectName) propertyEquals(prefix + "hashCode") { hashCode() } propertyEquals(prefix + "toString") { toString() } } fun <T> CompareContext<Collection<T>>.collectionBehavior(objectName: String = "") { val prefix = objectName + if (objectName.isNotEmpty()) "." else "" propertyEquals(prefix + "size") { size } propertyEquals(prefix + "isEmpty") { isEmpty() } (object {}).let { propertyEquals { contains(it as Any?) } } propertyEquals { contains(firstOrNull()) } propertyEquals { containsAll(this) } } public fun CompareContext<ListIterator<*>>.listIteratorProperties() { propertyEquals { hasNext() } propertyEquals { hasPrevious() } propertyEquals { nextIndex() } propertyEquals { previousIndex() } } fun <T> CompareContext<ListIterator<T>>.listIteratorBehavior() { listIteratorProperties() while (expected.hasNext()) { propertyEquals { next() } listIteratorProperties() } propertyFails { next() } while (expected.hasPrevious()) { propertyEquals { previous() } listIteratorProperties() } propertyFails { previous() } } fun box() { val original = listOf(2L, 3L, Long.MAX_VALUE) val reversed = original.reversed() compare(reversed, original.asReversed()) { listBehavior() } }
apache-2.0
0f8e41e2cd9a08a5c82e1d8b61003c35
30.219048
92
0.655583
4.441734
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/multifileClasses/multifileClassWithCrossCall.kt
3
469
// TARGET_BACKEND: JVM // WITH_RUNTIME // FILE: Baz.java public class Baz { public static String baz() { return Util.foo() + Util.bar(); } } // FILE: bar.kt @file:JvmName("Util") @file:JvmMultifileClass public fun bar(): String = barx() public fun foox(): String = "O" // FILE: foo.kt @file:JvmName("Util") @file:JvmMultifileClass public fun foo(): String = foox() public fun barx(): String = "K" // FILE: test.kt fun box(): String = Baz.baz()
apache-2.0
7cd6f684e114f1d359568b17bb5b1a6c
15.172414
39
0.628998
3.045455
false
false
false
false
AndroidX/androidx
compose/ui/ui-geometry/src/commonMain/kotlin/androidx/compose/ui/geometry/MutableRect.kt
3
3325
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.geometry import androidx.compose.runtime.Stable import kotlin.math.max import kotlin.math.min /** * An mutable, 2D, axis-aligned, floating-point rectangle whose coordinates * are relative to a given origin. * * @param left The offset of the left edge of this rectangle from the x axis. * @param top The offset of the top edge of this rectangle from the y axis. * @param right The offset of the right edge of this rectangle from the x axis. * @param bottom The offset of the bottom edge of this rectangle from the y axis. */ class MutableRect( var left: Float, var top: Float, var right: Float, var bottom: Float ) { /** The distance between the left and right edges of this rectangle. */ inline val width: Float get() = right - left /** The distance between the top and bottom edges of this rectangle. */ inline val height: Float get() = bottom - top /** * The distance between the upper-left corner and the lower-right corner of * this rectangle. */ val size: Size get() = Size(width, height) /** * Whether this rectangle encloses a non-zero area. Negative areas are * considered empty. */ val isEmpty: Boolean get() = left >= right || top >= bottom /** * Modifies `this` to be the intersection of this and the rect formed * by [left], [top], [right], and [bottom]. */ @Stable fun intersect(left: Float, top: Float, right: Float, bottom: Float) { this.left = max(left, this.left) this.top = max(top, this.top) this.right = min(right, this.right) this.bottom = min(bottom, this.bottom) } /** * Whether the point specified by the given offset (which is assumed to be * relative to the origin) lies between the left and right and the top and * bottom edges of this rectangle. * * Rectangles include their top and left edges but exclude their bottom and * right edges. */ operator fun contains(offset: Offset): Boolean { return offset.x >= left && offset.x < right && offset.y >= top && offset.y < bottom } /** * Sets new bounds to ([left], [top], [right], [bottom]) */ fun set(left: Float, top: Float, right: Float, bottom: Float) { this.left = left this.top = top this.right = right this.bottom = bottom } override fun toString() = "MutableRect(" + "${left.toStringAsFixed(1)}, " + "${top.toStringAsFixed(1)}, " + "${right.toStringAsFixed(1)}, " + "${bottom.toStringAsFixed(1)})" } fun MutableRect.toRect(): Rect = Rect(left, top, right, bottom)
apache-2.0
1e2a1658416f1958cfa2057fd9315427
31.930693
91
0.645414
4.040097
false
false
false
false
kohesive/kohesive-iac
model-aws/src/generated/kotlin/uy/kohesive/iac/model/aws/cloudformation/resources/Lambda.kt
1
2357
package uy.kohesive.iac.model.aws.cloudformation.resources import uy.kohesive.iac.model.aws.cloudformation.ResourceProperties import uy.kohesive.iac.model.aws.cloudformation.CloudFormationType import uy.kohesive.iac.model.aws.cloudformation.CloudFormationTypes @CloudFormationTypes object Lambda { @CloudFormationType("AWS::Lambda::EventSourceMapping") data class EventSourceMapping( val BatchSize: String? = null, val Enabled: String? = null, val EventSourceArn: String, val FunctionName: String, val StartingPosition: String ) : ResourceProperties @CloudFormationType("AWS::Lambda::Alias") data class Alias( val Description: String? = null, val FunctionName: String, val FunctionVersion: String, val Name: String ) : ResourceProperties @CloudFormationType("AWS::Lambda::Function") data class Function( val Code: Function.CodeProperty, val Description: String? = null, val Environment: Function.EnvironmentProperty? = null, val FunctionName: String? = null, val Handler: String, val KmsKeyArn: String? = null, val MemorySize: String? = null, val Role: String, val Runtime: String, val Timeout: String? = null, val VpcConfig: Function.VPCConfigProperty? = null ) : ResourceProperties { data class CodeProperty( val S3Bucket: String? = null, val S3Key: String? = null, val S3ObjectVersion: String? = null, val ZipFile: String? = null ) data class EnvironmentProperty( val Variables: Map<String, String>? = null ) data class VPCConfigProperty( val SecurityGroupIds: List<String>, val SubnetIds: List<String> ) } @CloudFormationType("AWS::Lambda::Permission") data class Permission( val Action: String, val FunctionName: String, val Principal: String, val SourceAccount: String? = null, val SourceArn: String? = null ) : ResourceProperties @CloudFormationType("AWS::Lambda::Version") data class Version( val CodeSha256: String? = null, val Description: String? = null, val FunctionName: String ) : ResourceProperties }
mit
04f2a3e37237ca440144eb27adbdc7a0
28.848101
67
0.638524
4.621569
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/viewmodels/MessagesViewModel.kt
1
25049
package com.kickstarter.viewmodels import android.content.Intent import android.util.Pair import com.kickstarter.libs.ActivityViewModel import com.kickstarter.libs.CurrentUserType import com.kickstarter.libs.Either import com.kickstarter.libs.Either.Left import com.kickstarter.libs.Either.Right import com.kickstarter.libs.Environment import com.kickstarter.libs.MessagePreviousScreenType import com.kickstarter.libs.rx.transformers.Transformers import com.kickstarter.libs.utils.ListUtils import com.kickstarter.libs.utils.ObjectUtils import com.kickstarter.libs.utils.PairUtils import com.kickstarter.libs.utils.extensions.isNonZero import com.kickstarter.libs.utils.extensions.isPresent import com.kickstarter.libs.utils.extensions.negate import com.kickstarter.models.Backing import com.kickstarter.models.BackingWrapper import com.kickstarter.models.Message import com.kickstarter.models.MessageThread import com.kickstarter.models.Project import com.kickstarter.models.User import com.kickstarter.services.ApiClientType import com.kickstarter.services.apiresponses.ErrorEnvelope import com.kickstarter.services.apiresponses.MessageThreadEnvelope import com.kickstarter.ui.IntentKey import com.kickstarter.ui.activities.MessagesActivity import com.kickstarter.ui.data.MessageSubject import com.kickstarter.ui.data.MessagesData import rx.Observable import rx.subjects.BehaviorSubject import rx.subjects.PublishSubject interface MessagesViewModel { interface Inputs { /** Call with the app bar's vertical offset value. */ fun appBarOffset(verticalOffset: Int) /** Call with the app bar's total scroll range. */ fun appBarTotalScrollRange(totalScrollRange: Int) /** Call when the back or close button has been clicked. */ fun backOrCloseButtonClicked() /** Call when the message edit text changes. */ fun messageEditTextChanged(messageBody: String) /** Call when the message edit text is in focus. */ fun messageEditTextIsFocused(isFocused: Boolean) /** Call when the send message button has been clicked. */ fun sendMessageButtonClicked() /** Call when the view pledge button is clicked. */ fun viewPledgeButtonClicked() } interface Outputs { /** Emits a boolean that determines if the back button should be gone. */ fun backButtonIsGone(): Observable<Boolean> /** Emits the backing and project to populate the backing info header. */ fun backingAndProject(): Observable<Pair<Backing, Project>> /** Emits a boolean that determines if the backing info view should be gone. */ fun backingInfoViewIsGone(): Observable<Boolean> /** Emits a boolean that determines if the close button should be gone. */ fun closeButtonIsGone(): Observable<Boolean> /** Emits the creator name to be displayed. */ fun creatorNameTextViewText(): Observable<String> /** Emits when we should navigate back. */ fun goBack(): Observable<Void> /** Emits a boolean to determine if the loading indicator should be gone. */ fun loadingIndicatorViewIsGone(): Observable<Boolean> /** Emits a string to display as the message edit text hint. */ fun messageEditTextHint(): Observable<String> /** Emits when the edit text should request focus. */ fun messageEditTextShouldRequestFocus(): Observable<Void> /** Emits a list of messages to be displayed. */ fun messageList(): Observable<List<Message>?> /** Emits the project name to be displayed. */ fun projectNameTextViewText(): Observable<String> /** Emits the project name to be displayed in the toolbar. */ fun projectNameToolbarTextViewText(): Observable<String> /** Emits the bottom padding for the recycler view. */ fun recyclerViewDefaultBottomPadding(): Observable<Void> /** Emits the initial bottom padding for the recycler view to account for the app bar scroll range. */ fun recyclerViewInitialBottomPadding(): Observable<Int> /** Emits when the RecyclerView should be scrolled to the bottom. */ fun scrollRecyclerViewToBottom(): Observable<Void> /** Emits a boolean that determines if the Send button should be enabled. */ fun sendMessageButtonIsEnabled(): Observable<Boolean> /** Emits a string to set the message edit text to. */ fun setMessageEditText(): Observable<String> /** Emits a string to display in the message error toast. */ fun showMessageErrorToast(): Observable<String> /** Emits when we should start the [BackingActivity]. */ fun startBackingActivity(): Observable<BackingWrapper> /** Emits when the thread has been marked as read. */ fun successfullyMarkedAsRead(): Observable<Void> /** Emits a boolean to determine when the toolbar should be expanded. */ fun toolbarIsExpanded(): Observable<Boolean> /** Emits a boolean that determines if the View pledge button should be gone. */ fun viewPledgeButtonIsGone(): Observable<Boolean> } class ViewModel(environment: Environment) : ActivityViewModel<MessagesActivity?>(environment), Inputs, Outputs { private val client: ApiClientType private val currentUser: CurrentUserType private fun projectAndBacker(envelopeAndData: Pair<MessageThreadEnvelope, MessagesData>): Pair<Project, User> { val project = envelopeAndData.second.project val backer = if (project.isBacking()) envelopeAndData.second.currentUser else envelopeAndData.first.messageThread() ?.participant() return Pair.create(project, backer) } private val appBarOffset = PublishSubject.create<Int>() private val appBarTotalScrollRange = PublishSubject.create<Int>() private val backOrCloseButtonClicked = PublishSubject.create<Void>() private val messageEditTextChanged = PublishSubject.create<String>() private val messageEditTextIsFocused = PublishSubject.create<Boolean?>() private val sendMessageButtonClicked = PublishSubject.create<Void>() private val viewPledgeButtonClicked = PublishSubject.create<Void>() private val backButtonIsGone: Observable<Boolean> private val backingAndProject = BehaviorSubject.create<Pair<Backing, Project>?>() private val backingInfoViewIsGone = BehaviorSubject.create<Boolean>() private val closeButtonIsGone: Observable<Boolean> private val creatorNameTextViewText = BehaviorSubject.create<String>() private val goBack: Observable<Void> private val loadingIndicatorViewIsGone: Observable<Boolean> private val messageEditTextHint = BehaviorSubject.create<String>() private val messageEditTextShouldRequestFocus = PublishSubject.create<Void>() private val messageList = BehaviorSubject.create<List<Message>?>() private val projectNameTextViewText = BehaviorSubject.create<String>() private val projectNameToolbarTextViewText: Observable<String> private val recyclerViewDefaultBottomPadding: Observable<Void> private val recyclerViewInitialBottomPadding: Observable<Int> private val scrollRecyclerViewToBottom: Observable<Void> private val showMessageErrorToast = PublishSubject.create<String>() private val sendMessageButtonIsEnabled: Observable<Boolean> private val setMessageEditText: Observable<String> private val startBackingActivity = PublishSubject.create<BackingWrapper>() private val successfullyMarkedAsRead = BehaviorSubject.create<Void>() private val toolbarIsExpanded: Observable<Boolean> private val viewPledgeButtonIsGone = BehaviorSubject.create<Boolean>() val inputs: Inputs = this val outputs: Outputs = this override fun appBarOffset(verticalOffset: Int) { appBarOffset.onNext(verticalOffset) } override fun appBarTotalScrollRange(totalScrollRange: Int) { appBarTotalScrollRange.onNext(totalScrollRange) } override fun backOrCloseButtonClicked() { backOrCloseButtonClicked.onNext(null) } override fun messageEditTextChanged(messageBody: String) { messageEditTextChanged.onNext(messageBody) } override fun messageEditTextIsFocused(isFocused: Boolean) { messageEditTextIsFocused.onNext(isFocused) } override fun sendMessageButtonClicked() { sendMessageButtonClicked.onNext(null) } override fun viewPledgeButtonClicked() { viewPledgeButtonClicked.onNext(null) } override fun backButtonIsGone(): Observable<Boolean> = backButtonIsGone override fun backingAndProject(): Observable<Pair<Backing, Project>> = backingAndProject override fun backingInfoViewIsGone(): Observable<Boolean> = backingInfoViewIsGone override fun closeButtonIsGone(): Observable<Boolean> = closeButtonIsGone override fun goBack(): Observable<Void> = goBack override fun loadingIndicatorViewIsGone(): Observable<Boolean> = loadingIndicatorViewIsGone override fun messageEditTextHint(): Observable<String> = messageEditTextHint override fun messageEditTextShouldRequestFocus(): Observable<Void> = messageEditTextShouldRequestFocus override fun messageList(): Observable<List<Message>?> = messageList override fun creatorNameTextViewText(): Observable<String> = creatorNameTextViewText override fun projectNameTextViewText(): Observable<String> = projectNameTextViewText override fun projectNameToolbarTextViewText(): Observable<String> = projectNameToolbarTextViewText override fun recyclerViewDefaultBottomPadding(): Observable<Void> = recyclerViewDefaultBottomPadding override fun recyclerViewInitialBottomPadding(): Observable<Int> = recyclerViewInitialBottomPadding override fun scrollRecyclerViewToBottom(): Observable<Void> = scrollRecyclerViewToBottom override fun showMessageErrorToast(): Observable<String> = showMessageErrorToast override fun sendMessageButtonIsEnabled(): Observable<Boolean> = sendMessageButtonIsEnabled override fun setMessageEditText(): Observable<String> = setMessageEditText override fun startBackingActivity(): Observable<BackingWrapper> = startBackingActivity override fun successfullyMarkedAsRead(): Observable<Void> = successfullyMarkedAsRead override fun toolbarIsExpanded(): Observable<Boolean> = toolbarIsExpanded override fun viewPledgeButtonIsGone(): Observable<Boolean> = viewPledgeButtonIsGone companion object { private fun backingAndProjectFromData( data: MessagesData, client: ApiClientType ): Observable<Pair<Backing, Project>?>? { return data.backingOrThread.either( { Observable.just(Pair.create(it, data.project)) } ) { val backingNotification = if (data.project.isBacking()) client.fetchProjectBacking( data.project, data.currentUser ).materialize().share() else client.fetchProjectBacking( data.project, data.participant ).materialize().share() Observable.merge( backingNotification.compose(Transformers.errors()) .map { null }, backingNotification.compose(Transformers.values()) .map { Pair.create(it, data.project) } ) .take(1) } } } init { client = requireNotNull(environment.apiClient()) currentUser = requireNotNull(environment.currentUser()) val configData = intent() .map { i: Intent -> val messageThread = i.getParcelableExtra<MessageThread>(IntentKey.MESSAGE_THREAD) messageThread?.let { Left(it) } ?: Right<MessageThread, Pair<Project?, Backing?>>( Pair.create( i.getParcelableExtra(IntentKey.PROJECT), i.getParcelableExtra(IntentKey.BACKING) ) ) } val messageAccountTypeObservable = intent() .map { it.getSerializableExtra(IntentKey.MESSAGE_SCREEN_SOURCE_CONTEXT) } .ofType(MessagePreviousScreenType::class.java) val configBacking = configData .map { it.right() } .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .map { PairUtils.second(it) } .map { requireNotNull(it) } val configThread = configData .map { it.left() } .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } val backingOrThread: Observable<Either<Backing, MessageThread>> = Observable.merge( configBacking.map { Left(it) }, configThread.map { Right(it) } ) val messageIsSending = PublishSubject.create<Boolean>() val messagesAreLoading = PublishSubject.create<Boolean>() val project = configData .map { data: Either<MessageThread, Pair<Project?, Backing?>> -> data.either({ obj: MessageThread -> obj.project() }) { projectAndBacking: Pair<Project?, Backing?> -> projectAndBacking.first } }.filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } val initialMessageThreadEnvelope = backingOrThread .switchMap { val response = it.either({ backing -> client.fetchMessagesForBacking( backing ) }) { messageThread -> client.fetchMessagesForThread( messageThread ) } response .doOnSubscribe { messagesAreLoading.onNext(true) } .doAfterTerminate { messagesAreLoading.onNext(false) } .compose(Transformers.neverError()) .share() } loadingIndicatorViewIsGone = messagesAreLoading .map { it.negate() } .distinctUntilChanged() // If view model was not initialized with a MessageThread, participant is // the project creator. val participant = Observable.combineLatest( initialMessageThreadEnvelope.map { it.messageThread() }, project ) { a: MessageThread?, b: Project? -> Pair.create(a, b) } .map { if (it.first != null) it?.first?.participant() else it.second?.creator() }.filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .take(1) participant .map { it.name() } .compose(bindToLifecycle()) .subscribe(messageEditTextHint) val messagesData = Observable.combineLatest( backingOrThread, project, participant, currentUser.observable() ) { backingOrThread: Either<Backing, MessageThread>, project: Project, participant: User, currentUser: User -> MessagesData( backingOrThread, project, participant, currentUser ) } val messageSubject = messagesData .map { (backingOrThread1, project1, _, currentUser1): MessagesData -> backingOrThread1.either( // Message subject is the project if the current user is the backer, // otherwise the current user is the creator and will send a message to the backing. { backing: Backing -> if (backing.backerId() == currentUser1.id()) MessageSubject.Project( project1 ) else MessageSubject.Backing(backing) }) { messageThread: MessageThread -> MessageSubject.MessageThread( messageThread ) } } val messageNotification = messageSubject .compose(Transformers.combineLatestPair(messageEditTextChanged)) .compose( Transformers.takeWhen( sendMessageButtonClicked ) ) .switchMap { client.sendMessage( it.first, it.second ) .doOnSubscribe { messageIsSending.onNext(true) } } .materialize() .share() val messageSent = messageNotification.compose(Transformers.values()).ofType( Message::class.java ) val sentMessageThreadEnvelope = backingOrThread .compose(Transformers.takeWhen(messageSent)) .switchMap { it.either({ backing: Backing -> client.fetchMessagesForBacking( backing ) }) { messageThread: MessageThread -> client.fetchMessagesForThread( messageThread ) } } .compose(Transformers.neverError()) .share() val messageThreadEnvelope = Observable.merge( initialMessageThreadEnvelope, sentMessageThreadEnvelope ) .distinctUntilChanged() val messageHasBody = messageEditTextChanged .map { !ObjectUtils.isNull(it) && it.isPresent() } messageThreadEnvelope .map { it.messageThread() } .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .switchMap { client.markAsRead( it ) } .materialize() .compose(Transformers.ignoreValues()) .compose(bindToLifecycle()) .subscribe { successfullyMarkedAsRead.onNext(it) } val initialMessages = initialMessageThreadEnvelope .map { it.messages() } val newMessages = sentMessageThreadEnvelope .map { it.messages() } .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } // Concat distinct messages to initial message list. Return just the new messages if // initial list is null, i.e. a new message thread. val updatedMessages = initialMessages .compose( Transformers.takePairWhen( newMessages ) ) .map { val messagesList = it?.first val message = it?.second?.toList() messagesList?.let { initialMessages -> message?.let { ListUtils.concatDistinct( initialMessages, it ) } } ?: it.second } // Load the initial messages once, subsequently load newer messages if any. initialMessages .filter { ObjectUtils.isNotNull(it) } .take(1) .compose(bindToLifecycle()) .subscribe { v: List<Message>? -> messageList.onNext(v) } updatedMessages .compose(bindToLifecycle()) .subscribe { v: List<Message>? -> messageList.onNext(v) } project .map { it.creator().name() } .compose(bindToLifecycle()) .subscribe { v: String -> creatorNameTextViewText.onNext(v) } initialMessageThreadEnvelope .map { it.messages() } .filter { ObjectUtils.isNull(it) } .take(1) .compose(Transformers.ignoreValues()) .compose(bindToLifecycle()) .subscribe { messageEditTextShouldRequestFocus.onNext(it) } val backingAndProject = messagesData .switchMap { backingAndProjectFromData(it, client) } backingAndProject .filter { ObjectUtils.isNotNull(it) } .compose(bindToLifecycle()) .subscribe { this.backingAndProject.onNext(it) } backingAndProject .map { ObjectUtils.isNull(it) } .compose(bindToLifecycle()) .subscribe { backingInfoViewIsGone.onNext(it) } messageAccountTypeObservable .map { c: MessagePreviousScreenType -> c == MessagePreviousScreenType.BACKER_MODAL } .compose(bindToLifecycle()) .subscribe { v: Boolean -> viewPledgeButtonIsGone.onNext(v) } backButtonIsGone = viewPledgeButtonIsGone.map { it.negate() } closeButtonIsGone = backButtonIsGone.map { it.negate() } goBack = backOrCloseButtonClicked projectNameToolbarTextViewText = projectNameTextViewText scrollRecyclerViewToBottom = updatedMessages.compose(Transformers.ignoreValues()) sendMessageButtonIsEnabled = Observable.merge( messageHasBody, messageIsSending.map { it.negate() } ) setMessageEditText = messageSent.map { "" } toolbarIsExpanded = messageList .compose( Transformers.takePairWhen( messageEditTextIsFocused ) ) .map { PairUtils.second(it) } .map { it.negate() } messageNotification .compose(Transformers.errors()) .map { ErrorEnvelope.fromThrowable(it) } .map { it?.errorMessage() } .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } .compose(bindToLifecycle()) .subscribe { showMessageErrorToast.onNext(it) } project .map { it.name() } .compose(bindToLifecycle()) .subscribe { projectNameTextViewText.onNext(it) } messageThreadEnvelope .compose(Transformers.combineLatestPair(messagesData)) .compose(Transformers.takeWhen(viewPledgeButtonClicked)) .map { projectAndBacker( it ) } .compose( Transformers.combineLatestPair( backingAndProject.filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } ) ) .map { BackingWrapper( it.second.first, it.first.second, it.first.first ) } .compose(bindToLifecycle()) .subscribe { v: BackingWrapper -> startBackingActivity.onNext(v) } // Set only the initial padding once to counteract the appbar offset. recyclerViewInitialBottomPadding = appBarTotalScrollRange.take(1) // Take only the first instance in which the offset changes. recyclerViewDefaultBottomPadding = appBarOffset .filter { it.isNonZero() } .compose(Transformers.ignoreValues()) .take(1) } } }
apache-2.0
107a243d4b647573b1b82b3da8048a06
42.33737
122
0.585013
5.904998
false
false
false
false
jotomo/AndroidAPS
omnipod/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/ui/OmnipodOverviewFragment.kt
1
30707
package info.nightscout.androidaps.plugins.pump.omnipod.ui import android.content.Intent import android.graphics.Color import android.os.Bundle import android.os.Handler import android.os.Looper import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import dagger.android.support.DaggerFragment import info.nightscout.androidaps.Constants import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.events.EventPreferenceChange import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.plugins.pump.common.events.EventRileyLinkDeviceStatusChange import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData import info.nightscout.androidaps.plugins.pump.omnipod.OmnipodPumpPlugin import info.nightscout.androidaps.plugins.pump.omnipod.R import info.nightscout.androidaps.plugins.pump.omnipod.driver.definition.ActivationProgress import info.nightscout.androidaps.plugins.pump.omnipod.driver.definition.OmnipodConstants import info.nightscout.androidaps.plugins.pump.omnipod.driver.definition.PodProgressStatus import info.nightscout.androidaps.plugins.pump.omnipod.driver.manager.PodStateManager import info.nightscout.androidaps.plugins.pump.omnipod.driver.util.TimeUtil import info.nightscout.androidaps.plugins.pump.omnipod.event.EventOmnipodPumpValuesChanged import info.nightscout.androidaps.plugins.pump.omnipod.manager.AapsOmnipodManager import info.nightscout.androidaps.plugins.pump.omnipod.queue.command.CommandAcknowledgeAlerts import info.nightscout.androidaps.plugins.pump.omnipod.queue.command.CommandGetPodStatus import info.nightscout.androidaps.plugins.pump.omnipod.queue.command.CommandHandleTimeChange import info.nightscout.androidaps.plugins.pump.omnipod.queue.command.CommandResumeDelivery import info.nightscout.androidaps.plugins.pump.omnipod.queue.command.CommandSuspendDelivery import info.nightscout.androidaps.plugins.pump.omnipod.util.AapsOmnipodUtil import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodAlertUtil import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.queue.events.EventQueueChanged import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.ui.UIRunnable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.omnipod_overview.* import org.apache.commons.lang3.StringUtils import org.joda.time.DateTime import org.joda.time.Duration import java.util.* import javax.inject.Inject import kotlin.collections.ArrayList class OmnipodOverviewFragment : DaggerFragment() { companion object { private val REFRESH_INTERVAL_MILLIS = 15 * 1000L // 15 seconds private val PLACEHOLDER = "-" // 15 seconds } @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var omnipodPumpPlugin: OmnipodPumpPlugin @Inject lateinit var podStateManager: PodStateManager @Inject lateinit var sp: SP @Inject lateinit var omnipodUtil: AapsOmnipodUtil @Inject lateinit var omnipodAlertUtil: OmnipodAlertUtil @Inject lateinit var rileyLinkServiceData: RileyLinkServiceData @Inject lateinit var dateUtil: DateUtil @Inject lateinit var omnipodManager: AapsOmnipodManager @Inject lateinit var protectionCheck: ProtectionCheck private var disposables: CompositeDisposable = CompositeDisposable() private val loopHandler = Handler(Looper.getMainLooper()) private lateinit var refreshLoop: Runnable init { refreshLoop = Runnable { activity?.runOnUiThread { updateUi() } loopHandler.postDelayed(refreshLoop, REFRESH_INTERVAL_MILLIS) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.omnipod_overview, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) omnipod_overview_button_pod_management.setOnClickListener { if (omnipodPumpPlugin.rileyLinkService?.verifyConfiguration() == true) { activity?.let { activity -> context?.let { context -> protectionCheck.queryProtection( activity, ProtectionCheck.Protection.PREFERENCES, UIRunnable { startActivity(Intent(context, PodManagementActivity::class.java)) } ) } } } else { displayNotConfiguredDialog() } } omnipod_overview_button_resume_delivery.setOnClickListener { disablePodActionButtons() commandQueue.customCommand(CommandResumeDelivery(), DisplayResultDialogCallback(resourceHelper.gs(R.string.omnipod_error_failed_to_resume_delivery), true).messageOnSuccess(resourceHelper.gs(R.string.omnipod_confirmation_delivery_resumed))) } omnipod_overview_button_refresh_status.setOnClickListener { disablePodActionButtons() commandQueue.customCommand(CommandGetPodStatus(), DisplayResultDialogCallback(resourceHelper.gs(R.string.omnipod_error_failed_to_refresh_status), false)) } omnipod_overview_button_acknowledge_active_alerts.setOnClickListener { disablePodActionButtons() commandQueue.customCommand(CommandAcknowledgeAlerts(), DisplayResultDialogCallback(resourceHelper.gs(R.string.omnipod_error_failed_to_acknowledge_alerts), false) .messageOnSuccess(resourceHelper.gs(R.string.omnipod_confirmation_acknowledged_alerts)) .actionOnSuccess { rxBus.send(EventDismissNotification(Notification.OMNIPOD_POD_ALERTS)) }) } omnipod_overview_button_suspend_delivery.setOnClickListener { disablePodActionButtons() commandQueue.customCommand(CommandSuspendDelivery(), DisplayResultDialogCallback(resourceHelper.gs(R.string.omnipod_error_failed_to_suspend_delivery), true) .messageOnSuccess(resourceHelper.gs(R.string.omnipod_confirmation_suspended_delivery))) } omnipod_overview_button_set_time.setOnClickListener { disablePodActionButtons() commandQueue.customCommand(CommandHandleTimeChange(true), DisplayResultDialogCallback(resourceHelper.gs(R.string.omnipod_error_failed_to_set_time), true) .messageOnSuccess(resourceHelper.gs(R.string.omnipod_confirmation_time_on_pod_updated))) } } override fun onResume() { super.onResume() loopHandler.postDelayed(refreshLoop, REFRESH_INTERVAL_MILLIS) disposables += rxBus .toObservable(EventRileyLinkDeviceStatusChange::class.java) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ updateRileyLinkStatus() updatePodActionButtons() }, { fabricPrivacy.logException(it) }) disposables += rxBus .toObservable(EventOmnipodPumpValuesChanged::class.java) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ updateOmnipodStatus() updatePodActionButtons() }, { fabricPrivacy.logException(it) }) disposables += rxBus .toObservable(EventQueueChanged::class.java) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ updateQueueStatus() updatePodActionButtons() }, { fabricPrivacy.logException(it) }) disposables += rxBus .toObservable(EventPreferenceChange::class.java) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ updatePodActionButtons() }, { fabricPrivacy.logException(it) }) updateUi() } override fun onPause() { super.onPause() disposables.clear() loopHandler.removeCallbacks(refreshLoop) } private fun updateUi() { updateRileyLinkStatus() updateOmnipodStatus() updatePodActionButtons() updateQueueStatus() } @Synchronized private fun updateRileyLinkStatus() { val rileyLinkServiceState = rileyLinkServiceData.rileyLinkServiceState val resourceId = rileyLinkServiceState.resourceId val rileyLinkError = rileyLinkServiceData.rileyLinkError omnipod_overview_riley_link_status.text = when { rileyLinkServiceState == RileyLinkServiceState.NotStarted -> resourceHelper.gs(resourceId) rileyLinkServiceState.isConnecting -> "{fa-bluetooth-b spin} " + resourceHelper.gs(resourceId) rileyLinkServiceState.isError && rileyLinkError == null -> "{fa-bluetooth-b} " + resourceHelper.gs(resourceId) rileyLinkServiceState.isError && rileyLinkError != null -> "{fa-bluetooth-b} " + resourceHelper.gs(rileyLinkError.getResourceId(RileyLinkTargetDevice.Omnipod)) else -> "{fa-bluetooth-b} " + resourceHelper.gs(resourceId) } omnipod_overview_riley_link_status.setTextColor(if (rileyLinkServiceState.isError || rileyLinkError != null) Color.RED else Color.WHITE) } private fun updateOmnipodStatus() { updateLastConnection() updateLastBolus() updateTempBasal() updatePodStatus() val errors = ArrayList<String>() if (omnipodPumpPlugin.rileyLinkService != null) { val rileyLinkErrorDescription = omnipodPumpPlugin.rileyLinkService.errorDescription if (StringUtils.isNotEmpty(rileyLinkErrorDescription)) { errors.add(rileyLinkErrorDescription) } } if (!podStateManager.hasPodState() || !podStateManager.isPodInitialized) { omnipod_overview_pod_address.text = if (podStateManager.hasPodState()) { podStateManager.address.toString() } else { PLACEHOLDER } omnipod_overview_pod_lot.text = PLACEHOLDER omnipod_overview_pod_tid.text = PLACEHOLDER omnipod_overview_firmware_version.text = PLACEHOLDER omnipod_overview_time_on_pod.text = PLACEHOLDER omnipod_overview_pod_expiry_date.text = PLACEHOLDER omnipod_overview_pod_expiry_date.setTextColor(Color.WHITE) omnipod_overview_base_basal_rate.text = PLACEHOLDER omnipod_overview_total_delivered.text = PLACEHOLDER omnipod_overview_reservoir.text = PLACEHOLDER omnipod_overview_reservoir.setTextColor(Color.WHITE) omnipod_overview_pod_active_alerts.text = PLACEHOLDER } else { omnipod_overview_pod_address.text = podStateManager.address.toString() omnipod_overview_pod_lot.text = podStateManager.lot.toString() omnipod_overview_pod_tid.text = podStateManager.tid.toString() omnipod_overview_firmware_version.text = resourceHelper.gs(R.string.omnipod_firmware_version_value, podStateManager.pmVersion.toString(), podStateManager.piVersion.toString()) omnipod_overview_time_on_pod.text = readableZonedTime(podStateManager.time) omnipod_overview_time_on_pod.setTextColor(if (podStateManager.timeDeviatesMoreThan(OmnipodConstants.TIME_DEVIATION_THRESHOLD)) { Color.RED } else { Color.WHITE }) val expiresAt = podStateManager.expiresAt if (expiresAt == null) { omnipod_overview_pod_expiry_date.text = PLACEHOLDER omnipod_overview_pod_expiry_date.setTextColor(Color.WHITE) } else { omnipod_overview_pod_expiry_date.text = readableZonedTime(expiresAt) omnipod_overview_pod_expiry_date.setTextColor(if (DateTime.now().isAfter(expiresAt)) { Color.RED } else { Color.WHITE }) } if (podStateManager.isPodFaulted) { val faultEventCode = podStateManager.faultEventCode errors.add(resourceHelper.gs(R.string.omnipod_pod_status_pod_fault_description, faultEventCode.value, faultEventCode.name)) } // base basal rate omnipod_overview_base_basal_rate.text = if (podStateManager.isPodActivationCompleted) { resourceHelper.gs(R.string.pump_basebasalrate, omnipodPumpPlugin.model().determineCorrectBasalSize(podStateManager.basalSchedule.rateAt(TimeUtil.toDuration(DateTime.now())))) } else { PLACEHOLDER } // total delivered omnipod_overview_total_delivered.text = if (podStateManager.isPodActivationCompleted && podStateManager.totalInsulinDelivered != null) { resourceHelper.gs(R.string.omnipod_overview_total_delivered_value, podStateManager.totalInsulinDelivered - OmnipodConstants.POD_SETUP_UNITS) } else { PLACEHOLDER } // reservoir if (podStateManager.reservoirLevel == null) { omnipod_overview_reservoir.text = resourceHelper.gs(R.string.omnipod_overview_reservoir_value_over50) omnipod_overview_reservoir.setTextColor(Color.WHITE) } else { val lowReservoirThreshold = (omnipodAlertUtil.lowReservoirAlertUnits ?: OmnipodConstants.DEFAULT_MAX_RESERVOIR_ALERT_THRESHOLD).toDouble() omnipod_overview_reservoir.text = resourceHelper.gs(R.string.omnipod_overview_reservoir_value, podStateManager.reservoirLevel) omnipod_overview_reservoir.setTextColor(if (podStateManager.reservoirLevel < lowReservoirThreshold) { Color.RED } else { Color.WHITE }) } omnipod_overview_pod_active_alerts.text = if (podStateManager.hasActiveAlerts()) { TextUtils.join(System.lineSeparator(), omnipodUtil.getTranslatedActiveAlerts(podStateManager)) } else { PLACEHOLDER } } if (errors.size == 0) { omnipod_overview_errors.text = PLACEHOLDER omnipod_overview_errors.setTextColor(Color.WHITE) } else { omnipod_overview_errors.text = StringUtils.join(errors, System.lineSeparator()) omnipod_overview_errors.setTextColor(Color.RED) } } private fun updateLastConnection() { if (podStateManager.isPodInitialized && podStateManager.lastSuccessfulCommunication != null) { omnipod_overview_last_connection.text = readableDuration(podStateManager.lastSuccessfulCommunication) val lastConnectionColor = if (omnipodPumpPlugin.isUnreachableAlertTimeoutExceeded(getPumpUnreachableTimeout().millis)) { Color.RED } else { Color.WHITE } omnipod_overview_last_connection.setTextColor(lastConnectionColor) } else { omnipod_overview_last_connection.setTextColor(Color.WHITE) omnipod_overview_last_connection.text = if (podStateManager.hasPodState() && podStateManager.lastSuccessfulCommunication != null) { readableDuration(podStateManager.lastSuccessfulCommunication) } else { PLACEHOLDER } } } private fun updatePodStatus() { omnipod_overview_pod_status.text = if (!podStateManager.hasPodState()) { resourceHelper.gs(R.string.omnipod_pod_status_no_active_pod) } else if (!podStateManager.isPodActivationCompleted) { if (!podStateManager.isPodInitialized) { resourceHelper.gs(R.string.omnipod_pod_status_waiting_for_activation) } else { if (podStateManager.activationProgress.isBefore(ActivationProgress.PRIMING_COMPLETED)) { resourceHelper.gs(R.string.omnipod_pod_status_waiting_for_activation) } else { resourceHelper.gs(R.string.omnipod_pod_status_waiting_for_cannula_insertion) } } } else { if (podStateManager.podProgressStatus.isRunning) { var status = if (podStateManager.isSuspended) { resourceHelper.gs(R.string.omnipod_pod_status_suspended) } else { resourceHelper.gs(R.string.omnipod_pod_status_running) } if (!podStateManager.isBasalCertain) { status += " (" + resourceHelper.gs(R.string.omnipod_uncertain) + ")" } status } else if (podStateManager.podProgressStatus == PodProgressStatus.FAULT_EVENT_OCCURRED) { resourceHelper.gs(R.string.omnipod_pod_status_pod_fault) } else if (podStateManager.podProgressStatus == PodProgressStatus.INACTIVE) { resourceHelper.gs(R.string.omnipod_pod_status_inactive) } else { podStateManager.podProgressStatus.toString() } } val podStatusColor = if (!podStateManager.isPodActivationCompleted || podStateManager.isPodDead || podStateManager.isSuspended || (podStateManager.isPodRunning && !podStateManager.isBasalCertain)) { Color.RED } else { Color.WHITE } omnipod_overview_pod_status.setTextColor(podStatusColor) } private fun updateLastBolus() { if (podStateManager.isPodActivationCompleted && podStateManager.hasLastBolus()) { var text = resourceHelper.gs(R.string.omnipod_overview_last_bolus_value, omnipodPumpPlugin.model().determineCorrectBolusSize(podStateManager.lastBolusAmount), resourceHelper.gs(R.string.insulin_unit_shortname), readableDuration(podStateManager.lastBolusStartTime)) val textColor: Int if (podStateManager.isLastBolusCertain) { textColor = Color.WHITE } else { textColor = Color.RED text += " (" + resourceHelper.gs(R.string.omnipod_uncertain) + ")" } omnipod_overview_last_bolus.text = text omnipod_overview_last_bolus.setTextColor(textColor) } else { omnipod_overview_last_bolus.text = PLACEHOLDER omnipod_overview_last_bolus.setTextColor(Color.WHITE) } } private fun updateTempBasal() { if (podStateManager.isPodActivationCompleted && podStateManager.isTempBasalRunning) { if (!podStateManager.hasTempBasal()) { omnipod_overview_temp_basal.text = "???" omnipod_overview_temp_basal.setTextColor(Color.RED) } else { val now = DateTime.now() val startTime = podStateManager.tempBasalStartTime val amount = podStateManager.tempBasalAmount val duration = podStateManager.tempBasalDuration val minutesRunning = Duration(startTime, now).standardMinutes var text: String val textColor: Int text = resourceHelper.gs(R.string.omnipod_overview_temp_basal_value, amount, dateUtil.timeString(startTime.millis), minutesRunning, duration.standardMinutes) if (podStateManager.isTempBasalCertain) { textColor = Color.WHITE } else { textColor = Color.RED text += " (" + resourceHelper.gs(R.string.omnipod_uncertain) + ")" } omnipod_overview_temp_basal.text = text omnipod_overview_temp_basal.setTextColor(textColor) } } else { var text = PLACEHOLDER val textColor: Int if (!podStateManager.isPodActivationCompleted || podStateManager.isTempBasalCertain) { textColor = Color.WHITE } else { textColor = Color.RED text += " (" + resourceHelper.gs(R.string.omnipod_uncertain) + ")" } omnipod_overview_temp_basal.text = text omnipod_overview_temp_basal.setTextColor(textColor) } } private fun updateQueueStatus() { if (isQueueEmpty()) { omnipod_overview_queue.visibility = View.GONE } else { omnipod_overview_queue.visibility = View.VISIBLE omnipod_overview_queue.text = commandQueue.spannedStatus().toString() } } private fun updatePodActionButtons() { updateRefreshStatusButton() updateResumeDeliveryButton() updateAcknowledgeAlertsButton() updateSuspendDeliveryButton() updateSetTimeButton() } private fun disablePodActionButtons() { omnipod_overview_button_acknowledge_active_alerts.isEnabled = false omnipod_overview_button_resume_delivery.isEnabled = false omnipod_overview_button_suspend_delivery.isEnabled = false omnipod_overview_button_set_time.isEnabled = false omnipod_overview_button_refresh_status.isEnabled = false } private fun updateRefreshStatusButton() { omnipod_overview_button_refresh_status.isEnabled = podStateManager.isPodInitialized && podStateManager.activationProgress.isAtLeast(ActivationProgress.PAIRING_COMPLETED) && rileyLinkServiceData.rileyLinkServiceState.isReady && isQueueEmpty() } private fun updateResumeDeliveryButton() { if (podStateManager.isPodRunning && (podStateManager.isSuspended || commandQueue.isCustomCommandInQueue(CommandResumeDelivery::class.java))) { omnipod_overview_button_resume_delivery.visibility = View.VISIBLE omnipod_overview_button_resume_delivery.isEnabled = rileyLinkServiceData.rileyLinkServiceState.isReady && isQueueEmpty() } else { omnipod_overview_button_resume_delivery.visibility = View.GONE } } private fun updateAcknowledgeAlertsButton() { if (!omnipodManager.isAutomaticallyAcknowledgeAlertsEnabled && podStateManager.isPodRunning && (podStateManager.hasActiveAlerts() || commandQueue.isCustomCommandInQueue(CommandAcknowledgeAlerts::class.java))) { omnipod_overview_button_acknowledge_active_alerts.visibility = View.VISIBLE omnipod_overview_button_acknowledge_active_alerts.isEnabled = rileyLinkServiceData.rileyLinkServiceState.isReady && isQueueEmpty() } else { omnipod_overview_button_acknowledge_active_alerts.visibility = View.GONE } } private fun updateSuspendDeliveryButton() { // If the Pod is currently suspended, we show the Resume delivery button instead. if (omnipodManager.isSuspendDeliveryButtonEnabled && podStateManager.isPodRunning && (!podStateManager.isSuspended || commandQueue.isCustomCommandInQueue(CommandSuspendDelivery::class.java))) { omnipod_overview_button_suspend_delivery.visibility = View.VISIBLE omnipod_overview_button_suspend_delivery.isEnabled = podStateManager.isPodRunning && !podStateManager.isSuspended && rileyLinkServiceData.rileyLinkServiceState.isReady && isQueueEmpty() } else { omnipod_overview_button_suspend_delivery.visibility = View.GONE } } private fun updateSetTimeButton() { if (podStateManager.isPodRunning && (podStateManager.timeDeviatesMoreThan(Duration.standardMinutes(5)) || commandQueue.isCustomCommandInQueue(CommandHandleTimeChange::class.java))) { omnipod_overview_button_set_time.visibility = View.VISIBLE omnipod_overview_button_set_time.isEnabled = !podStateManager.isSuspended && rileyLinkServiceData.rileyLinkServiceState.isReady && isQueueEmpty() } else { omnipod_overview_button_set_time.visibility = View.GONE } } private fun displayNotConfiguredDialog() { context?.let { UIRunnable { OKDialog.show(it, resourceHelper.gs(R.string.omnipod_warning), resourceHelper.gs(R.string.omnipod_error_operation_not_possible_no_configuration), null) }.run() } } private fun displayErrorDialog(title: String, message: String, withSound: Boolean) { context?.let { val i = Intent(it, ErrorHelperActivity::class.java) i.putExtra("soundid", if (withSound) R.raw.boluserror else 0) i.putExtra("status", message) i.putExtra("title", title) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) it.startActivity(i) } } private fun displayOkDialog(title: String, message: String) { context?.let { UIRunnable { OKDialog.show(it, title, message, null) }.run() } } private fun readableZonedTime(time: DateTime): String { val timeAsJavaData = time.toLocalDateTime().toDate() val timeZone = podStateManager.timeZone.toTimeZone() if (timeZone == TimeZone.getDefault()) { return dateUtil.dateAndTimeString(timeAsJavaData) } val isDaylightTime = timeZone.inDaylightTime(timeAsJavaData) val locale = resources.configuration.locales.get(0) val timeZoneDisplayName = timeZone.getDisplayName(isDaylightTime, TimeZone.SHORT, locale) + " " + timeZone.getDisplayName(isDaylightTime, TimeZone.LONG, locale) return resourceHelper.gs(R.string.omnipod_time_with_timezone, dateUtil.dateAndTimeString(timeAsJavaData), timeZoneDisplayName) } private fun readableDuration(dateTime: DateTime): String { val duration = Duration(dateTime, DateTime.now()) val hours = duration.standardHours.toInt() val minutes = duration.standardMinutes.toInt() val seconds = duration.standardSeconds.toInt() when { seconds < 10 -> { return resourceHelper.gs(R.string.omnipod_moments_ago) } seconds < 60 -> { return resourceHelper.gs(R.string.omnipod_less_than_a_minute_ago) } seconds < 60 * 60 -> { // < 1 hour return resourceHelper.gs(R.string.omnipod_time_ago, resourceHelper.gq(R.plurals.omnipod_minutes, minutes, minutes)) } seconds < 24 * 60 * 60 -> { // < 1 day val minutesLeft = minutes % 60 if (minutesLeft > 0) return resourceHelper.gs(R.string.omnipod_time_ago, resourceHelper.gs(R.string.omnipod_composite_time, resourceHelper.gq(R.plurals.omnipod_hours, hours, hours), resourceHelper.gq(R.plurals.omnipod_minutes, minutesLeft, minutesLeft))) return resourceHelper.gs(R.string.omnipod_time_ago, resourceHelper.gq(R.plurals.omnipod_hours, hours, hours)) } else -> { val days = hours / 24 val hoursLeft = hours % 24 if (hoursLeft > 0) return resourceHelper.gs(R.string.omnipod_time_ago, resourceHelper.gs(R.string.omnipod_composite_time, resourceHelper.gq(R.plurals.omnipod_days, days, days), resourceHelper.gq(R.plurals.omnipod_hours, hoursLeft, hoursLeft))) return resourceHelper.gs(R.string.omnipod_time_ago, resourceHelper.gq(R.plurals.omnipod_days, days, days)) } } } private fun isQueueEmpty(): Boolean { return commandQueue.size() == 0 && commandQueue.performing() == null } // FIXME ideally we should just have access to LocalAlertUtils here private fun getPumpUnreachableTimeout(): Duration { return Duration.standardMinutes(sp.getInt(R.string.key_pump_unreachable_threshold_minutes, Constants.DEFAULT_PUMP_UNREACHABLE_THRESHOLD_MINUTES).toLong()) } inner class DisplayResultDialogCallback(private val errorMessagePrefix: String, private val withSoundOnError: Boolean) : Callback() { private var messageOnSuccess: String? = null private var actionOnSuccess: Runnable? = null override fun run() { if (result.success) { val messageOnSuccess = this.messageOnSuccess if (messageOnSuccess != null) { displayOkDialog(resourceHelper.gs(R.string.omnipod_confirmation), messageOnSuccess) } actionOnSuccess?.run() } else { displayErrorDialog(resourceHelper.gs(R.string.omnipod_warning), resourceHelper.gs(R.string.omnipod_two_strings_concatenated_by_colon, errorMessagePrefix, result.comment), withSoundOnError) } } fun messageOnSuccess(message: String): DisplayResultDialogCallback { messageOnSuccess = message return this } fun actionOnSuccess(action: Runnable): DisplayResultDialogCallback { actionOnSuccess = action return this } } }
agpl-3.0
65ed3a268872e04c8d719446afaeb23f
47.587025
276
0.668707
5.076376
false
false
false
false
QuixomTech/DeviceInfo
app/src/main/java/com/quixom/apps/deviceinfo/fragments/CPUFragment.kt
1
7545
package com.quixom.apps.deviceinfo.fragments import android.annotation.SuppressLint import android.app.ActivityManager import android.content.ContentValues.TAG import android.content.Context import android.os.Build import android.os.Bundle import android.os.Handler import android.support.annotation.RequiresApi import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.util.Log import android.view.* import android.widget.ImageView import android.widget.TextView import com.github.lzyzsd.circleprogress.ArcProgress import com.quixom.apps.deviceinfo.R import com.quixom.apps.deviceinfo.adapters.CPUAdapter import com.quixom.apps.deviceinfo.models.FeaturesHW import com.quixom.apps.deviceinfo.utilities.Methods import java.io.File import java.io.IOException import java.io.InputStream import java.text.DecimalFormat import java.util.* class CPUFragment : BaseFragment() { var ivMenu: ImageView? = null var ivBack: ImageView? = null var tvTitle: TextView? = null var arcCpu: ArcProgress? = null var arcRAM: ArcProgress? = null var tvSystemAppsMemory: TextView? = null var tvAvailableRAM: TextView? = null var tvTotalRAMSpace: TextView? = null private var rvCpuFeatureList: RecyclerView? = null var activityManager: ActivityManager? = null var memoryInfo: ActivityManager.MemoryInfo? = null var inputStream: InputStream? = null var byteArray = ByteArray(1024) var cpuData: String = "" override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val contextThemeWrapper = ContextThemeWrapper(activity, R.style.ProcessorTheme) val localInflater = inflater.cloneInContext(contextThemeWrapper) val view = localInflater.inflate(R.layout.fragment_cpu, container, false) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val window = activity!!.window window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) window.statusBarColor = resources.getColor(R.color.dark_violet) window.navigationBarColor = resources.getColor(R.color.dark_violet) } /* val intent = activity!!.intent activity!!.finish() startActivity(intent)*/ // val view = inflater.inflate(R.layout.fragment_cpu, container, false) ivMenu = view.findViewById(R.id.iv_menu) ivBack = view.findViewById(R.id.iv_back) tvTitle = view.findViewById(R.id.tv_title) arcCpu = view.findViewById(R.id.arc_cpu) arcRAM = view.findViewById(R.id.arc_ram) tvSystemAppsMemory = view.findViewById(R.id.tv_system_apps_memory) tvAvailableRAM = view.findViewById(R.id.tv_available_ram) tvTotalRAMSpace = view.findViewById(R.id.tv_total_ram_space) rvCpuFeatureList = view.findViewById(R.id.rv_cpu_feature_list) return view } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) initToolbar() rvCpuFeatureList?.layoutManager = LinearLayoutManager(mActivity) rvCpuFeatureList?.hasFixedSize() getCpuInfoMap() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { getMemoryInfo() } // Init val handler = Handler() val runnable = object : Runnable { override fun run() { val totalRamValue = totalRamMemorySize() val freeRamValue = freeRamMemorySize() val usedRamValue = totalRamValue - freeRamValue arcRAM?.progress = Methods.calculatePercentage(usedRamValue.toDouble(), totalRamValue.toDouble()) handler.postDelayed(this, 500) } } handler.postDelayed(runnable, 500) } override fun onHiddenChanged(hidden: Boolean) { super.onHiddenChanged(hidden) if (!hidden && isAdded) { initToolbar() } } private fun initToolbar() { ivMenu?.visibility = View.VISIBLE ivBack?.visibility = View.GONE tvTitle?.text = mResources.getString(R.string.processor_label) ivMenu?.setOnClickListener { mActivity.openDrawer() } } @SuppressLint("SetTextI18n") @RequiresApi(Build.VERSION_CODES.JELLY_BEAN) private fun getMemoryInfo() { activityManager = mActivity.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager? memoryInfo = ActivityManager.MemoryInfo() activityManager?.getMemoryInfo(memoryInfo) val freeMemory = memoryInfo?.availMem val totalMemory = memoryInfo?.totalMem val usedMemory = freeMemory?.let { totalMemory?.minus(it) } tvSystemAppsMemory?.text = mResources.getString(R.string.system_and_apps) + ": ".plus(formatSize(usedMemory!!)) tvAvailableRAM?.text = mResources.getString(R.string.available_ram) + ": ".plus(formatSize(freeMemory)) tvTotalRAMSpace?.text = mResources.getString(R.string.total_ram_space) + ": ".plus(formatSize(totalMemory!!)) } private fun freeRamMemorySize(): Long { val mi = ActivityManager.MemoryInfo() val activityManager = mActivity.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager activityManager.getMemoryInfo(mi) return mi.availMem } private fun totalRamMemorySize(): Long { val mi = ActivityManager.MemoryInfo() val activityManager = mActivity.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager activityManager.getMemoryInfo(mi) return mi.totalMem } private fun formatSize(size: Long): String { if (size <= 0) return "0" val units = arrayOf("B", "KB", "MB", "GB", "TB") val digitGroups = (Math.log10(size.toDouble()) / Math.log10(1024.0)).toInt() return DecimalFormat("#,##0.#").format(size / Math.pow(1024.0, digitGroups.toDouble())) + " " + units[digitGroups] } private fun getCpuInfoMap() { val lists = ArrayList<FeaturesHW>() try { val s = Scanner(File("/proc/cpuinfo")) while (s.hasNextLine()) { val vals = s.nextLine().split(": ") if (vals.size > 1) lists.add(FeaturesHW(vals[0].trim({ it <= ' ' }), vals[1].trim({ it <= ' ' }))) } } catch (e: Exception) { Log.e("getCpuInfoMap", Log.getStackTraceString(e)) } val adapter = CPUAdapter(lists, mActivity) //now adding the adapter to RecyclerView rvCpuFeatureList?.adapter = adapter } fun getCpuInfo() { try { val proc = Runtime.getRuntime().exec("cat /proc/cpuinfo") val cpuDetails = proc.inputStream println("cpuDetails = " + cpuDetails) } catch (e: IOException) { Log.e(TAG, "------ getCpuInfo " + e.printStackTrace()) } } private fun getCPUInformation() { /* try { val proc = Runtime.getRuntime().exec("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq") inputStream = proc?.inputStream while (inputStream?.read(byteArray) != -1) { cpuData += String(byteArray) println("cpuData###### ==" + cpuData) } inputStream!!.close() } catch (e: Exception) { println(e.printStackTrace()) }*/ } }
apache-2.0
fb656e23800c4eeac90b779497f0613e
35.985294
122
0.65222
4.42522
false
false
false
false
fabmax/kool
kool-demo/src/commonMain/kotlin/de/fabmax/kool/demo/uidemo/LauncherWindow.kt
1
3633
package de.fabmax.kool.demo.uidemo import de.fabmax.kool.modules.ui2.* import kotlin.reflect.KClass class LauncherWindow(val uiDemo: UiDemo) : UiDemo.DemoWindow { private val windowState = WindowState().apply { setWindowSize(Dp(250f), FitContent) } override val windowSurface = Window(windowState, name = "Window Launcher") { surface.sizes = uiDemo.selectedUiSize.use() surface.colors = uiDemo.selectedColors.use() val isMinimizedToTitle = weakRememberState(false) modifier .isMinimizedToTitle(isMinimizedToTitle.use()) .isResizable(false, false) TitleBar( onMinimizeAction = if (!isDocked && !isMinimizedToTitle.use()) { { isMinimizedToTitle.set(true) } } else null, onMaximizeAction = if (!isDocked && isMinimizedToTitle.use()) { { isMinimizedToTitle.set(false) } } else null ) if (!isMinimizedToTitle.value) { WindowContent() } } override val windowScope = windowSurface.windowScope!! private fun UiScope.WindowContent() = Column(Grow.Std) { val allowMultiInstances = weakRememberState(false) Button("UI Basics") { launcherButtonStyle("Example window with a few basic UI components") modifier.onClick { launchOrBringToTop(allowMultiInstances.use(), BasicUiWindow::class) { BasicUiWindow(uiDemo) } } } Button("Text Style") { launcherButtonStyle("Signed-distance-field font rendering showcase") modifier.onClick { launchOrBringToTop(allowMultiInstances.use(), TextStyleWindow::class) { TextStyleWindow(uiDemo) } } } Button("Text Area") { launcherButtonStyle("Editable text area with many different text styles") modifier.onClick { launchOrBringToTop(allowMultiInstances.use(), TextAreaWindow::class) { TextAreaWindow(uiDemo) } } } Button("Conway's Game of Life") { launcherButtonStyle("Game of Life simulation / toggle-button benchmark") modifier.onClick { launchOrBringToTop(allowMultiInstances.use(), GameOfLifeWindow::class) { GameOfLifeWindow(uiDemo) } } } Button("Theme Editor") { launcherButtonStyle("UI color theme editor") modifier.onClick { launchOrBringToTop(false, ThemeEditorWindow::class) { ThemeEditorWindow(uiDemo) } } } Row(Grow.Std) { modifier .margin(sizes.largeGap) Text("Multiple instances") { modifier .width(Grow.Std) .alignY(AlignmentY.Center) .onClick { allowMultiInstances.toggle() } } Switch(allowMultiInstances.use()) { modifier.onToggle { allowMultiInstances.set(it) } } } } private fun <T: UiDemo.DemoWindow> launchOrBringToTop(multiAllowed: Boolean, windowClass: KClass<T>, factory: () -> T) { if (!multiAllowed) { val existing = uiDemo.demoWindows.find { it::class == windowClass } if (existing != null) { existing.windowSurface.bringToTop() return } } uiDemo.spawnWindow(factory()) } private fun ButtonScope.launcherButtonStyle(tooltip: String) { modifier .width(Grow.Std) .margin(sizes.largeGap) .padding(vertical = sizes.gap) Tooltip(tooltip) } }
apache-2.0
709dd7d72631da31e08281d5f8f7c69b
36.463918
124
0.593999
4.587121
false
false
false
false
michaelkourlas/voipms-sms-client
voipms-sms/src/main/kotlin/net/kourlas/voipms_sms/preferences/fragments/DidPreferencesFragment.kt
1
8645
/* * VoIP.ms SMS * Copyright (C) 2017-2021 Michael Kourlas * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.kourlas.voipms_sms.preferences.fragments import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Bundle import android.widget.CompoundButton import androidx.appcompat.widget.SwitchCompat import androidx.lifecycle.lifecycleScope import androidx.preference.Preference import androidx.preference.SwitchPreference import com.takisoft.preferencex.PreferenceFragmentCompat import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import net.kourlas.voipms_sms.R import net.kourlas.voipms_sms.database.Database import net.kourlas.voipms_sms.preferences.* import net.kourlas.voipms_sms.utils.* class DidPreferencesFragment : PreferenceFragmentCompat(), CompoundButton.OnCheckedChangeListener { // Did private lateinit var did: String // Broadcast receivers private val pushNotificationsRegistrationCompleteReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { activity?.let { activity -> // Show error if one occurred intent?.getStringArrayListExtra( getString( R.string .push_notifications_reg_complete_failed_dids ) ) ?.let { if (it.isNotEmpty()) { // Some DIDs failed registration showSnackbar( activity, R.id.coordinator_layout, getString( R.string.push_notifications_fail_register ) ) } } ?: run { // Unknown error showSnackbar( activity, R.id.coordinator_layout, getString(R.string.push_notifications_fail_unknown) ) // Regardless of whether an error occurred, mark setup // as complete setSetupCompletedForVersion(activity, 134) } } } } override fun onCheckedChanged( buttonView: CompoundButton?, isChecked: Boolean ) { activity?.let { if (!::did.isInitialized) { return } // When enabled switch is checked or unchecked, enable or // disable and check or uncheck the additional switches as well val dids = if (isChecked) { getDids(it).plus(did) } else { getDids(it).minus(did) } setDids(it, dids) if (dids.isNotEmpty()) { // Re-register for push notifications when DIDs change enablePushNotifications( it.applicationContext, activityToShowError = it ) } lifecycleScope.launch(Dispatchers.Default) { replaceIndex(it) } updatePreferences() } } override fun onCreatePreferencesFix( savedInstanceState: Bundle?, rootKey: String? ) { activity?.let { // Set DID did = arguments?.getString( getString( R.string.preferences_did_fragment_argument_did ) ) ?: run { abortActivity(it, Exception("Missing DID argument")) return } // Add preferences addPreferencesFromResource(R.xml.preferences_did) // Set keys and update checked status for each preference setupPreferences() updatePreferences() // Add listener for enabled switch val enabledSwitch = it.findViewById<SwitchCompat>( R.id.enabled_switch ) enabledSwitch.setOnCheckedChangeListener(this) } } override fun onResume() { super.onResume() activity?.let { // Set DID did = arguments?.getString( getString( R.string.preferences_did_fragment_argument_did ) ) ?: run { abortActivity(it, Exception("Missing DID argument")) return } // Register dynamic receivers for this fragment it.registerReceiver( pushNotificationsRegistrationCompleteReceiver, IntentFilter( getString( R.string.push_notifications_reg_complete_action ) ) ) // Update checked status for each preference updatePreferences() } } override fun onPause() { super.onPause() activity?.let { // Unregister dynamic receivers for this fragment safeUnregisterReceiver( it, pushNotificationsRegistrationCompleteReceiver ) } } /** * Set the keys for each preference. */ private fun setupPreferences() { val showInConversationsViewPreference = preferenceScreen.getPreference(0) as SwitchPreference showInConversationsViewPreference.key = getString( R.string.preferences_did_show_in_conversations_view_key, did ) val retrieveMessagesPreference = preferenceScreen.getPreference(1) as SwitchPreference retrieveMessagesPreference.key = getString( R.string.preferences_did_retrieve_messages_key, did ) val showNotificationsPreference = preferenceScreen.getPreference(2) as SwitchPreference showNotificationsPreference.key = getString( R.string.preferences_did_show_notifications_key, did ) showNotificationsPreference.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, _ -> context?.let { lifecycleScope.launch(Dispatchers.Default) { Database.getInstance(it).updateShortcuts() replaceIndex(it) } } true } } /** * Update checked status for each preference. */ private fun updatePreferences() { activity?.let { val enabledSwitch = it.findViewById<SwitchCompat>( R.id.enabled_switch ) enabledSwitch.isChecked = did in getDids(it) val showInConversationsViewPreference = preferenceScreen.getPreference(0) as SwitchPreference showInConversationsViewPreference.isEnabled = enabledSwitch.isChecked showInConversationsViewPreference.isChecked = getDidShowInConversationsView(it, did) val retrieveMessagesPreference = preferenceScreen.getPreference(1) as SwitchPreference retrieveMessagesPreference.isEnabled = enabledSwitch.isChecked retrieveMessagesPreference.isChecked = getDidRetrieveMessages(it, did) val showNotificationsPreference = preferenceScreen.getPreference(2) as SwitchPreference showNotificationsPreference.isEnabled = enabledSwitch.isChecked showNotificationsPreference.isChecked = getDidShowNotifications( it, did ) } } }
apache-2.0
df0dd20fd90f15e30f5c98764ed33336
33.035433
81
0.553036
6.075193
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/cutPaste/MoveDeclarationsCopyPasteProcessor.kt
1
4661
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.cutPaste import com.intellij.codeInsight.editorActions.CopyPastePostProcessor import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.ControlFlowException import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.util.Ref import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiComment import com.intellij.psi.PsiFile import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.util.PsiModificationTracker import org.jetbrains.kotlin.psi.KtClassBody import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.KtObjectDeclaration import org.jetbrains.kotlin.psi.psiUtil.elementsInRange import java.awt.datatransfer.Transferable class MoveDeclarationsCopyPasteProcessor : CopyPastePostProcessor<MoveDeclarationsTransferableData>() { companion object { private val LOG = Logger.getInstance(MoveDeclarationsCopyPasteProcessor::class.java) fun rangeToDeclarations(file: KtFile, startOffset: Int, endOffset: Int): List<KtNamedDeclaration> { val elementsInRange = file.elementsInRange(TextRange(startOffset, endOffset)) val meaningfulElements = elementsInRange.filterNot { it is PsiWhiteSpace || it is PsiComment } if (meaningfulElements.isEmpty()) return emptyList() if (!meaningfulElements.all { it is KtNamedDeclaration }) return emptyList() @Suppress("UNCHECKED_CAST") return meaningfulElements as List<KtNamedDeclaration> } } override fun collectTransferableData( file: PsiFile, editor: Editor, startOffsets: IntArray, endOffsets: IntArray ): List<MoveDeclarationsTransferableData> { if (DumbService.isDumb(file.project)) return emptyList() if (file !is KtFile) return emptyList() if (startOffsets.size != 1) return emptyList() val declarations = rangeToDeclarations(file, startOffsets[0], endOffsets[0]) if (declarations.isEmpty()) return emptyList() val parent = declarations.asSequence().map { it.parent }.distinct().singleOrNull() ?: return emptyList() val sourceObjectFqName = when (parent) { is KtFile -> null is KtClassBody -> (parent.parent as? KtObjectDeclaration)?.fqName?.asString() ?: return emptyList() else -> return emptyList() } if (declarations.any { it.name == null }) return emptyList() val imports = file.importDirectives.map { it.text } return listOf( MoveDeclarationsTransferableData( file.virtualFile.url, sourceObjectFqName, declarations.map { it.text }, imports ) ) } override fun extractTransferableData(content: Transferable): List<MoveDeclarationsTransferableData> { try { if (content.isDataFlavorSupported(MoveDeclarationsTransferableData.DATA_FLAVOR)) { return listOf(content.getTransferData(MoveDeclarationsTransferableData.DATA_FLAVOR) as MoveDeclarationsTransferableData) } } catch (e: Throwable) { if (e is ControlFlowException) throw e LOG.error(e) } return emptyList() } override fun processTransferableData( project: Project, editor: Editor, bounds: RangeMarker, caretOffset: Int, indented: Ref<in Boolean>, values: List<MoveDeclarationsTransferableData> ) { val data = values.single() fun putCookie() { if (bounds.isValid) { val cookie = MoveDeclarationsEditorCookie(data, bounds, PsiModificationTracker.SERVICE.getInstance(project).modificationCount) editor.putUserData(MoveDeclarationsEditorCookie.KEY, cookie) } } if (ApplicationManager.getApplication().isUnitTestMode) { putCookie() } else { // in real application we put cookie later to allow all other paste handlers do their work (because modificationCount will change) ApplicationManager.getApplication().invokeLater(::putCookie) } } }
apache-2.0
25a9dd063071493295df8bd16f108f7b
40.247788
158
0.693199
5.13892
false
false
false
false
jwren/intellij-community
platform/built-in-server/src/org/jetbrains/ide/ToolboxUpdateActions.kt
6
3484
// 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.ide import com.intellij.ide.actions.SettingsEntryPointAction import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.util.Disposer import com.intellij.util.Alarm import com.intellij.util.Consumer import com.intellij.util.messages.Topic import com.intellij.util.ui.update.MergingUpdateQueue import com.intellij.util.ui.update.Update import org.jetbrains.annotations.Nls import java.util.* @Service(Service.Level.APP) class ToolboxSettingsActionRegistry : Disposable { private val readActions = Collections.synchronizedSet(HashSet<String>()) private val pendingActions = Collections.synchronizedList(LinkedList<ToolboxUpdateAction>()) private val alarm = MergingUpdateQueue("toolbox-updates", 500, true, null, this, null, Alarm.ThreadToUse.SWING_THREAD).usePassThroughInUnitTestMode() override fun dispose() = Unit fun isNewAction(actionId: String) = actionId !in readActions fun markAsRead(actionId: String) { readActions.add(actionId) } fun scheduleUpdate() { alarm.queue(object: Update(this){ override fun run() { SettingsEntryPointAction.updateState() } }) } internal fun registerUpdateAction(action: ToolboxUpdateAction) { action.registry = this val dispose = Disposable { pendingActions.remove(action) scheduleUpdate() } pendingActions += action ApplicationManager.getApplication().messageBus.syncPublisher(UpdateActionsListener.TOPIC).actionReceived(action) if (!Disposer.tryRegister(action.lifetime, dispose)) { Disposer.dispose(dispose) return } scheduleUpdate() } fun getActions() : List<SettingsEntryPointAction.UpdateAction> = ArrayList(pendingActions).sortedBy { it.actionId } } class ToolboxSettingsActionRegistryActionProvider : SettingsEntryPointAction.ActionProvider { override fun getUpdateActions(context: DataContext) = service<ToolboxSettingsActionRegistry>().getActions() } internal class ToolboxUpdateAction( val actionId: String, val lifetime: Disposable, text: @Nls String, description: @Nls String, val actionHandler: Consumer<AnActionEvent>, val restartRequired: Boolean ) : SettingsEntryPointAction.UpdateAction(text) { lateinit var registry : ToolboxSettingsActionRegistry init { templatePresentation.description = description } override fun isIdeUpdate() = true override fun isRestartRequired(): Boolean { return restartRequired } override fun isNewAction(): Boolean { return registry.isNewAction(actionId) } override fun markAsRead() { registry.markAsRead(actionId) } override fun actionPerformed(e: AnActionEvent) { actionHandler.consume(e) } override fun update(e: AnActionEvent) { super.update(e) if (Disposer.isDisposed(lifetime)) { e.presentation.isEnabledAndVisible = false } } } interface UpdateActionsListener: EventListener { companion object { val TOPIC = Topic(UpdateActionsListener::class.java) } fun actionReceived(action: SettingsEntryPointAction.UpdateAction) }
apache-2.0
5d8b2b68879d214ed1a7a1a19d8d96a8
29.304348
158
0.769805
4.61457
false
false
false
false
jwren/intellij-community
platform/configuration-store-impl/src/statistic/eventLog/FeatureUsageSettingsCustomRules.kt
1
1954
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.configurationStore.statistic.eventLog import com.intellij.internal.statistic.eventLog.validator.ValidationResultType import com.intellij.internal.statistic.eventLog.validator.ValidationResultType.ACCEPTED import com.intellij.internal.statistic.eventLog.validator.ValidationResultType.REJECTED import com.intellij.internal.statistic.eventLog.validator.rules.EventContext import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule class SettingsComponentNameValidator : CustomValidationRule() { override fun getRuleId(): String = "component_name" override fun acceptRuleId(ruleId: String?): Boolean { return getRuleId() == ruleId || "option_name" == ruleId } override fun doValidate(data: String, context: EventContext): ValidationResultType { if (isComponentName(data, context)) { return if (isComponentNameWhitelisted(data)) ACCEPTED else REJECTED } return if (isComponentOptionNameWhitelisted(data)) ACCEPTED else REJECTED } private fun isComponentName(data: String, context: EventContext): Boolean { @Suppress("HardCodedStringLiteral") return context.eventData.containsKey("component") && data == context.eventData["component"] } } class SettingsValueValidator : CustomValidationRule() { override fun getRuleId(): String = "setting_value" override fun doValidate(data: String, context: EventContext): ValidationResultType { @Suppress("HardCodedStringLiteral") val componentName = context.eventData["component"] as? String ?: return REJECTED val optionName = context.eventData["name"] as? String ?: return REJECTED if (!isComponentNameWhitelisted(componentName) || !isComponentOptionNameWhitelisted(optionName)) return REJECTED return acceptWhenReportedByJetBrainsPlugin(context) } }
apache-2.0
eef2f3f6281838ea257a12b6ee2ea03e
47.875
140
0.788639
4.897243
false
false
false
false
androidx/androidx
camera/camera-camera2-pipe-integration/src/main/java/androidx/camera/camera2/pipe/integration/compat/EvCompCompat.kt
3
6263
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java package androidx.camera.camera2.pipe.integration.compat import android.hardware.camera2.CameraCharacteristics.CONTROL_AE_COMPENSATION_RANGE import android.hardware.camera2.CameraCharacteristics.CONTROL_AE_COMPENSATION_STEP import android.hardware.camera2.CaptureRequest.CONTROL_AE_EXPOSURE_COMPENSATION import android.hardware.camera2.CaptureResult import android.util.Range import android.util.Rational import androidx.annotation.RequiresApi import androidx.camera.camera2.pipe.FrameInfo import androidx.camera.camera2.pipe.FrameNumber import androidx.camera.camera2.pipe.Request import androidx.camera.camera2.pipe.RequestMetadata import androidx.camera.camera2.pipe.integration.config.CameraScope import androidx.camera.camera2.pipe.integration.impl.CameraProperties import androidx.camera.camera2.pipe.integration.impl.ComboRequestListener import androidx.camera.camera2.pipe.integration.impl.UseCaseCamera import androidx.camera.camera2.pipe.integration.impl.UseCaseThreads import androidx.camera.core.CameraControl import dagger.Binds import dagger.Module import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Deferred import kotlinx.coroutines.launch import javax.inject.Inject interface EvCompCompat { val supported: Boolean val range: Range<Int> val step: Rational fun stopRunningTask() fun applyAsync( evCompIndex: Int, camera: UseCaseCamera ): Deferred<Int> @Module abstract class Bindings { @Binds abstract fun bindEvCompImpl(impl: EvCompImpl): EvCompCompat } } internal val EMPTY_RANGE: Range<Int> = Range(0, 0) /** * The implementation of the [EvCompCompat]. The [applyAsync] update the new exposure index value * to the camera, and wait for the exposure value of the camera reach to the new target. * It receives the [FrameInfo] via the [ComboRequestListener] to monitor the capture result. */ @RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java @CameraScope class EvCompImpl @Inject constructor( private val cameraProperties: CameraProperties, private val threads: UseCaseThreads, private val comboRequestListener: ComboRequestListener, ) : EvCompCompat { override val supported: Boolean get() = range.upper != 0 && range.lower != 0 override val range: Range<Int> by lazy { cameraProperties.metadata.getOrDefault(CONTROL_AE_COMPENSATION_RANGE, EMPTY_RANGE) } override val step: Rational get() = if (!supported) { Rational.ZERO } else { cameraProperties.metadata[CONTROL_AE_COMPENSATION_STEP]!! } private var updateSignal: CompletableDeferred<Int>? = null private var updateListener: Request.Listener? = null override fun stopRunningTask() { threads.sequentialScope.launch { stopRunningTaskInternal() } } override fun applyAsync(evCompIndex: Int, camera: UseCaseCamera): Deferred<Int> { val signal = CompletableDeferred<Int>() threads.sequentialScope.launch { stopRunningTaskInternal() updateSignal = signal camera.setParameterAsync(CONTROL_AE_EXPOSURE_COMPENSATION, evCompIndex) // Prepare the listener to wait for the exposure value to reach the target. updateListener = object : Request.Listener { override fun onComplete( requestMetadata: RequestMetadata, frameNumber: FrameNumber, result: FrameInfo ) { val state = result.metadata[CaptureResult.CONTROL_AE_STATE] val evResult = result.metadata[CaptureResult.CONTROL_AE_EXPOSURE_COMPENSATION] if (state != null && evResult != null) { when (state) { CaptureResult.CONTROL_AE_STATE_FLASH_REQUIRED, CaptureResult.CONTROL_AE_STATE_CONVERGED, CaptureResult.CONTROL_AE_STATE_LOCKED -> if (evResult == evCompIndex) { signal.complete(evCompIndex) comboRequestListener.removeListener(this) } else -> { } } } else if (evResult != null && evResult == evCompIndex) { // If AE state is null, only wait for the exposure result to the desired // value. signal.complete(evCompIndex) // Remove the capture result listener. The updateSignal and // updateListener will be cleared before the next set exposure task. comboRequestListener.removeListener(this) } } } comboRequestListener.addListener(updateListener!!, threads.sequentialExecutor) } return signal } private fun stopRunningTaskInternal() { updateSignal?.let { it.completeExceptionally( CameraControl.OperationCanceledException( "Cancelled by another setExposureCompensationIndex()" ) ) updateSignal = null } updateListener?.let { comboRequestListener.removeListener(it) updateListener = null } } }
apache-2.0
3297f6815570b805590bfb3286b79a22
37.906832
99
0.654
4.931496
false
false
false
false
androidx/androidx
lint-checks/src/main/java/androidx/build/lint/AndroidManifestServiceExportedDetector.kt
3
2435
/* * 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.build.lint import com.android.SdkConstants import com.android.tools.lint.detector.api.Category import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Incident import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.Scope import com.android.tools.lint.detector.api.Severity import com.android.tools.lint.detector.api.XmlContext import com.android.tools.lint.detector.api.XmlScanner import org.w3c.dom.Element @Suppress("UnstableApiUsage") class AndroidManifestServiceExportedDetector : Detector(), XmlScanner { override fun getApplicableElements(): Collection<String> { return listOf(SdkConstants.TAG_SERVICE) } override fun visitElement(context: XmlContext, element: Element) { val attrExported = element.getAttribute("android:${SdkConstants.ATTR_EXPORTED}") if (attrExported != "true") { val incident = Incident(context, ISSUE) .message("Missing exported=true in <service> tag") .at(element) context.report(incident) } } companion object { val ISSUE = Issue.create( id = "MissingServiceExportedEqualsTrue", briefDescription = "Missing exported=true declaration in the <service> tag inside" + " the library manifest", explanation = "Library-defined services should set the exported attribute to true.", category = Category.CORRECTNESS, priority = 5, severity = Severity.ERROR, implementation = Implementation( AndroidManifestServiceExportedDetector::class.java, Scope.MANIFEST_SCOPE ) ) } }
apache-2.0
d1eab442d32c957ce9ad1a4aa961629c
37.666667
96
0.699795
4.435337
false
false
false
false
androidx/androidx
wear/compose/compose-material/src/commonMain/kotlin/androidx/wear/compose/material/Shapes.kt
3
2644
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.compose.material import androidx.compose.foundation.shape.CornerBasedShape import androidx.compose.foundation.shape.CornerSize import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Immutable import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.ui.unit.dp /** * Components are grouped into shape categories based on common features. These categories provide a * way to change multiple component values at once, by changing the category’s values. * */ @Immutable public class Shapes( /** * Buttons and Chips use this shape */ public val small: CornerBasedShape = RoundedCornerShape(corner = CornerSize(50)), public val medium: CornerBasedShape = RoundedCornerShape(4.dp), /** * Cards use this shape */ public val large: CornerBasedShape = RoundedCornerShape(24.dp), ) { /** * Returns a copy of this Shapes, optionally overriding some of the values. */ public fun copy( small: CornerBasedShape = this.small, medium: CornerBasedShape = this.medium, large: CornerBasedShape = this.large, ): Shapes = Shapes( small = small, medium = medium, large = large, ) override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Shapes) return false if (small != other.small) return false if (medium != other.medium) return false if (large != other.large) return false return true } override fun hashCode(): Int { var result = small.hashCode() result = 31 * result + medium.hashCode() result = 31 * result + large.hashCode() return result } override fun toString(): String { return "Shapes(small=$small, medium=$medium, large=$large)" } } /** * CompositionLocal used to specify the default shapes for the surfaces. */ internal val LocalShapes = staticCompositionLocalOf { Shapes() }
apache-2.0
e6195d23459112bc8937521f3f57dc71
30.831325
100
0.690765
4.447811
false
false
false
false
androidx/androidx
compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/layout/Layout.kt
3
11427
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("DEPRECATION") package androidx.compose.ui.layout import androidx.compose.runtime.Applier import androidx.compose.runtime.Composable import androidx.compose.runtime.ReusableComposeNode import androidx.compose.runtime.SkippableUpdater import androidx.compose.runtime.currentComposer import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.UiComposable import androidx.compose.ui.graphics.GraphicsLayerScope import androidx.compose.ui.materialize import androidx.compose.ui.node.ComposeUiNode import androidx.compose.ui.node.LayoutNode import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.platform.LocalViewConfiguration import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.util.fastForEach /** * [Layout] is the main core component for layout. It can be used to measure and position * zero or more layout children. * * The measurement, layout and intrinsic measurement behaviours of this layout will be defined * by the [measurePolicy] instance. See [MeasurePolicy] for more details. * * For a composable able to define its content according to the incoming constraints, * see [androidx.compose.foundation.layout.BoxWithConstraints]. * * Example usage: * @sample androidx.compose.ui.samples.LayoutUsage * * Example usage with custom intrinsic measurements: * @sample androidx.compose.ui.samples.LayoutWithProvidedIntrinsicsUsage * * @param content The children composable to be laid out. * @param modifier Modifiers to be applied to the layout. * @param measurePolicy The policy defining the measurement and positioning of the layout. * * @see Layout * @see MeasurePolicy * @see androidx.compose.foundation.layout.BoxWithConstraints */ @Suppress("ComposableLambdaParameterPosition") @UiComposable @Composable inline fun Layout( content: @Composable @UiComposable () -> Unit, modifier: Modifier = Modifier, measurePolicy: MeasurePolicy ) { val density = LocalDensity.current val layoutDirection = LocalLayoutDirection.current val viewConfiguration = LocalViewConfiguration.current ReusableComposeNode<ComposeUiNode, Applier<Any>>( factory = ComposeUiNode.Constructor, update = { set(measurePolicy, ComposeUiNode.SetMeasurePolicy) set(density, ComposeUiNode.SetDensity) set(layoutDirection, ComposeUiNode.SetLayoutDirection) set(viewConfiguration, ComposeUiNode.SetViewConfiguration) }, skippableUpdate = materializerOf(modifier), content = content ) } /** * [Layout] is the main core component for layout for "leaf" nodes. It can be used to measure and * position zero children. * * The measurement, layout and intrinsic measurement behaviours of this layout will be defined * by the [measurePolicy] instance. See [MeasurePolicy] for more details. * * For a composable able to define its content according to the incoming constraints, * see [androidx.compose.foundation.layout.BoxWithConstraints]. * * Example usage: * @sample androidx.compose.ui.samples.LayoutUsage * * Example usage with custom intrinsic measurements: * @sample androidx.compose.ui.samples.LayoutWithProvidedIntrinsicsUsage * * @param modifier Modifiers to be applied to the layout. * @param measurePolicy The policy defining the measurement and positioning of the layout. * * @see Layout * @see MeasurePolicy * @see androidx.compose.foundation.layout.BoxWithConstraints */ @Suppress("NOTHING_TO_INLINE") @Composable @UiComposable inline fun Layout( modifier: Modifier = Modifier, measurePolicy: MeasurePolicy ) { val density = LocalDensity.current val layoutDirection = LocalLayoutDirection.current val viewConfiguration = LocalViewConfiguration.current val materialized = currentComposer.materialize(modifier) ReusableComposeNode<ComposeUiNode, Applier<Any>>( factory = ComposeUiNode.Constructor, update = { set(measurePolicy, ComposeUiNode.SetMeasurePolicy) set(density, ComposeUiNode.SetDensity) set(layoutDirection, ComposeUiNode.SetLayoutDirection) set(viewConfiguration, ComposeUiNode.SetViewConfiguration) set(materialized, ComposeUiNode.SetModifier) }, ) } /** * [Layout] is the main core component for layout. It can be used to measure and position * zero or more layout children. * * This overload accepts a list of multiple composable content lambdas, which allows treating * measurables put into different content lambdas differently - measure policy will provide * a list of lists of Measurables, not just a single list. Such list has the same size * as the list of contents passed into [Layout] and contains the list of measurables * of the corresponding content lambda in the same order. * * Note that layouts emitted as part of all [contents] lambdas will be added as a direct children * for this [Layout]. This means that if you set a custom z index on some children, the drawing * order will be calculated as if they were all provided as part of one lambda. * * Example usage: * @sample androidx.compose.ui.samples.LayoutWithMultipleContentsUsage * * @param contents The list of children composable contents to be laid out. * @param modifier Modifiers to be applied to the layout. * @param measurePolicy The policy defining the measurement and positioning of the layout. * * @see Layout for a simpler use case when you have only one content lambda. */ @Suppress("ComposableLambdaParameterPosition", "NOTHING_TO_INLINE") @UiComposable @Composable inline fun Layout( contents: List<@Composable @UiComposable () -> Unit>, modifier: Modifier = Modifier, measurePolicy: MultiContentMeasurePolicy ) { Layout( content = combineAsVirtualLayouts(contents), modifier = modifier, measurePolicy = remember(measurePolicy) { createMeasurePolicy(measurePolicy) } ) } @PublishedApi internal fun combineAsVirtualLayouts( contents: List<@Composable @UiComposable () -> Unit> ): @Composable @UiComposable () -> Unit = { contents.fastForEach { content -> ReusableComposeNode<ComposeUiNode, Applier<Any>>( factory = ComposeUiNode.VirtualConstructor, update = {}, content = content ) } } @PublishedApi internal fun materializerOf( modifier: Modifier ): @Composable SkippableUpdater<ComposeUiNode>.() -> Unit = { val materialized = currentComposer.materialize(modifier) update { set(materialized, ComposeUiNode.SetModifier) } } @Suppress("ComposableLambdaParameterPosition") @Composable @UiComposable @Deprecated( "This API is unsafe for UI performance at scale - using it incorrectly will lead " + "to exponential performance issues. This API should be avoided whenever possible." ) fun MultiMeasureLayout( modifier: Modifier = Modifier, content: @Composable @UiComposable () -> Unit, measurePolicy: MeasurePolicy ) { val materialized = currentComposer.materialize(modifier) val density = LocalDensity.current val layoutDirection = LocalLayoutDirection.current val viewConfiguration = LocalViewConfiguration.current ReusableComposeNode<LayoutNode, Applier<Any>>( factory = LayoutNode.Constructor, update = { set(materialized, ComposeUiNode.SetModifier) set(measurePolicy, ComposeUiNode.SetMeasurePolicy) set(density, ComposeUiNode.SetDensity) set(layoutDirection, ComposeUiNode.SetLayoutDirection) set(viewConfiguration, ComposeUiNode.SetViewConfiguration) @Suppress("DEPRECATION") init { this.canMultiMeasure = true } }, content = content ) } /** * Used to return a fixed sized item for intrinsics measurements in [Layout] */ private class FixedSizeIntrinsicsPlaceable(width: Int, height: Int) : Placeable() { init { measuredSize = IntSize(width, height) } override fun get(alignmentLine: AlignmentLine): Int = AlignmentLine.Unspecified override fun placeAt( position: IntOffset, zIndex: Float, layerBlock: (GraphicsLayerScope.() -> Unit)? ) { } } /** * Identifies an [IntrinsicMeasurable] as a min or max intrinsic measurement. */ internal enum class IntrinsicMinMax { Min, Max } /** * Identifies an [IntrinsicMeasurable] as a width or height intrinsic measurement. */ internal enum class IntrinsicWidthHeight { Width, Height } /** * A wrapper around a [Measurable] for intrinsic measurements in [Layout]. Consumers of * [Layout] don't identify intrinsic methods, but we can give a reasonable implementation * by using their [measure], substituting the intrinsics gathering method * for the [Measurable.measure] call. */ internal class DefaultIntrinsicMeasurable( val measurable: IntrinsicMeasurable, val minMax: IntrinsicMinMax, val widthHeight: IntrinsicWidthHeight ) : Measurable { override val parentData: Any? get() = measurable.parentData override fun measure(constraints: Constraints): Placeable { if (widthHeight == IntrinsicWidthHeight.Width) { val width = if (minMax == IntrinsicMinMax.Max) { measurable.maxIntrinsicWidth(constraints.maxHeight) } else { measurable.minIntrinsicWidth(constraints.maxHeight) } return FixedSizeIntrinsicsPlaceable(width, constraints.maxHeight) } val height = if (minMax == IntrinsicMinMax.Max) { measurable.maxIntrinsicHeight(constraints.maxWidth) } else { measurable.minIntrinsicHeight(constraints.maxWidth) } return FixedSizeIntrinsicsPlaceable(constraints.maxWidth, height) } override fun minIntrinsicWidth(height: Int): Int { return measurable.minIntrinsicWidth(height) } override fun maxIntrinsicWidth(height: Int): Int { return measurable.maxIntrinsicWidth(height) } override fun minIntrinsicHeight(width: Int): Int { return measurable.minIntrinsicHeight(width) } override fun maxIntrinsicHeight(width: Int): Int { return measurable.maxIntrinsicHeight(width) } } /** * Receiver scope for [Layout]'s and [LayoutModifier]'s layout lambda when used in an intrinsics * call. */ internal class IntrinsicsMeasureScope( density: Density, override val layoutDirection: LayoutDirection ) : MeasureScope, Density by density
apache-2.0
4c0ee1d985b250938ea173d24a51abd4
35.27619
97
0.734751
4.664082
false
false
false
false
waynepiekarski/XPlaneMonitor
app/src/main/java/net/waynepiekarski/xplanemonitor/BarView.kt
1
2913
// --------------------------------------------------------------------- // // XPlaneMonitor // // Copyright (C) 2017-2018 Wayne Piekarski // [email protected] http://tinmith.net/wayne // // 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 net.waynepiekarski.xplanemonitor import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.util.AttributeSet import android.view.View class BarView(context: Context, attrs: AttributeSet) : View(context, attrs) { private val mPaintNormal = Paint() private val mPaintWarning = Paint() private var mValue = 0.0 // Current value private var mMax = 1.0 // Maximum +/- value allowed private var mWarning = 0.0 // Warning +/- with different color private val mHeight = 20 // Height of the view in pixels init { mPaintNormal.color = Color.BLUE mPaintWarning.color = Color.RED resetLimits() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val parentWidth = View.MeasureSpec.getSize(widthMeasureSpec) this.setMeasuredDimension(parentWidth, mHeight) } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) val p: Paint if (mValue < -mWarning || mValue > mWarning) p = mPaintWarning else p = mPaintNormal // Draw a bar from the center out to the left or right depending on the mValue if (mValue >= 0) canvas.drawRect((canvas.width / 2).toFloat(), 0f, (canvas.width / 2.0 + mValue / mMax * canvas.width / 2.0).toInt().toFloat(), (canvas.height - 1).toFloat(), p) else // Cannot render right to left so need to flip around X arguments canvas.drawRect((canvas.width / 2.0 + mValue / mMax * canvas.width / 2.0).toInt().toFloat(), 0f, (canvas.width / 2).toFloat(), (canvas.height - 1).toFloat(), p) } fun setValue(arg: Double) { if (mValue != arg) { mValue = arg invalidate() } } fun resetLimits(max: Double = 1.0, warn: Double = 0.0) { mMax = max mWarning = warn mValue = 0.0 invalidate() } }
gpl-3.0
0f554d02e50485a9e064a702caa2ca6d
34.096386
172
0.623412
4.221739
false
false
false
false
yuzumone/SDNMonitor
app/src/main/kotlin/net/yuzumone/sdnmonitor/fragment/LoginFragment.kt
1
3765
/* * Copyright (C) 2016 yuzumone * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.yuzumone.sdnmonitor.fragment import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import net.yuzumone.sdnmonitor.R import net.yuzumone.sdnmonitor.api.MonitorClient import net.yuzumone.sdnmonitor.databinding.FragmentLoginBinding import net.yuzumone.sdnmonitor.util.AppUtil import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory import retrofit2.converter.moshi.MoshiConverterFactory import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import rx.subscriptions.CompositeSubscription import javax.inject.Inject class LoginFragment : BaseFragment() { private lateinit var binding: FragmentLoginBinding @Inject lateinit var client: OkHttpClient @Inject lateinit var compositeSubscription: CompositeSubscription override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = FragmentLoginBinding.inflate(inflater, container, false) initView() return binding.root } override fun onAttach(context: Context?) { super.onAttach(context) getComponent().inject(this) } private fun initView() { binding.editAddress.setText(AppUtil.getAddress(activity)) binding.editPort.setText(AppUtil.getPort(activity)) binding.buttonLogin.setOnClickListener { val address = binding.editAddress.text.toString() val port = binding.editPort.text.toString() connection(address, port) } } private fun connection(address: String, port: String) { val retrofit = Retrofit.Builder().client(client) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(MoshiConverterFactory.create()) .baseUrl("http://$address:$port/v1/") .build() val service = retrofit.create(MonitorClient.MonitorService::class.java) val subscription = service.ping() .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe { binding.progressBar.visibility = View.VISIBLE } .doOnCompleted { binding.progressBar.visibility = View.GONE } .subscribe( { response -> AppUtil.storeUri(activity, address, port) val fragment = SwitchListFragment() fragmentManager.beginTransaction().replace(R.id.container, fragment).commit() }, { error -> binding.progressBar.visibility = View.GONE Toast.makeText(activity, error.message, Toast.LENGTH_SHORT).show() } ) compositeSubscription.add(subscription) } override fun onDestroy() { compositeSubscription.unsubscribe() super.onDestroy() } }
apache-2.0
49496b8e9367caade444ff052e5a1664
37.428571
117
0.673307
5.108548
false
false
false
false
jwren/intellij-community
plugins/git4idea/src/git4idea/actions/GitCreateNewBranchAction.kt
1
4313
// 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 git4idea.actions import com.intellij.dvcs.DvcsUtil.guessVcsRoot import com.intellij.dvcs.branch.DvcsSyncSettings.Value.SYNC import com.intellij.dvcs.getCommonCurrentBranch import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys.VIRTUAL_FILE import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.vcs.log.Hash import com.intellij.vcs.log.VcsLogDataKeys import com.intellij.vcs.log.VcsRef import git4idea.GitRemoteBranch import git4idea.GitUtil.HEAD import git4idea.GitUtil.getRepositoryManager import git4idea.config.GitVcsSettings import git4idea.i18n.GitBundle import git4idea.repo.GitRepository import git4idea.ui.branch.createOrCheckoutNewBranch import org.jetbrains.annotations.Nls internal class GitCreateNewBranchAction : DumbAwareAction() { override fun actionPerformed(e: AnActionEvent) { when (val data = collectData(e)) { is Data.WithCommit -> createOrCheckoutNewBranch(data.repository.project, listOf(data.repository), data.hash.toString(), GitBundle.message("action.Git.New.Branch.dialog.title", data.hash.toShortString()), data.name) is Data.NoCommit -> createOrCheckoutNewBranch(data.project, data.repositories, HEAD, initialName = data.repositories.getCommonCurrentBranch()) } } override fun update(e: AnActionEvent) { super.update(e) when (val data = collectData(e)) { is Data.Invisible -> e.presentation.isEnabledAndVisible = false is Data.Disabled -> { e.presentation.isVisible = true e.presentation.isEnabled = false e.presentation.description = data.description } else -> e.presentation.isEnabledAndVisible = true } } private sealed class Data { object Invisible : Data() class Disabled(val description : @Nls String) : Data() class WithCommit(val repository: GitRepository, val hash: Hash, val name: String?) : Data() class NoCommit(val project: Project, val repositories: List<GitRepository>) : Data() } private fun collectData(e: AnActionEvent): Data { val project = e.project ?: return Data.Invisible val manager = getRepositoryManager(project) if (manager.repositories.isEmpty()) return Data.Invisible val log = e.getData(VcsLogDataKeys.VCS_LOG) if (log != null) { val commits = log.selectedCommits if (commits.isEmpty()) return Data.Invisible if (commits.size > 1) return Data.Disabled(GitBundle.message("action.New.Branch.disabled.several.commits.description")) val commit = commits.first() val repository = manager.getRepositoryForRootQuick(commit.root) if (repository != null) { val initialName = suggestBranchName(repository, e.getData(VcsLogDataKeys.VCS_LOG_BRANCHES)) return Data.WithCommit(repository, commit.hash, initialName) } } val repositories = if (manager.moreThanOneRoot()) { if (GitVcsSettings.getInstance(project).syncSetting == SYNC) manager.repositories else { val repository = manager.getRepositoryForRootQuick(guessVcsRoot(project, e.getData(VIRTUAL_FILE))) repository?.let { listOf(repository) } } } else listOf(manager.repositories.first()) if (repositories == null || repositories.any { it.isFresh }) return Data.Disabled(GitBundle.message("action.New.Branch.disabled.fresh.description")) return Data.NoCommit(project, repositories) } private fun suggestBranchName(repository: GitRepository, branches: List<VcsRef>?): String? { val existingBranches = branches.orEmpty().filter { it.type.isBranch } val suggestedNames = existingBranches.map { val branch = repository.branches.findBranchByName(it.name) ?: return@map null if (branch.isRemote) { return@map (branch as GitRemoteBranch).nameForRemoteOperations } else { return@map branch.name } } return suggestedNames.distinct().singleOrNull() } }
apache-2.0
8a877c8e7a06a80330bcacc2f573f6ac
42.13
152
0.708556
4.497393
false
false
false
false
K0zka/kerub
src/main/kotlin/com/github/kerubistan/kerub/data/ispn/JsonMarshaller.kt
2
2461
package com.github.kerubistan.kerub.data.ispn import com.fasterxml.jackson.databind.ObjectMapper import com.github.kerubistan.kerub.model.Entity import com.github.kerubistan.kerub.model.Host import com.github.kerubistan.kerub.model.VirtualMachine import com.github.kerubistan.kerub.model.controller.Assignment import com.github.kerubistan.kerub.utils.getLogger import org.infinispan.commons.io.ByteBuffer import org.infinispan.commons.io.ByteBufferImpl import org.infinispan.commons.marshall.BufferSizePredictor import org.infinispan.commons.marshall.Marshaller import java.io.ByteArrayOutputStream /** * Integrates the jackson objectmapper to the infinispan infrastructure and allows * persisting the data in json format. */ class JsonMarshaller(private val objectMapper: ObjectMapper) : Marshaller { object Predictor : BufferSizePredictor { override fun nextSize(obj: Any?): Int = when (obj) { is VirtualMachine -> 8 * KB is Assignment -> 1 * KB is Host -> 128 * KB else -> 1024 } override fun recordSize(previousSize: Int) = logger.debug("size: $previousSize") } companion object { const val KB = 1024 private val logger = getLogger() } private fun objectToByteArray(o: Any?, objectMapper: ObjectMapper, estimatedSize: Int? = null): ByteArray = ByteArrayOutputStream(estimatedSize ?: 1024).use { objectMapper.writeValue(it, o) it.toByteArray() } private fun byteArrayToObject( objectMapper: ObjectMapper, bytes: ByteArray, start: Int? = null, len: Int? = null ): Any? = objectMapper.readValue(bytes, start ?: 1, len ?: bytes.size, Entity::class.java) override fun objectToBuffer(o: Any?): ByteBuffer? { val bytes = objectToByteArray(o, objectMapper) return ByteBufferImpl(bytes, 0, bytes.size) } override fun objectToByteBuffer(obj: Any?, estimatedSize: Int): ByteArray = objectToByteArray(obj, objectMapper, estimatedSize) override fun objectToByteBuffer(obj: Any?): ByteArray = objectToByteArray(obj, objectMapper) override fun isMarshallable(o: Any?): Boolean = Entity::class.java.isAssignableFrom(o?.javaClass) override fun objectFromByteBuffer(buf: ByteArray?): Any? = byteArrayToObject(objectMapper, buf ?: ByteArray(0)) override fun objectFromByteBuffer(buf: ByteArray?, offset: Int, length: Int): Any? = byteArrayToObject(objectMapper, buf ?: ByteArray(0), offset, length) override fun getBufferSizePredictor(o: Any?): BufferSizePredictor = Predictor }
apache-2.0
576b00f6066091c7c4138859f1dc2662
35.746269
112
0.762292
3.94391
false
false
false
false
GunoH/intellij-community
platform/statistics/devkit/src/com/intellij/internal/statistic/devkit/actions/CollectFUStatisticsAction.kt
4
6696
// 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.internal.statistic.devkit.actions import com.google.common.collect.HashMultiset import com.google.gson.GsonBuilder import com.intellij.BundleBase import com.intellij.ide.actions.GotoActionBase import com.intellij.ide.util.gotoByName.ChooseByNameItem import com.intellij.ide.util.gotoByName.ChooseByNamePopup import com.intellij.ide.util.gotoByName.ChooseByNamePopupComponent import com.intellij.ide.util.gotoByName.ListChooseByNameModel import com.intellij.internal.statistic.devkit.StatisticsDevKitUtil import com.intellij.internal.statistic.eventLog.LogEventSerializer import com.intellij.internal.statistic.eventLog.newLogEvent import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector import com.intellij.internal.statistic.service.fus.collectors.FUStateUsagesLogger import com.intellij.internal.statistic.service.fus.collectors.FeatureUsagesCollector import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector import com.intellij.internal.statistic.utils.StatisticsRecorderUtil import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileTypes.FileTypeManager import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.runBackgroundableTask import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil import com.intellij.testFramework.LightVirtualFile import com.intellij.util.containers.ContainerUtil import org.jetbrains.concurrency.resolvedPromise internal class CollectFUStatisticsAction : GotoActionBase(), DumbAware { override fun update(e: AnActionEvent) { super.update(e) if (e.presentation.isEnabled) { e.presentation.isEnabled = StatisticsRecorderUtil.isTestModeEnabled(StatisticsDevKitUtil.DEFAULT_RECORDER) } } override fun gotoActionPerformed(e: AnActionEvent) { val project = e.project ?: return val projectCollectors = ExtensionPointName.create<Any>("com.intellij.statistics.projectUsagesCollector").extensionList val applicationCollectors = ExtensionPointName.create<Any>("com.intellij.statistics.applicationUsagesCollector").extensionList val collectors = (projectCollectors + applicationCollectors).filterIsInstance(FeatureUsagesCollector::class.java) val ids = collectors.mapTo(HashMultiset.create()) { it.groupId } val items = collectors .map { collector -> val groupId = collector.groupId val className = StringUtil.nullize(collector.javaClass.simpleName, true) Item(collector, groupId, className, ids.count(groupId) > 1) } ContainerUtil.sort(items, Comparator.comparing { it.groupId }) val model = MyChooseByNameModel(project, items) val popup = ChooseByNamePopup.createPopup(project, model, getPsiContext(e)) popup.setShowListForEmptyPattern(true) popup.invoke(object : ChooseByNamePopupComponent.Callback() { override fun onClose() { if ([email protected] == myInAction) myInAction = null } override fun elementChosen(element: Any) { runBackgroundableTask("Collecting statistics", project, true) { indicator -> indicator.isIndeterminate = true indicator.text2 = (element as Item).usagesCollector.javaClass.simpleName showCollectorUsages(project, element, model.useExtendedPresentation, indicator) } } }, ModalityState.current(), false) } private fun showCollectorUsages(project: Project, item: Item, useExtendedPresentation: Boolean, indicator: ProgressIndicator) { if (project.isDisposed) { return } val collector = item.usagesCollector val metricsPromise = when (collector) { is ApplicationUsagesCollector -> resolvedPromise(collector.getMetrics()) is ProjectUsagesCollector -> collector.getMetrics(project, indicator) else -> throw IllegalArgumentException("Unsupported collector: $collector") } val gson = GsonBuilder().setPrettyPrinting().create() val result = StringBuilder() metricsPromise.onSuccess { metrics -> if (useExtendedPresentation) { result.append("[\n") for (metric in metrics) { val metricData = FUStateUsagesLogger.mergeWithEventData(null, metric.data)!!.build() val event = newLogEvent("test.session", "build", "bucket", System.currentTimeMillis(), collector.groupId, collector.version.toString(), "recorder.version", "event.id", true, metricData) val presentation = LogEventSerializer.toString(event) result.append(presentation) result.append(",\n") } result.append("]") } else { result.append("{") for (metric in metrics) { result.append("\"") result.append(metric.eventId) result.append("\" : ") val presentation = gson.toJsonTree(metric.data.build()) result.append(presentation) result.append(",\n") } result.append("}") } val fileType = FileTypeManager.getInstance().getStdFileType("JSON") val file = LightVirtualFile(item.groupId, fileType, result.toString()) ApplicationManager.getApplication().invokeLater { FileEditorManager.getInstance(project).openFile(file, true) } } } private class Item(val usagesCollector: FeatureUsagesCollector, val groupId: String, val className: String?, val nonUniqueId: Boolean) : ChooseByNameItem { override fun getName(): String = groupId + if (nonUniqueId) " ($className)" else "" override fun getDescription(): String? = className } private class MyChooseByNameModel(project: Project, items: List<Item>) : ListChooseByNameModel<Item>(project, "Enter usage collector group id", "No collectors found", items), DumbAware { var useExtendedPresentation: Boolean = false override fun getCheckBoxName(): String? = BundleBase.replaceMnemonicAmpersand("&Extended presentation") override fun loadInitialCheckBoxState(): Boolean = false override fun saveInitialCheckBoxState(state: Boolean) { useExtendedPresentation = state } override fun useMiddleMatching(): Boolean = true } }
apache-2.0
92288eec2facee0ad435790387c83d0a
44.25
130
0.742085
4.938053
false
false
false
false
LouisCAD/Splitties
modules/experimental/src/commonMain/kotlin/splitties/experimental/Annotations.kt
1
614
/* * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ package splitties.experimental @MustBeDocumented @Retention(value = AnnotationRetention.BINARY) @RequiresOptIn(level = RequiresOptIn.Level.WARNING) annotation class ExperimentalSplittiesApi @MustBeDocumented @Retention(value = AnnotationRetention.BINARY) @RequiresOptIn(level = RequiresOptIn.Level.ERROR) annotation class NonSymmetricalApi @MustBeDocumented @Retention(value = AnnotationRetention.BINARY) @RequiresOptIn(level = RequiresOptIn.Level.ERROR) annotation class InternalSplittiesApi
apache-2.0
bf6159f67eae066653c669f259b22fb0
29.7
109
0.830619
4.723077
false
false
false
false
smmribeiro/intellij-community
uast/uast-common/src/org/jetbrains/uast/values/UValueBase.kt
16
3407
// 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 org.jetbrains.uast.values abstract class UValueBase : UValue { override operator fun plus(other: UValue): UValue = if (other is UDependentValue) other + this else UUndeterminedValue override operator fun minus(other: UValue): UValue = this + (-other) override operator fun times(other: UValue): UValue = if (other is UDependentValue) other * this else UUndeterminedValue override operator fun div(other: UValue): UValue = (other as? UDependentValue)?.inverseDiv(this) ?: UUndeterminedValue override operator fun rem(other: UValue): UValue = (other as? UDependentValue)?.inverseMod(this) ?: UUndeterminedValue override fun unaryMinus(): UValue = UUndeterminedValue override fun valueEquals(other: UValue): UValue = if (other is UDependentValue || other is UNaNConstant) other.valueEquals(this) else UUndeterminedValue override fun valueNotEquals(other: UValue): UValue = !this.valueEquals(other) override fun identityEquals(other: UValue): UValue = valueEquals(other) override fun identityNotEquals(other: UValue): UValue = !this.identityEquals(other) override fun not(): UValue = UUndeterminedValue override fun greater(other: UValue): UValue = if (other is UDependentValue || other is UNaNConstant) other.less(this) else UUndeterminedValue override fun less(other: UValue): UValue = other.greater(this) override fun greaterOrEquals(other: UValue): UValue = this.greater(other) or this.valueEquals(other) override fun lessOrEquals(other: UValue): UValue = this.less(other) or this.valueEquals(other) override fun inc(): UValue = UUndeterminedValue override fun dec(): UValue = UUndeterminedValue override fun and(other: UValue): UValue = if (other is UDependentValue || other == UBooleanConstant.False) other and this else UUndeterminedValue override fun or(other: UValue): UValue = if (other is UDependentValue || other == UBooleanConstant.True) other or this else UUndeterminedValue override fun bitwiseAnd(other: UValue): UValue = if (other is UDependentValue) other bitwiseAnd this else UUndeterminedValue override fun bitwiseOr(other: UValue): UValue = if (other is UDependentValue) other bitwiseOr this else UUndeterminedValue override fun bitwiseXor(other: UValue): UValue = if (other is UDependentValue) other bitwiseXor this else UUndeterminedValue override fun shl(other: UValue): UValue = (other as? UDependentValue)?.inverseShiftLeft(this) ?: UUndeterminedValue override fun shr(other: UValue): UValue = (other as? UDependentValue)?.inverseShiftRight(this) ?: UUndeterminedValue override fun ushr(other: UValue): UValue = (other as? UDependentValue)?.inverseShiftRightUnsigned(this) ?: UUndeterminedValue override fun merge(other: UValue): UValue = when (other) { this -> this is UDependentValue -> other.merge(this) is UCallResultValue -> other.merge(this) else -> UPhiValue.create(this, other) } override val dependencies: Set<UDependency> get() = emptySet() override fun toConstant(): UConstant? = this as? UConstant internal open fun coerceConstant(constant: UConstant): UValue = constant override val reachable: Boolean = true abstract override fun toString(): String }
apache-2.0
61ff65fc80f615d01858f8cc79a1de61
38.172414
140
0.750514
4.542667
false
false
false
false
BenWoodworth/FastCraft
fastcraft-core/src/main/kotlin/net/benwoodworth/fastcraft/util/MinecraftAssets.kt
1
4966
package net.benwoodworth.fastcraft.util import kotlinx.serialization.Serializable import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import net.benwoodworth.fastcraft.platform.server.FcLogger import net.benwoodworth.fastcraft.platform.server.FcPluginData import net.benwoodworth.fastcraft.platform.server.FcServer import java.io.InputStream import java.net.URL import java.nio.file.Path import java.nio.file.StandardCopyOption import java.security.DigestInputStream import java.security.MessageDigest import javax.inject.Inject import javax.inject.Singleton import kotlin.io.path.* @Singleton @OptIn(ExperimentalPathApi::class) class MinecraftAssets @Inject constructor( fcPluginData: FcPluginData, private val fcServer: FcServer, private val fcLogger: FcLogger, ) { private val versionManifestUrl = URL("https://launchermeta.mojang.com/mc/game/version_manifest.json") private val assetsCacheDir = fcPluginData.dataFolder.resolve("cache/assets/minecraft/${fcServer.minecraftVersion}") private lateinit var assetIndex: AssetIndex private val json = Json { this.ignoreUnknownKeys = true } private fun getVersionManifest(): VersionManifest { versionManifestUrl.openStream().bufferedReader().use { reader -> return json.decodeFromString(reader.readText()) } } private fun getVersionInfo(): VersionInfo { val versionInfoUrl = getVersionManifest().versions .firstOrNull { it.id == fcServer.minecraftVersion } ?.let { URL(it.url) } ?: error("Minecraft version not found in version manifest: ${fcServer.minecraftVersion}") versionInfoUrl.openStream().bufferedReader().use { reader -> return json.decodeFromString(reader.readText()) } } private fun getAssetIndex(): AssetIndex { if (!this::assetIndex.isInitialized) { assetIndex = try { val versionInfo = getVersionInfo() val assetIndexFile = assetsCacheDir.resolve("index.json") if (!assetIndexFile.exists()) { downloadFile(URL(versionInfo.assetIndex.url), assetIndexFile, versionInfo.assetIndex.sha1) } json.decodeFromString(assetIndexFile.readText()) } catch (e: Exception) { fcLogger.error("Error getting Minecraft assets: ${e.message}") AssetIndex(emptyMap()) } } return assetIndex } fun getAssets(): Set<String> { return getAssetIndex().objects.keys } private fun cacheAsset(name: String) { val assetCacheFile = assetsCacheDir.resolve(name) if (!assetCacheFile.exists()) { val asset = getAssetIndex().objects[name] ?: error("Minecraft asset not found: $name") downloadFile(asset.url, assetCacheFile, asset.hash) } } fun openAsset(name: String): InputStream { cacheAsset(name) return assetsCacheDir.resolve(name).inputStream() } @OptIn(ExperimentalUnsignedTypes::class) private fun downloadFile(url: URL, file: Path, sha1: String?) { val partFile = file.resolveSibling("${file.fileName}.part") if (!partFile.parent.exists()) { partFile.parent.createDirectories() } else if (partFile.exists()) { partFile.deleteExisting() } val digest = MessageDigest.getInstance("SHA-1") DigestInputStream(url.openStream(), digest).bufferedReader().use { reader -> partFile.bufferedWriter().use { writer -> reader.copyTo(writer) } } if (sha1 != null) { val actualHash = digest.digest().asUByteArray() .joinToString("") { it.toString(16).padStart(2, '0') } if (!actualHash.equals(sha1, ignoreCase = true)) { error("Minecraft asset hash mismatch while downloading $url") } } partFile.moveTo(file, StandardCopyOption.REPLACE_EXISTING) } @Serializable private class VersionManifest( val versions: List<Version>, ) { @Serializable class Version( val id: String, val url: String, ) } @Serializable private class VersionInfo( val assetIndex: AssetIndex, ) { @Serializable class AssetIndex( val id: String, val sha1: String, val size: Long, val url: String, ) } @Serializable private class AssetIndex( val objects: Map<String, Object>, ) { @Serializable class Object( val hash: String, val size: Long, ) } private val AssetIndex.Object.url: URL get() = URL("http://resources.download.minecraft.net/${hash.take(2)}/$hash") }
gpl-3.0
fa03752d06ca9ed0eb6d12c64d80d619
30.833333
119
0.626259
4.761266
false
false
false
false
testIT-LivingDoc/livingdoc2
livingdoc-reports/src/main/kotlin/org/livingdoc/reports/ReportWriter.kt
2
951
package org.livingdoc.reports import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.nio.file.StandardOpenOption class ReportWriter( private val outputDir: String = REPORT_OUTPUT_PATH, private val fileExtension: String ) { private companion object { const val REPORT_OUTPUT_PATH = "build/livingdoc/reports/" const val REPORT_OUTPUT_FILENAME = "result" } /** * Write the [textToWrite] as report to the configured location. The reports filename will contain the [reportName] * and end with the [fileExtension]. */ fun writeToFile(textToWrite: String, reportName: String = REPORT_OUTPUT_FILENAME): Path { val path = Paths.get(outputDir) Files.createDirectories(path) val file = path.resolve("$reportName.$fileExtension") Files.write(file, textToWrite.toByteArray(), StandardOpenOption.CREATE_NEW) return file } }
apache-2.0
6c18f7f94c935ac91c88e5a378d2b4cb
30.7
119
0.701367
4.322727
false
false
false
false
clumsy/intellij-community
platform/script-debugger/backend/src/org/jetbrains/debugger/sourcemap/SourceMap.kt
2
2257
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger.sourcemap import com.intellij.openapi.util.NullableLazyValue import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.Url // sources - is not originally specified, but canonicalized/normalized class SourceMap(val outFile: String?, val mappings: MappingList, internal val sourceIndexToMappings: Array<MappingList?>, val sourceResolver: SourceResolver, val hasNameMappings: Boolean) { val sources: Array<Url> get() = sourceResolver.canonicalizedSources fun getSourceLineByRawLocation(rawLine: Int, rawColumn: Int) = mappings.get(rawLine, rawColumn)?.sourceLine ?: -1 fun findMappingList(sourceUrls: List<Url>, sourceFile: VirtualFile?, resolver: NullableLazyValue<SourceResolver.Resolver>?): MappingList? { var mappings = sourceResolver.findMappings(sourceUrls, this, sourceFile) if (mappings == null && resolver != null) { val resolverValue = resolver.value if (resolverValue != null) { mappings = sourceResolver.findMappings(sourceFile, this, resolverValue) } } return mappings } fun processMappingsInLine(sourceUrls: List<Url>, sourceLine: Int, mappingProcessor: MappingList.MappingsProcessorInLine, sourceFile: VirtualFile?, resolver: NullableLazyValue<SourceResolver.Resolver>?): Boolean { val mappings = findMappingList(sourceUrls, sourceFile, resolver) return mappings != null && mappings.processMappingsInLine(sourceLine, mappingProcessor) } fun getMappingsOrderedBySource(source: Int) = sourceIndexToMappings[source]!! }
apache-2.0
9da733a6643b67de08440a104bb81369
44.16
189
0.726628
4.550403
false
false
false
false
joaomneto/TitanCompanion
src/main/java/pt/joaomneto/titancompanion/adventure/impl/fragments/trok/TROKStarShipCombatFragment.kt
1
7854
package pt.joaomneto.titancompanion.adventure.impl.fragments.trok import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.View.OnClickListener import android.view.ViewGroup import android.widget.Button import android.widget.TextView import pt.joaomneto.titancompanion.R import pt.joaomneto.titancompanion.adventure.Adventure import pt.joaomneto.titancompanion.adventure.AdventureFragment import pt.joaomneto.titancompanion.adventure.impl.TROKAdventure import pt.joaomneto.titancompanion.util.DiceRoller class TROKStarShipCombatFragment : AdventureFragment() { internal var starshipWeaponsValue: TextView? = null internal var starshipShieldsValue: TextView? = null internal var starshipMissilesValue: TextView? = null internal var enemyWeaponsValue: TextView? = null internal var enemyShieldsValue: TextView? = null internal var enemy2WeaponsValue: TextView? = null internal var enemy2ShieldsValue: TextView? = null internal var attackButton: Button? = null var enemyWeapons = 0 var enemyShields = 0 var enemy2Weapons = 0 var enemy2Shields = 0 internal var combatResult: TextView? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { super.onCreate(savedInstanceState) val rootView = inflater.inflate(R.layout.fragment_15trok_adventure_starshipcombat, container, false) val adv = activity as TROKAdventure starshipWeaponsValue = rootView.findViewById<View>(R.id.starshipWeaponsValue) as TextView starshipShieldsValue = rootView.findViewById<View>(R.id.starshipShieldsValue) as TextView starshipMissilesValue = rootView.findViewById<View>(R.id.starshipMissilesValue) as TextView enemyWeaponsValue = rootView.findViewById<View>(R.id.enemyWeaponsValue) as TextView enemyShieldsValue = rootView.findViewById<View>(R.id.enemyShieldsValue) as TextView enemy2WeaponsValue = rootView.findViewById<View>(R.id.enemy2WeaponsValue) as TextView enemy2ShieldsValue = rootView.findViewById<View>(R.id.enemy2ShieldsValue) as TextView starshipWeaponsValue!!.text = "" + adv.currentWeapons starshipShieldsValue!!.text = "" + adv.currentShields combatResult = rootView.findViewById<View>(R.id.combatResult) as TextView setupIncDecButton( rootView, R.id.plusWeaponsButton, R.id.minusWeaponsButton, adv, TROKAdventure::currentWeapons, 1 ) setupIncDecButton( rootView, R.id.plusShieldsButton, R.id.minusShieldsButton, adv, TROKAdventure::currentShields, adv.initialShields ) setupIncDecButton(rootView, R.id.plusMissilesButton, R.id.minusMissilesButton, adv, TROKAdventure::missiles, 99) setupIncDecButton(rootView, R.id.plusEnemyWeaponsButton, R.id.minusEnemyWeaponsButton, ::enemyWeapons, 99) setupIncDecButton(rootView, R.id.plusEnemyShieldsButton, R.id.minusEnemyShieldsButton, ::enemyShields, 99) setupIncDecButton(rootView, R.id.plusEnemy2WeaponsButton, R.id.minusEnemy2WeaponsButton, ::enemyWeapons, 99) setupIncDecButton(rootView, R.id.plusEnemy2ShieldsButton, R.id.minusEnemy2ShieldsButton, ::enemyShields, 99) setupIncDecButton(rootView, R.id.plusEnemy2WeaponsButton, R.id.minusEnemy2WeaponsButton, ::enemy2Weapons, 99) setupIncDecButton(rootView, R.id.plusEnemy2ShieldsButton, R.id.minusEnemy2ShieldsButton, ::enemy2Shields, 99) attackButton = rootView.findViewById<View>(R.id.buttonAttack) as Button attackButton!!.setOnClickListener( OnClickListener { if (enemyShields == 0 || adv.currentShields == 0) return@OnClickListener combatResult!!.text = "" if (enemyShields > 0) { if (DiceRoller.roll2D6().sum <= adv.currentWeapons) { val damage = 1 enemyShields -= damage if (enemyShields <= 0) { enemyShields = 0 Adventure.showAlert(R.string.ffDirectHitDefeat, adv) } else { combatResult!!.text = getString(R.string.trokDirectHit, damage) } } else { combatResult!!.setText(R.string.missedTheEnemy) } } else if (enemy2Shields > 0) { if (DiceRoller.roll2D6().sum <= adv.currentWeapons) { val damage = 1 enemy2Shields -= damage if (enemy2Shields <= 0) { enemy2Shields = 0 Adventure.showAlert(getString(R.string.directHitDefeatSecondEnemy), adv) } else { combatResult!!.text = getString(R.string.trokDirectHit, damage) } } else { combatResult!!.setText(R.string.missedTheEnemy) } } else { return@OnClickListener } if (enemyShields > 0) { if (DiceRoller.roll2D6().sum <= enemyWeapons) { val damage = 1 adv.currentShields = adv.currentShields - damage if (adv.currentShields <= 0) { adv.currentShields = 0 Adventure.showAlert(getString(R.string.trokPlayerStarshipDestroyed), adv) } else { combatResult!!.text = combatResult!!.text.toString() + "\n" + getString( R.string.trokEnemyHitPlayerStarship, damage ) } } else { combatResult!!.text = combatResult!!.text.toString() + "\n" + getString(R.string.enemyMissed) } } if (enemy2Shields > 0) { if (DiceRoller.roll2D6().sum <= enemy2Weapons) { val damage = 1 adv.currentShields = adv.currentShields - damage if (adv.currentShields <= 0) { adv.currentShields = 0 Adventure.showAlert(R.string.trokPlayerStarshipDestroyed, adv) } else { combatResult!!.text = combatResult!!.text.toString() + "\n" + getString( R.string.trokSecondEnemyHitPlayerStarship, damage ) } } else { combatResult!!.text = combatResult!!.text.toString() + "\n" + getString(R.string.secondEnemyMissed) } } refreshScreensFromResume() } ) refreshScreensFromResume() return rootView } override fun refreshScreensFromResume() { val adv = activity as TROKAdventure enemyShieldsValue!!.text = "" + enemyShields enemyWeaponsValue!!.text = "" + enemyWeapons enemy2ShieldsValue!!.text = "" + enemy2Shields enemy2WeaponsValue!!.text = "" + enemy2Weapons starshipShieldsValue!!.text = "" + adv.currentShields starshipWeaponsValue!!.text = "" + adv.currentWeapons starshipMissilesValue!!.text = "" + adv.missiles } }
lgpl-3.0
4e0072001208decc1a4f3501eec814d7
42.877095
123
0.580851
4.672219
false
false
false
false
getsentry/raven-java
sentry/src/test/java/io/sentry/protocol/BrowserTest.kt
1
1164
package io.sentry.protocol import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertNotSame class BrowserTest { @Test fun `copying browser wont have the same references`() { val browser = Browser() browser.name = "browser name" browser.version = "browser version" val unknown = mapOf(Pair("unknown", "unknown")) browser.acceptUnknownProperties(unknown) val clone = Browser(browser) assertNotNull(clone) assertNotSame(browser, clone) assertNotSame(browser.unknown, clone.unknown) } @Test fun `copying browser will have the same values`() { val browser = Browser() browser.name = "browser name" browser.version = "browser version" val unknown = mapOf(Pair("unknown", "unknown")) browser.acceptUnknownProperties(unknown) val clone = Browser(browser) assertEquals("browser name", clone.name) assertEquals("browser version", clone.version) assertNotNull(clone.unknown) { assertEquals("unknown", it["unknown"]) } } }
bsd-3-clause
f36ad5bbcacf84e5510be035db0cc032
27.390244
59
0.649485
4.731707
false
true
false
false
softappeal/yass
kotlin/yass/test/ch/softappeal/yass/remote/RemoteTest.kt
1
7752
package ch.softappeal.yass.remote import ch.softappeal.yass.* import java.util.concurrent.* import kotlin.system.* import kotlin.test.* class DivisionByZeroException(val a: Int) : RuntimeException() interface Calculator { @OneWay fun oneWay() fun twoWay() fun divide(a: Int, b: Int): Int fun echo(value: String?): String? } private interface AsyncCalculator { fun oneWay() fun twoWay(): CompletionStage<Unit> fun divide(a: Int, b: Int): CompletionStage<Int> fun echo(value: String?): CompletionStage<String?> } private fun asyncCalculator(asyncCalculator: Calculator): AsyncCalculator = object : AsyncCalculator { override fun oneWay() { asyncCalculator.oneWay() } override fun twoWay(): CompletionStage<Unit> { return promise { asyncCalculator.twoWay() } } override fun divide(a: Int, b: Int): CompletionStage<Int> { return promise { asyncCalculator.divide(a, b) } } override fun echo(value: String?): CompletionStage<String?> { return promise { asyncCalculator.echo(value) } } } val CalculatorImpl = object : Calculator { override fun oneWay() { println("oneWay") } override fun twoWay() { println("twoWay") } override fun divide(a: Int, b: Int): Int { if (b == 0) throw DivisionByZeroException(a) return a / b } override fun echo(value: String?) = value } val AsyncCalculatorImpl = object : Calculator { private fun sleep(execute: (completer: Completer) -> Unit) { val completer = completer Thread { TimeUnit.MILLISECONDS.sleep(100L) execute(completer) }.start() } override fun oneWay() { println("oneWay") } override fun twoWay() { println("twoWay") sleep(Completer::complete) } override fun divide(a: Int, b: Int): Int { sleep { if (b == 0) it.completeExceptionally(DivisionByZeroException(a)) else it.complete(a / b) } return 0 } override fun echo(value: String?): String? { sleep { completer -> completer.complete(value) } return null } } fun useSyncClient(calculator: Calculator) { assertEquals(4, calculator.divide(12, 3)) assertEquals( 12, assertFailsWith<DivisionByZeroException> { calculator.divide(12, 0) }.a ) calculator.twoWay() assertNull(calculator.echo(null)) assertEquals("hello", calculator.echo("hello")) calculator.oneWay() } private fun useAsyncClient(asyncCalculator: Calculator) { assertEquals( "asynchronous OneWay proxy call must not be enclosed with 'promise' function", assertFailsWith<IllegalStateException> { promise { asyncCalculator.oneWay() } }.message ) assertEquals( "asynchronous request/reply proxy call must be enclosed with 'promise' function", assertFailsWith<IllegalStateException> { asyncCalculator.twoWay() }.message ) } fun useClient(calculator: Calculator, asyncCalculator: Calculator) { useSyncClient(calculator) useAsyncClient(asyncCalculator) } val calculatorId = contractId<Calculator>(123, SimpleMethodMapperFactory) val asyncCalculatorId = contractId<Calculator>(321, SimpleMethodMapperFactory) private fun printer(side: String): Interceptor { return { method, arguments, invocation -> fun print(type: String, data: Any?, arguments: List<Any?>? = null) = println("$side - ${Thread.currentThread().name} - $type - $data ${arguments ?: ""}") print("enter", method.name, arguments) try { val result = invocation() print("exit", result) result } catch (e: Exception) { print("exception", e) throw e } } } val clientPrinter = printer("client") val serverPrinter = printer("server") private var counter = 0 fun asyncPrinter(side: String) = object : AsyncInterceptor { override fun entry(invocation: AbstractInvocation) { invocation.context = counter++ println("$side - ${invocation.context} - enter ${invocation.methodMapping.method.name}${invocation.arguments}") } override fun exit(invocation: AbstractInvocation, result: Any?) { println("$side - ${invocation.context} - exit $result") } override fun exception(invocation: AbstractInvocation, exception: Exception) { println("$side - ${invocation.context} - exception $exception") } } fun performance(client: Client) { val calculator = client.proxy(calculatorId) val iterations = 1 // 10_000 for (warmUp in 1..2) { println("iterations = $iterations, one took ${1_000.0 * measureTimeMillis { for (i in 1..iterations) assertEquals(4, calculator.divide(12, 3)) } / iterations}us") } } private fun client(server: Server, clientAsyncSupported: Boolean) = object : Client() { override fun invoke(invocation: ClientInvocation) = invocation.invoke(clientAsyncSupported) { request -> Thread { server.invocation(true, request) .invoke({ println("cleanup ${invocation.methodMapping.method.name}") }) { reply -> invocation.settle(reply) } }.start() } } class RemoteTest { @Test fun invocations() { val client = client( Server( Service(calculatorId, CalculatorImpl, serverPrinter), AsyncService(asyncCalculatorId, AsyncCalculatorImpl, asyncPrinter("server")) ), true ) useClient( client.proxy(calculatorId, clientPrinter), client.asyncProxy(asyncCalculatorId, asyncPrinter("client")) ) } @Test fun asyncProxy() { val client = client(Server(Service(calculatorId, CalculatorImpl)), false) client.proxy(calculatorId).twoWay() assertEquals( "asynchronous services not supported (service id 123)", assertFailsWith<IllegalStateException> { promise { client.asyncProxy(calculatorId).twoWay() } }.message ) } @Test fun services() { val service = Service(calculatorId, CalculatorImpl) assertEquals( "service id 123 already added", assertFailsWith<IllegalStateException> { Server(service, service) }.message ) assertEquals( "no service id 987 found (method id 0)", assertFailsWith<IllegalStateException> { Server(service).invocation(true, Request(987, 0, listOf())) }.message ) } @Test fun asyncService() { val asyncService = AsyncService(calculatorId, CalculatorImpl) Server(asyncService).invocation(true, Request(calculatorId.id, 0, listOf())) assertEquals( "asynchronous services not supported (service id 123)", assertFailsWith<IllegalStateException> { Server(asyncService).invocation(false, Request(calculatorId.id, 0, listOf())) }.message ) } @Test fun noCompleter() = assertEquals( "no active asynchronous request/reply service invocation", assertFailsWith<IllegalStateException> { completer }.message ) @Test fun performance() { fun client(server: Server) = object : Client() { override fun invoke(invocation: ClientInvocation) = invocation.invoke(false) { request -> server.invocation(true, request).invoke { reply -> invocation.settle(reply) } } } performance(client(Server(Service(calculatorId, CalculatorImpl)))) } }
bsd-3-clause
d7b2b14d7e9eab2d921e199a26cc577a
29.884462
119
0.62758
4.509599
false
false
false
false
atlarge-research/opendc-simulator
opendc-stdlib/src/main/kotlin/com/atlarge/opendc/simulator/instrumentation/Interpolation.kt
1
6069
/* * MIT License * * Copyright (c) 2017 atlarge-research * * 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.atlarge.opendc.simulator.instrumentation import kotlinx.coroutines.experimental.Unconfined import kotlinx.coroutines.experimental.channels.ReceiveChannel import kotlinx.coroutines.experimental.channels.consume import kotlinx.coroutines.experimental.channels.produce import kotlin.coroutines.experimental.CoroutineContext /** * Interpolate [n] amount of elements between every two occurrences of elements passing through the channel. * * The operation is _intermediate_ and _stateless_. * This function [consumes][consume] all elements of the original [ReceiveChannel]. * * @param n The amount of elements to interpolate between the actual elements in the channel. * @param context The context of the coroutine. * @param interpolator A function to interpolate between the two element occurrences. */ fun <E> ReceiveChannel<E>.interpolate(n: Int, context: CoroutineContext = Unconfined, interpolator: (Double, E, E) -> E): ReceiveChannel<E> { require(n >= 0) { "The amount to interpolate must be non-negative" } // Fast-path: if we do not want to interpolate any elements, just return the original channel if (n == 0) { return this } return interpolate(context, { _, _ -> n }, interpolator) } /** * Interpolate a dynamic amount of elements between every two occurrences of elements passing through the channel. * * The operation is _intermediate_ and _stateless_. * This function [consumes][consume] all elements of the original [ReceiveChannel]. * * @param context The context of the coroutine. * @param amount A function to compute the amount of elements to interpolate between the actual elements in the channel. * @param interpolator A function to interpolate between the two element occurrences. */ fun <E> ReceiveChannel<E>.interpolate(context: CoroutineContext = Unconfined, amount: (E, E) -> Int, interpolator: (Double, E, E) -> E): ReceiveChannel<E> { return produce(context) { consume { val iterator = iterator() if (!iterator.hasNext()) return@produce var a = iterator.next() send(a) while (iterator.hasNext()) { val b = iterator.next() val n = amount(a, b) for (i in 1..n) { send(interpolator(i.toDouble() / (n + 1), a, b)) } send(b) a = b } } } } /** * Perform a linear interpolation on the given double values. * * @param a The start value * @param b The end value * @param f The amount to interpolate which represents the position between the two values as a percentage in [0, 1]. * @return The interpolated double result between the double values. */ fun lerp(a: Double, b: Double, f: Double): Double = a + f * (b - a) /** * Perform a linear interpolation on the given float values. * * @param a The start value * @param b The end value * @param f The amount to interpolate which represents the position between the two values as a percentage in [0, 1]. * @return The interpolated float result between the float values. */ fun lerp(a: Float, b: Float, f: Float): Float = a + f * (b - a) /** * Perform a linear interpolation on the given integer values. * * @param a The start value * @param b The end value * @param f The amount to interpolate which represents the position between the two values as a percentage in [0, 1]. * @return The interpolated integer result between the integer values. */ fun lerp(a: Int, b: Int, f: Float): Int = lerp(a.toFloat(), b.toFloat(), f).toInt() /** * Perform a linear interpolation on the given integer values. * * @param a The start value * @param b The end value * @param f The amount to interpolate which represents the position between the two values as a percentage in [0, 1]. * @return The interpolated integer result between the integer values. */ fun lerp(a: Int, b: Int, f: Double): Int = lerp(a.toDouble(), b.toDouble(), f).toInt() /** * Perform a linear interpolation on the given long values. * * @param a The start value * @param b The end value * @param f The amount to interpolate which represents the position between the two values as a percentage in [0, 1]. * @return The interpolated long result between the long values. */ fun lerp(a: Long, b: Long, f: Double): Long = lerp(a.toDouble(), b.toDouble(), f).toLong() /** * Perform a linear interpolation on the given long values. * * @param a The start value * @param b The end value * @param f The amount to interpolate which represents the position between the two values as a percentage in [0, 1]. * @return The interpolated long result between the long values. */ fun lerp(a: Long, b: Long, f: Float): Long = lerp(a.toFloat(), b.toFloat(), f).toLong()
mit
d1dc13dd10bb50ee4e7d16c63e5fa30a
39.731544
120
0.686604
4.273944
false
false
false
false
koma-im/koma
src/main/kotlin/koma/gui/view/window/preferences/prefwindow.kt
1
1088
package koma.gui.view.window.preferences import javafx.geometry.Side import javafx.scene.Scene import javafx.scene.control.Tab import javafx.scene.control.TabPane import javafx.stage.Stage import javafx.stage.Window import koma.gui.view.window.preferences.tab.NetworkSettingsTab import koma.storage.persistence.settings.encoding.ProxyList import link.continuum.desktop.gui.VBox import link.continuum.desktop.gui.add class PreferenceWindow(proxyList: ProxyList) { val root = VBox() private val nettab = NetworkSettingsTab(this, proxyList) private val stage = Stage() fun close() { stage.close() } fun openModal(owner: Window) { stage.initOwner(owner) stage.scene = Scene(root) stage.show() } init { val tabs = TabPane() with(tabs) { this.tabClosingPolicy = TabPane.TabClosingPolicy.UNAVAILABLE this.side = Side.LEFT getTabs().addAll( Tab("Network", nettab.root) ) } with(root) { add(tabs) } } }
gpl-3.0
1a6ab20ba25769a4413198ff6464c5a7
24.904762
72
0.648897
3.927798
false
false
false
false
koma-im/koma
src/test/kotlin/link/continuum/desktop/gui/MiscKtTest.kt
1
2335
package link.continuum.desktop.gui import javafx.beans.property.SimpleObjectProperty import javafx.scene.Parent import javafx.scene.layout.StackPane as StackPaneJ import javafx.scene.paint.Color import javafx.scene.text.Text import kotlin.test.Test import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.assertThrows import kotlin.time.ExperimentalTime @ExperimentalTime internal class MiscKtTest { @Test fun testPropertyDelegate() { class Testing { val property = SimpleObjectProperty<Color> () var color by prop(property) } val t0 = Testing() assertEquals(null, t0.color) assertEquals(null, t0.property.get()) t0.color = Color.AQUAMARINE assertEquals(Color.AQUAMARINE, t0.property.get()) assertEquals(Color.AQUAMARINE, t0.color) t0.property.set(Color.CORNFLOWERBLUE) assertEquals(Color.CORNFLOWERBLUE, t0.property.get()) assertEquals(Color.CORNFLOWERBLUE, t0.color) } class ParentBoundsException: Exception() class BrokenParent(): Parent() { override fun updateBounds() { throw ParentBoundsException() } } class OutOfBoundsParent(): Parent() { var updateBoundsCount = 0 override fun updateBounds() { updateBoundsCount += 1 throw IndexOutOfBoundsException("testing-out-of-bounds") } } @Test fun callUpdateCachedBounds() { val h = StackPane() h.children.add(BrokenParent()) assertThrows<ParentBoundsException> { h.callUpdateBoundsReflectively() } val p = BrokenParent() val h1 = HBox().apply { children.add(p) } assertThrows<ParentBoundsException> { h1.callUpdateBoundsReflectively() } val p2 = OutOfBoundsParent() val h2 = HBox().apply { children.addAll(Text(), Text(), p2) } assertEquals(0, p2.updateBoundsCount) h2.callUpdateBoundsReflectively() val p3 = OutOfBoundsParent() val s = StackPaneJ().apply { children.add(p3) } val h3 = HBox().apply { children.add(s) } assertEquals(0, p3.updateBoundsCount) h3.callUpdateBoundsReflectively() val su = StackPaneJ(h3) } }
gpl-3.0
7c20c57570fe0b969dce1c6979777742
31
81
0.635974
4.184588
false
true
false
false
quran/quran_android
common/audio/src/main/java/com/quran/labs/androidquran/common/audio/util/QariUtil.kt
2
1137
package com.quran.labs.androidquran.common.audio.util import android.content.Context import com.quran.data.model.audio.Qari import com.quran.data.source.PageProvider import com.quran.labs.androidquran.common.audio.model.QariItem import javax.inject.Inject class QariUtil @Inject constructor(private val pageProvider: PageProvider) { /** * Get a list of all available qaris as [Qari]. * * Unlike the method with the context parameter, this version does not have * the actual qari name. It only has the resource id for the qari. */ fun getQariList(): List<Qari> { return pageProvider.getQaris() } /** * Get a list of all available qaris as [QariItem]s * * @param context the current context * @return a list of [QariItem] representing the qaris to show. */ fun getQariList(context: Context): List<QariItem> { return getQariList().map { item -> QariItem( id = item.id, name = context.getString(item.nameResource), url = item.url, path = item.path, hasGaplessAlternative = item.hasGaplessAlternative, db = item.db ) } } }
gpl-3.0
ae701e8b35caee489531c1e1f5bf9eba
28.153846
77
0.684257
3.880546
false
false
false
false
JetBrains/teamcity-azure-plugin
plugin-azure-server/src/main/kotlin/jetbrains/buildServer/clouds/azure/arm/types/AzureContainerHandler.kt
1
4543
/* * Copyright 2000-2021 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 jetbrains.buildServer.clouds.azure.arm.types import jetbrains.buildServer.clouds.azure.arm.AzureCloudImage import jetbrains.buildServer.clouds.azure.arm.AzureCloudImageDetails import jetbrains.buildServer.clouds.azure.arm.AzureCloudInstance import jetbrains.buildServer.clouds.azure.arm.AzureConstants import jetbrains.buildServer.clouds.azure.arm.connector.AzureApiConnector import jetbrains.buildServer.clouds.azure.arm.utils.ArmTemplateBuilder import jetbrains.buildServer.clouds.azure.arm.utils.AzureUtils import kotlinx.coroutines.coroutineScope import java.util.* class AzureContainerHandler(private val connector: AzureApiConnector) : AzureHandler { override suspend fun checkImage(image: AzureCloudImage) = coroutineScope { val exceptions = ArrayList<Throwable>() val details = image.imageDetails details.checkSourceId(exceptions) details.checkRegion(exceptions) details.checkOsType(exceptions) details.checkImageId(exceptions) details.checkResourceGroup(connector, exceptions) details.checkCustomEnvironmentVariables(exceptions) details.checkCustomTags(exceptions) details.checkServiceExistence("Microsoft.ContainerInstance", connector, exceptions) exceptions } override suspend fun prepareBuilder(instance: AzureCloudInstance) = coroutineScope { val details = instance.image.imageDetails val template = AzureUtils.getResourceAsString("/templates/container-template.json") val builder = ArmTemplateBuilder(template) builder.setParameterValue("containerName", instance.name) .setParameterValue(AzureConstants.IMAGE_ID, details.imageId!!.trim()) .setParameterValue(AzureConstants.OS_TYPE, details.osType!!) .setParameterValue(AzureConstants.NUMBER_CORES, details.numberCores!!) .setParameterValue(AzureConstants.MEMORY, details.memory!!) .addContainer(instance.name, parseEnvironmentVariables(details.customEnvironmentVariables)) .apply { if (!details.registryUsername.isNullOrEmpty() && !details.password.isNullOrEmpty()) { val server = getImageServer(details.imageId) addContainerCredentials(server, details.registryUsername.trim(), details.password!!.trim()) } if (!details.networkId.isNullOrEmpty() && !details.subnetId.isNullOrEmpty()) { setParameterValue("networkId", details.networkId) setParameterValue("subnetName", details.subnetId) addContainerNetwork() } } } override suspend fun getImageHash(details: AzureCloudImageDetails) = coroutineScope { Integer.toHexString(details.imageId!!.hashCode())!! } private fun getImageServer(imageId: String): String { return hostMatcher.find(imageId)?.let { val (server) = it.destructured server } ?: imageId } companion object { private val hostMatcher = Regex("^(?:https?:\\/\\/)?([^\\/]+)") fun parseEnvironmentVariables(rawString: String?): List<Pair<String, String>> { return if (rawString != null && rawString.isNotEmpty()) { rawString.lines().map { it.trim() }.filter { it.isNotEmpty() }.filter(AzureUtils::customEnvironmentVariableSyntaxIsValid).mapNotNull { val envVar = it val equalsSignIndex = envVar.indexOf("=") if (equalsSignIndex > 1) { Pair(envVar.substring(0, equalsSignIndex), envVar.substring(equalsSignIndex + 1)) } else { null } } } else { Collections.emptyList() } } } }
apache-2.0
f61c8e63d72157b6cfd8cf5471404c60
44.43
150
0.662778
5.104494
false
false
false
false
luhaoaimama1/JavaZone
JavaTest_Zone/src/ktxc/组合挂起.kt
1
1396
package ktxc import kotlinx.coroutines.* import kotlin.system.measureTimeMillis fun main() { runBlocking { // zuse() // noZuse() lazy() } } private suspend fun CoroutineScope.lazy() { //惰性的话 可以通过 start 或者await启动 不是直接启动 val one = async(start = CoroutineStart.LAZY) { doSomethingUsefulOne() } val two = async(start = CoroutineStart.LAZY) { doSomethingUsefulTwo() } // 执行一些计算 // two.start() // 启动第二个 // one.start() // 启动第一个 println("The answer is ${two.await() + one.await()}") } private suspend fun CoroutineScope.noZuse() { //非阻塞的 val one = async { doSomethingUsefulOne() } val two = async { doSomethingUsefulTwo() } println("The answer is~~~") println("The answer is ${one.await() + two.await()}") } private suspend fun zuse() { // 阻塞 val one = doSomethingUsefulOne() val two = doSomethingUsefulTwo() println("The answer is ${one + two}") } suspend fun doSomethingUsefulOne(): Int { println("doSomethingUsefulOne ") delay(1000L) // 假设我们在这里做了一些有用的事 println("13") return 13 } suspend fun doSomethingUsefulTwo(): Int { println("doSomethingUsefulTwo ") delay(1000L) // 假设我们在这里也做了一些有用的事 println("29") return 29 }
epl-1.0
6d34226d43b056fb49efa0f1f43b6ad5
23.134615
75
0.635566
3.454545
false
false
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/search/gene/sql/geometric/SqlPolygonGene.kt
1
7901
package org.evomaster.core.search.gene.sql.geometric import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType import org.evomaster.core.search.gene.* import org.evomaster.core.logging.LoggingUtil import org.evomaster.core.output.OutputFormat import org.evomaster.core.search.gene.collection.ArrayGene import org.evomaster.core.search.gene.root.CompositeFixedGene import org.evomaster.core.search.gene.utils.GeneUtils import org.evomaster.core.search.service.Randomness import org.evomaster.core.search.service.mutator.genemutation.AdditionalGeneMutationInfo import org.evomaster.core.search.service.mutator.genemutation.SubsetGeneMutationSelectionStrategy import org.slf4j.Logger import org.slf4j.LoggerFactory import java.awt.geom.Line2D /** * Represents a polygon (closed area). * It does not contain more than a single linestring. */ class SqlPolygonGene( name: String, val databaseType: DatabaseType = DatabaseType.POSTGRES, val minLengthOfPolygonRing: Int = 2, val onlyNonIntersectingPolygons: Boolean = false, val points: ArrayGene<SqlPointGene> = ArrayGene( name = "points", // polygons have at least 2 points minSize = minLengthOfPolygonRing, template = SqlPointGene("p", databaseType = databaseType)) ) : CompositeFixedGene(name, mutableListOf(points)) { companion object { val log: Logger = LoggerFactory.getLogger(SqlPolygonGene::class.java) } override fun copyContent(): Gene = SqlPolygonGene( name, minLengthOfPolygonRing = minLengthOfPolygonRing, onlyNonIntersectingPolygons = onlyNonIntersectingPolygons, points = points.copy() as ArrayGene<SqlPointGene>, databaseType = databaseType ) override fun randomize(randomness: Randomness, tryToForceNewValue: Boolean) { val pointList = mutableListOf<SqlPointGene>() repeat(minLengthOfPolygonRing) { val newGene = points.template.copy() as SqlPointGene pointList.add(newGene) do { newGene.randomize(randomness, tryToForceNewValue) } while (onlyNonIntersectingPolygons && !noCrossOvers(pointList)) } points.randomize(randomness, tryToForceNewValue) points.killAllChildren() pointList.map { points.addChild(it) } assert(isLocallyValid()) } /** * If [onlyNonIntersectingPolygons] is enabled, checks if the * linestring has an intersection by checking all segments * againts each other O(n^2) * Source: https://stackoverflow.com/questions/4876065/is-there-an-easy-and-fast-way-of-checking-if-a-polygon-is-self-intersecting */ override fun isLocallyValid(): Boolean { if (!onlyNonIntersectingPolygons) return true val pointList = points.getViewOfChildren() as List<SqlPointGene> return noCrossOvers(pointList) } /** * checks if the * linestring has an intersection by checking all segments * againts each other O(n^2) * Source: https://stackoverflow.com/questions/4876065/is-there-an-easy-and-fast-way-of-checking-if-a-polygon-is-self-intersecting */ private fun noCrossOvers(pointList: List<SqlPointGene>): Boolean { val len = pointList.size /* * No cross-over if len <= 3 */ if (len <= 3) { return true } for (i in 0 until (len - 1)) { for (j in (i + 2) until len) { /* * Eliminate combinations already checked * or not valid */ if ((i == 0) && (j == (len - 1))) { continue } val cut = Line2D.linesIntersect( pointList[i].x.value.toDouble(), pointList[i].y.value.toDouble(), pointList[i + 1].x.value.toDouble(), pointList[i + 1].y.value.toDouble(), pointList[j].x.value.toDouble(), pointList[j].y.value.toDouble(), pointList[(j + 1) % len].x.value.toDouble(), pointList[(j + 1) % len].y.value.toDouble()) if (cut) { return false } } } return true } override fun getValueAsPrintableString( previousGenes: List<Gene>, mode: GeneUtils.EscapeMode?, targetFormat: OutputFormat?, extraCheck: Boolean ): String { return when (databaseType) { DatabaseType.POSTGRES, DatabaseType.H2 -> "\"${getValueAsRawString()}\"" DatabaseType.MYSQL -> getValueAsRawString() else -> throw IllegalArgumentException("Unsupported SqlPolygonGene.getValueAsPrintableString() for ${databaseType}") } } override fun getValueAsRawString(): String { return when (databaseType) { /* * In MySQL, the first and the last point of * the polygon should be equal. We enforce * this by repeating the first point at the * end of the list */ DatabaseType.MYSQL -> { "POLYGON(LINESTRING(" + points.getViewOfElements() .joinToString(", ") { it.getValueAsRawString() } + ", " + points.getViewOfElements()[0].getValueAsRawString() + "))" } /* * In PostgreSQL, the (..) denotes a closed path */ DatabaseType.POSTGRES -> { "(${ points.getViewOfElements().joinToString(", ") { it.getValueAsRawString() } })" } /* * In H2, polygon's last point must be equal to * first point, we enforce that by repeating the * first point. */ DatabaseType.H2 -> { "POLYGON((${ points.getViewOfElements().joinToString(", ") { it.x.getValueAsRawString() + " " + it.y.getValueAsRawString() } + ", " + points.getViewOfElements()[0].x.getValueAsRawString() + " " + points.getViewOfElements()[0].y.getValueAsRawString() }))" } else -> throw IllegalArgumentException("Unsupported SqlPolygonGene.getValueAsRawString() for ${databaseType}") } } override fun copyValueFrom(other: Gene) { if (other !is SqlPolygonGene) { throw IllegalArgumentException("Invalid gene type ${other.javaClass}") } this.points.copyValueFrom(other.points) } override fun containsSameValueAs(other: Gene): Boolean { if (other !is SqlPolygonGene) { throw IllegalArgumentException("Invalid gene type ${other.javaClass}") } return this.points.containsSameValueAs(other.points) } override fun bindValueBasedOn(gene: Gene): Boolean { return when { gene is SqlPolygonGene -> { points.bindValueBasedOn(gene.points) } else -> { LoggingUtil.uniqueWarn(log, "cannot bind PathGene with ${gene::class.java.simpleName}") false } } } override fun customShouldApplyShallowMutation( randomness: Randomness, selectionStrategy: SubsetGeneMutationSelectionStrategy, enableAdaptiveGeneMutation: Boolean, additionalGeneMutationInfo: AdditionalGeneMutationInfo? ): Boolean { return false } }
lgpl-3.0
142a624ccc8a4e846c9f1a37a2de004b
35.753488
134
0.5798
5.077763
false
false
false
false
RSDT/Japp
app/src/main/java/nl/rsdt/japp/jotial/maps/wrapper/osm/OsmCircle.kt
2
1563
package nl.rsdt.japp.jotial.maps.wrapper.osm import com.google.android.gms.maps.model.CircleOptions import com.google.android.gms.maps.model.LatLng import nl.rsdt.japp.jotial.maps.wrapper.ICircle import org.osmdroid.util.GeoPoint import org.osmdroid.views.MapView import org.osmdroid.views.overlay.Polygon import java.util.* /** * Created by mattijn on 08/08/17. */ class OsmCircle(circleOptions: CircleOptions, private val osmMap: MapView) : ICircle { private val osmCircle: Polygon private val centre: LatLng override var fillColor: Int get() = osmCircle.fillColor set(color) { osmCircle.fillColor = color } init { osmCircle = Polygon() osmCircle.strokeWidth = circleOptions.strokeWidth osmCircle.fillColor = circleOptions.fillColor osmCircle.strokeColor = circleOptions.strokeColor val radius = circleOptions.radius this.centre = circleOptions.center this.setRadius(radius.toFloat()) osmMap.overlays.add(osmCircle) } override fun remove() { osmMap.overlays.remove(osmCircle) } override fun setRadius(radius: Float) { val nrOfPoints = 360 val circlePoints = ArrayList<GeoPoint>() for (f in 0 until nrOfPoints) { circlePoints.add(GeoPoint(centre.latitude, centre.longitude).destinationPoint(radius.toDouble(), f.toFloat())) } osmCircle.points = circlePoints } override fun setVisible(visible: Boolean) { osmCircle.isVisible = visible } }
apache-2.0
83f637ad8599dfe8de2ef7ed446118bf
27.944444
122
0.684581
4.156915
false
false
false
false
collave/workbench-android-common
library/src/main/kotlin/com/collave/workbench/common/android/component/preferences/StringPreference.kt
1
928
package com.collave.workbench.common.android.component.preferences import android.content.SharedPreferences import kotlin.reflect.KProperty /** * Created by Andrew on 6/6/2017. */ class StringPreference(val preferences: SharedPreferences, val propertyName: String? = null, val defaultValue: (()->String)? = null) { operator fun getValue(thisRef: Any?, property: KProperty<*>): String { val name = propertyName ?: property.name val value = preferences.getString(name, "") if (value.isEmpty() && defaultValue != null) { val newValue = defaultValue.invoke() preferences.edit().putString(name, newValue).apply() return newValue } return value } operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) { val name = propertyName ?: property.name preferences.edit().putString(name, value).apply() } }
gpl-3.0
c232cd9564840a5cecb99275e0e486e5
33.407407
134
0.662716
4.64
false
false
false
false
rostyslav-y/android-clean-architecture-boilerplate
mobile-ui/src/main/java/org/buffer/android/boilerplate/ui/browse/BrowseAdapter.kt
1
1748
package org.buffer.android.boilerplate.ui.browse import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import org.buffer.android.boilerplate.ui.R import org.buffer.android.boilerplate.ui.model.BufferooViewModel import javax.inject.Inject class BrowseAdapter @Inject constructor(): RecyclerView.Adapter<BrowseAdapter.ViewHolder>() { var bufferoos: List<BufferooViewModel> = arrayListOf() override fun onBindViewHolder(holder: ViewHolder, position: Int) { val bufferoo = bufferoos[position] holder.nameText.text = bufferoo.name holder.titleText.text = bufferoo.title Glide.with(holder.itemView.context) .load(bufferoo.avatar) .apply(RequestOptions.circleCropTransform()) .into(holder.avatarImage) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val itemView = LayoutInflater .from(parent.context) .inflate(R.layout.item_bufferoo, parent, false) return ViewHolder(itemView) } override fun getItemCount(): Int { return bufferoos.size } inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { var avatarImage: ImageView var nameText: TextView var titleText: TextView init { avatarImage = view.findViewById(R.id.image_avatar) nameText = view.findViewById(R.id.text_name) titleText = view.findViewById(R.id.text_title) } } }
mit
303e51c1f533f1abef066d74e72bdfbf
32
93
0.697368
4.575916
false
false
false
false
ratedali/EEESE-android
app/src/main/java/edu/uofk/eeese/eeese/data/source/ProjectsRepository.kt
1
4147
/* * Copyright 2017 Ali Salah Alddin * * 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 edu.uofk.eeese.eeese.data.source import android.content.Context import com.squareup.sqlbrite.SqlBrite import edu.uofk.eeese.eeese.data.DataContract.ProjectEntry import edu.uofk.eeese.eeese.data.DataUtils.Projects import edu.uofk.eeese.eeese.data.Project import edu.uofk.eeese.eeese.data.sync.SyncManager import hu.akarnokd.rxjava.interop.RxJavaInterop import io.reactivex.Completable import io.reactivex.Observable import io.reactivex.schedulers.Schedulers as V2Schedulers import rx.schedulers.Schedulers as V1Schedulers class ProjectsRepository(context: Context, private val syncManager: SyncManager) : Repository<Project> { companion object { private val TAG = ProjectsRepository::class.java.name } private val resolver = context.contentResolver private val sqlBrite = SqlBrite.Builder().build() private val briteResolver = sqlBrite.wrapContentProvider(resolver, V1Schedulers.io()) override fun getOne(spec: Specification): Observable<Project> { val (selection, selectionArgs) = (spec as ContentProviderSpecification).toSelectionQuery() return RxJavaInterop.toV2Observable( briteResolver.createQuery(ProjectEntry.CONTENT_URI, null, selection, selectionArgs, null, false)) .map { it.run()!! } .map { Projects.project(it) } } override fun get(spec: Specification): Observable<List<Project>> { val (selection, selectionArgs) = (spec as ContentProviderSpecification).toSelectionQuery() return RxJavaInterop.toV2Observable( briteResolver.createQuery(ProjectEntry.CONTENT_URI, null, selection, selectionArgs, null, false)) .map { it.run()!! } .map { Projects.projects(it) } } override fun get(): Observable<List<Project>> = RxJavaInterop.toV2Observable( briteResolver.createQuery(ProjectEntry.CONTENT_URI, null, null, null, null, false)) .map { it.run()!! } .map { Projects.projects(it) } override fun add(event: Project): Completable = Completable.fromAction { resolver.insert(ProjectEntry.CONTENT_URI, Projects.values(event)) } override fun addAll(events: Iterable<Project>): Completable = Completable.fromAction { val contentValues = events.map { Projects.values(it) }.toTypedArray() resolver.bulkInsert(ProjectEntry.CONTENT_URI, contentValues) } override fun delete(spec: Specification): Completable { val (selection, selectionArgs) = (spec as ContentProviderSpecification).toSelectionQuery() return Completable.fromAction { resolver.delete(ProjectEntry.CONTENT_URI, selection, selectionArgs) } } override fun clear(): Completable = Completable.fromAction { resolver.delete(ProjectEntry.CONTENT_URI, null, null) } override fun sync(): Completable = Completable.fromAction { syncManager.syncNow() } }
mit
5a010a79446331d732e9364206f27f5d
48.369048
463
0.711358
4.744851
false
false
false
false
xCatG/android-UniversalMusicPlayer
app/src/main/java/com/example/android/uamp/fragments/NowPlayingFragment.kt
1
4186
/* * Copyright 2019 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.uamp.fragments import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.bumptech.glide.Glide import com.example.android.uamp.R import com.example.android.uamp.databinding.FragmentNowplayingBinding import com.example.android.uamp.utils.InjectorUtils import com.example.android.uamp.viewmodels.MainActivityViewModel import com.example.android.uamp.viewmodels.NowPlayingFragmentViewModel import com.example.android.uamp.viewmodels.NowPlayingFragmentViewModel.NowPlayingMetadata /** * A fragment representing the current media item being played. */ class NowPlayingFragment : Fragment() { private lateinit var mainActivityViewModel: MainActivityViewModel private lateinit var nowPlayingViewModel: NowPlayingFragmentViewModel lateinit var binding: FragmentNowplayingBinding companion object { fun newInstance() = NowPlayingFragment() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentNowplayingBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Always true, but lets lint know that as well. val context = activity ?: return // Inject our activity and view models into this fragment mainActivityViewModel = ViewModelProviders .of(context, InjectorUtils.provideMainActivityViewModel(context)) .get(MainActivityViewModel::class.java) nowPlayingViewModel = ViewModelProviders .of(context, InjectorUtils.provideNowPlayingFragmentViewModel(context)) .get(NowPlayingFragmentViewModel::class.java) // Attach observers to the LiveData coming from this ViewModel nowPlayingViewModel.mediaMetadata.observe(this, Observer { mediaItem -> updateUI(view, mediaItem) }) nowPlayingViewModel.mediaButtonRes.observe(this, Observer { res -> binding.mediaButton.setImageResource(res) }) nowPlayingViewModel.mediaPosition.observe(this, Observer { pos -> binding.position.text = NowPlayingMetadata.timestampToMSS(context, pos) }) // Setup UI handlers for buttons binding.mediaButton.setOnClickListener { nowPlayingViewModel.mediaMetadata.value?.let { mainActivityViewModel.playMediaId(it.id) } } // Initialize playback duration and position to zero binding.duration.text = NowPlayingMetadata.timestampToMSS(context, 0L) binding.position.text = NowPlayingMetadata.timestampToMSS(context, 0L) } /** * Internal function used to update all UI elements except for the current item playback */ private fun updateUI(view: View, metadata: NowPlayingMetadata) = with(binding) { if (metadata.albumArtUri == Uri.EMPTY) { albumArt.setImageResource(R.drawable.ic_album_black_24dp) } else { Glide.with(view) .load(metadata.albumArtUri) .into(albumArt) } title.text = metadata.title subtitle.text = metadata.subtitle duration.text = metadata.duration } }
apache-2.0
0566d109bb5b4a3c3921313498bdf447
38.121495
101
0.716197
4.942149
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-block-logging-bukkit/src/main/kotlin/com/rpkit/blocklog/bukkit/listener/InventoryDragListener.kt
1
3447
/* * Copyright 2020 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.blocklog.bukkit.listener import com.rpkit.blocklog.bukkit.RPKBlockLoggingBukkit import com.rpkit.blocklog.bukkit.block.RPKBlockHistoryService import com.rpkit.blocklog.bukkit.block.RPKBlockInventoryChangeImpl import com.rpkit.characters.bukkit.character.RPKCharacterService import com.rpkit.core.bukkit.location.toRPKBlockLocation import com.rpkit.core.service.Services import com.rpkit.players.bukkit.profile.RPKProfile import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService import org.bukkit.block.BlockState import org.bukkit.entity.Player import org.bukkit.event.EventHandler import org.bukkit.event.EventPriority.MONITOR import org.bukkit.event.Listener import org.bukkit.event.inventory.InventoryDragEvent import org.bukkit.scheduler.BukkitRunnable import java.time.LocalDateTime class InventoryDragListener(private val plugin: RPKBlockLoggingBukkit) : Listener { @EventHandler(priority = MONITOR) fun onInventoryDrag(event: InventoryDragEvent) { val blockHistoryService = Services[RPKBlockHistoryService::class.java] ?: return val inventoryHolder = event.inventory.holder if (inventoryHolder !is BlockState) return val whoClicked = event.whoClicked if (whoClicked !is Player) return val oldContents = event.inventory.contents object : BukkitRunnable() { override fun run() { val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return val characterService = Services[RPKCharacterService::class.java] ?: return val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(whoClicked) val profile = minecraftProfile?.profile as? RPKProfile val character = if (minecraftProfile == null) null else characterService.getPreloadedActiveCharacter(minecraftProfile) blockHistoryService.getBlockHistory(inventoryHolder.block.toRPKBlockLocation()).thenAccept { blockHistory -> val blockInventoryChange = RPKBlockInventoryChangeImpl( blockHistory = blockHistory, time = LocalDateTime.now(), profile = profile, minecraftProfile = minecraftProfile, character = character, from = oldContents, to = event.inventory.contents, reason = "DRAG" ) plugin.server.scheduler.runTask(plugin, Runnable { blockHistoryService.addBlockInventoryChange(blockInventoryChange) }) } } }.runTaskLater(plugin, 1L) // Scheduled 1 tick later to allow inventory change to take place. } }
apache-2.0
2e02986bccb4c169f91f014ba5a87461
46.875
134
0.697418
5.183459
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-monsters-bukkit/src/main/kotlin/com/rpkit/monsters/bukkit/listener/CreatureSpawnListener.kt
1
2984
/* * Copyright 2020 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.monsters.bukkit.listener import com.rpkit.core.service.Services import com.rpkit.monsters.bukkit.RPKMonstersBukkit import com.rpkit.monsters.bukkit.monsterlevel.RPKMonsterLevelService import com.rpkit.monsters.bukkit.monsterspawnarea.RPKMonsterSpawnAreaService import com.rpkit.monsters.bukkit.monsterstat.RPKMonsterStatServiceImpl import org.bukkit.attribute.Attribute import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.entity.CreatureSpawnEvent class CreatureSpawnListener(private val plugin: RPKMonstersBukkit) : Listener { @EventHandler fun onCreatureSpawn(event: CreatureSpawnEvent) { val monster = event.entity if (plugin.config.getBoolean("monsters.${event.entityType}.ignored", plugin.config.getBoolean("monsters.default.ignored"))) { return } val monsterSpawnAreaService = Services[RPKMonsterSpawnAreaService::class.java] ?: return val spawnArea = monsterSpawnAreaService.getSpawnArea(event.location) if (spawnArea == null) { event.isCancelled = true return } if (!spawnArea.allowedMonsters.contains(event.entityType)) { event.isCancelled = true return } val monsterLevelService = Services[RPKMonsterLevelService::class.java] ?: return val monsterStatService = Services[RPKMonsterStatServiceImpl::class.java] ?: return val level = monsterLevelService.getMonsterLevel(monster) val health = monsterStatService.calculateMonsterMaxHealth(event.entityType, level) val maxHealthInstance = event.entity.getAttribute(Attribute.GENERIC_MAX_HEALTH) val calculatedHealth = if (maxHealthInstance != null) { maxHealthInstance.baseValue = health event.entity.health = maxHealthInstance.value maxHealthInstance.value } else { health } val minDamage = monsterStatService.calculateMonsterMinDamageMultiplier(event.entityType, level) val maxDamage = monsterStatService.calculateMonsterMaxDamageMultiplier(event.entityType, level) monsterStatService.setMonsterNameplate( monster, level, calculatedHealth, calculatedHealth, minDamage, maxDamage ) } }
apache-2.0
2dd94580382cb81ac2a881d3b1007939
40.458333
133
0.710791
4.805153
false
false
false
false
hea3ven/Malleable
src/main/java/com/hea3ven/malleable/block/BlockMetalFurnace.kt
1
1825
package com.hea3ven.malleable.block import com.hea3ven.malleable.ModMetals import com.hea3ven.malleable.block.tileentity.TileMetalFurnace import com.hea3ven.tools.commonutils.block.base.BlockMachine import com.hea3ven.tools.commonutils.block.metadata.MetadataManagerBuilder import net.minecraft.block.BlockFurnace import net.minecraft.block.SoundType import net.minecraft.block.material.Material import net.minecraft.block.properties.PropertyBool import net.minecraft.block.state.BlockStateContainer import net.minecraft.block.state.IBlockState import net.minecraft.entity.EntityLivingBase import net.minecraft.util.EnumFacing import net.minecraft.util.math.BlockPos import net.minecraft.world.World class BlockMetalFurnace : BlockMachine(Material.ROCK, ModMetals.MODID, ModMetals.guiIdMetalFurnace) { init { soundType = SoundType.STONE defaultState = blockState.baseState .withProperty(BlockFurnace.FACING, EnumFacing.NORTH) .withProperty(LIT, false) } val metaManager = MetadataManagerBuilder(this).map(2, BlockFurnace.FACING).map(1, LIT).build() override fun createNewTileEntity(worldIn: World, meta: Int) = TileMetalFurnace() override fun createBlockState() = BlockStateContainer(this, BlockFurnace.FACING, LIT) override fun getMetaFromState(state: IBlockState) = metaManager.getMeta(state) override fun getStateFromMeta(meta: Int) = metaManager.getState(meta) override fun onBlockPlaced(worldIn: World, pos: BlockPos, facing: EnumFacing, hitX: Float, hitY: Float, hitZ: Float, meta: Int, placer: EntityLivingBase): IBlockState? { return defaultState .withProperty(BlockFurnace.FACING, placer.getHorizontalFacing().getOpposite()) } override fun getLightValue(state: IBlockState) = if (state.getValue(LIT)) 13 else 0 companion object { val LIT = PropertyBool.create("lit") } }
mit
3f32926d0a1d74c2e9551393460c7d8e
37.041667
104
0.808219
3.747433
false
false
false
false
itachi1706/CheesecakeUtilities
app/src/main/java/com/itachi1706/cheesecakeutilities/modules/barcodeTools/objects/BarcodeHistoryScan.kt
1
1109
package com.itachi1706.cheesecakeutilities.modules.barcodeTools.objects import com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode /** * Created by Kenneth on 15/1/2020. * for com.itachi1706.cheesecakeutilities.modules.barcodeTools.objects in CheesecakeUtilities */ data class BarcodeHistoryScan(val barcodeValue:String = "", val rawBarcodeValue: String = "", val format: Int = FirebaseVisionBarcode.FORMAT_ALL_FORMATS, val valueType: Int = FirebaseVisionBarcode.TYPE_UNKNOWN, val email: FirebaseVisionBarcode.Email? = null, val phone: FirebaseVisionBarcode.Phone? = null, val sms: FirebaseVisionBarcode.Sms? = null, val wifi: FirebaseVisionBarcode.WiFi? = null, val url: FirebaseVisionBarcode.UrlBookmark? = null, val geoPoint: FirebaseVisionBarcode.GeoPoint? = null, val calendarEvent: FirebaseVisionBarcode.CalendarEvent? = null, val contactInfo: FirebaseVisionBarcode.ContactInfo? = null, val driverLicense: FirebaseVisionBarcode.DriverLicense? = null) : BarcodeHistory()
mit
f71262695bc106aac8e96fe97f9a754f
84.307692
199
0.724076
4.821739
false
false
false
false
cketti/k-9
backend/imap/src/main/java/com/fsck/k9/backend/imap/ImapFolderPusher.kt
1
3123
package com.fsck.k9.backend.imap import com.fsck.k9.logging.Timber import com.fsck.k9.mail.power.PowerManager import com.fsck.k9.mail.store.imap.IdleRefreshManager import com.fsck.k9.mail.store.imap.IdleRefreshTimeoutProvider import com.fsck.k9.mail.store.imap.IdleResult import com.fsck.k9.mail.store.imap.ImapFolderIdler import com.fsck.k9.mail.store.imap.ImapStore import kotlin.concurrent.thread /** * Listens for changes to an IMAP folder in a dedicated thread. */ class ImapFolderPusher( private val imapStore: ImapStore, private val powerManager: PowerManager, private val idleRefreshManager: IdleRefreshManager, private val callback: ImapPusherCallback, private val accountName: String, private val folderServerId: String, private val idleRefreshTimeoutProvider: IdleRefreshTimeoutProvider ) { @Volatile private var folderIdler: ImapFolderIdler? = null @Volatile private var stopPushing = false fun start() { Timber.v("Starting ImapFolderPusher for %s / %s", accountName, folderServerId) thread(name = "ImapFolderPusher-$accountName-$folderServerId") { Timber.v("Starting ImapFolderPusher thread for %s / %s", accountName, folderServerId) runPushLoop() Timber.v("Exiting ImapFolderPusher thread for %s / %s", accountName, folderServerId) } } fun refresh() { Timber.v("Refreshing ImapFolderPusher for %s / %s", accountName, folderServerId) folderIdler?.refresh() } fun stop() { Timber.v("Stopping ImapFolderPusher for %s / %s", accountName, folderServerId) stopPushing = true folderIdler?.stop() } private fun runPushLoop() { val wakeLock = powerManager.newWakeLock("ImapFolderPusher-$accountName-$folderServerId") wakeLock.acquire() performInitialSync() val folderIdler = ImapFolderIdler.create( idleRefreshManager, wakeLock, imapStore, folderServerId, idleRefreshTimeoutProvider ).also { folderIdler = it } try { while (!stopPushing) { when (folderIdler.idle()) { IdleResult.SYNC -> { callback.onPushEvent(folderServerId) } IdleResult.STOPPED -> { // ImapFolderIdler only stops when we ask it to. // But it can't hurt to make extra sure we exit the loop. stopPushing = true } IdleResult.NOT_SUPPORTED -> { stopPushing = true callback.onPushNotSupported() } } } } catch (e: Exception) { Timber.v(e, "Exception in ImapFolderPusher") this.folderIdler = null callback.onPushError(folderServerId, e) } wakeLock.release() } private fun performInitialSync() { callback.onPushEvent(folderServerId) } }
apache-2.0
15dd4eff9b2a7acea0a5eb491a8c5a7c
29.920792
97
0.607749
4.67515
false
false
false
false
coil-kt/coil
coil-base/src/main/java/coil/disk/DiskLruCache.kt
1
30538
/* * Copyright (C) 2011 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 coil.disk import androidx.annotation.VisibleForTesting import coil.util.createFile import coil.util.deleteContents import coil.util.forEachIndices import java.io.Flushable import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import okio.BufferedSink import okio.Closeable import okio.EOFException import okio.FileSystem import okio.ForwardingFileSystem import okio.IOException import okio.Path import okio.Sink import okio.blackholeSink import okio.buffer /** * A cache that uses a bounded amount of space on a filesystem. Each cache entry has a string key * and a fixed number of values. Each key must match the regex `[a-z0-9_-]{1,64}`. Values are byte * sequences, accessible as streams or files. Each value must be between `0` and `Int.MAX_VALUE` * bytes in length. * * The cache stores its data in a directory on the filesystem. This directory must be exclusive to * the cache; the cache may delete or overwrite files from its directory. It is an error for * multiple processes to use the same cache directory at the same time. * * This cache limits the number of bytes that it will store on the filesystem. When the number of * stored bytes exceeds the limit, the cache will remove entries in the background until the limit * is satisfied. The limit is not strict: the cache may temporarily exceed it while waiting for * files to be deleted. The limit does not include filesystem overhead or the cache journal so * space-sensitive applications should set a conservative limit. * * Clients call [edit] to create or update the values of an entry. An entry may have only one editor * at one time; if a value is not available to be edited then [edit] will return null. * * * When an entry is being **created** it is necessary to supply a full set of values; the empty * value should be used as a placeholder if necessary. * * * When an entry is being **edited**, it is not necessary to supply data for every value; values * default to their previous value. * * Every [edit] call must be matched by a call to [Editor.commit] or [Editor.abort]. Committing is * atomic: a read observes the full set of values as they were before or after the commit, but never * a mix of values. * * Clients call [get] to read a snapshot of an entry. The read will observe the value at the time * that [get] was called. Updates and removals after the call do not impact ongoing reads. * * This class is tolerant of some I/O errors. If files are missing from the filesystem, the * corresponding entries will be dropped from the cache. If an error occurs while writing a cache * value, the edit will fail silently. Callers should handle other problems by catching * `IOException` and responding appropriately. * * @constructor Create a cache which will reside in [directory]. This cache is lazily initialized on * first access and will be created if it does not exist. * @param directory a writable directory. * @param cleanupDispatcher the dispatcher to run cache size trim operations on. * @param valueCount the number of values per cache entry. Must be positive. * @param maxSize the maximum number of bytes this cache should use to store. */ @OptIn(ExperimentalCoroutinesApi::class) internal class DiskLruCache( fileSystem: FileSystem, private val directory: Path, cleanupDispatcher: CoroutineDispatcher, private val maxSize: Long, private val appVersion: Int, private val valueCount: Int, ) : Closeable, Flushable { /* * This cache uses a journal file named "journal". A typical journal file looks like this: * * libcore.io.DiskLruCache * 1 * 100 * 2 * * CLEAN 3400330d1dfc7f3f7f4b8d4d803dfcf6 832 21054 * DIRTY 335c4c6028171cfddfbaae1a9c313c52 * CLEAN 335c4c6028171cfddfbaae1a9c313c52 3934 2342 * REMOVE 335c4c6028171cfddfbaae1a9c313c52 * DIRTY 1ab96a171faeeee38496d8b330771a7a * CLEAN 1ab96a171faeeee38496d8b330771a7a 1600 234 * READ 335c4c6028171cfddfbaae1a9c313c52 * READ 3400330d1dfc7f3f7f4b8d4d803dfcf6 * * The first five lines of the journal form its header. They are the constant string * "libcore.io.DiskLruCache", the disk cache's version, the application's version, the value * count, and a blank line. * * Each of the subsequent lines in the file is a record of the state of a cache entry. Each line * contains space-separated values: a state, a key, and optional state-specific values. * * o DIRTY lines track that an entry is actively being created or updated. Every successful * DIRTY action should be followed by a CLEAN or REMOVE action. DIRTY lines without a matching * CLEAN or REMOVE indicate that temporary files may need to be deleted. * * o CLEAN lines track a cache entry that has been successfully published and may be read. A * publish line is followed by the lengths of each of its values. * * o READ lines track accesses for LRU. * * o REMOVE lines track entries that have been deleted. * * The journal file is appended to as cache operations occur. The journal may occasionally be * compacted by dropping redundant lines. A temporary file named "journal.tmp" will be used during * compaction; that file should be deleted if it exists when the cache is opened. */ init { require(maxSize > 0L) { "maxSize <= 0" } require(valueCount > 0) { "valueCount <= 0" } } private val journalFile = directory / JOURNAL_FILE private val journalFileTmp = directory / JOURNAL_FILE_TMP private val journalFileBackup = directory / JOURNAL_FILE_BACKUP private val lruEntries = LinkedHashMap<String, Entry>(0, 0.75f, true) private val cleanupScope = CoroutineScope(SupervisorJob() + cleanupDispatcher.limitedParallelism(1)) private var size = 0L private var operationsSinceRewrite = 0 private var journalWriter: BufferedSink? = null private var hasJournalErrors = false private var initialized = false private var closed = false private var mostRecentTrimFailed = false private var mostRecentRebuildFailed = false private val fileSystem = object : ForwardingFileSystem(fileSystem) { override fun sink(file: Path, mustCreate: Boolean): Sink { // Ensure the parent directory exists. file.parent?.let(::createDirectories) return super.sink(file, mustCreate) } } @Synchronized fun initialize() { if (initialized) return // If a temporary file exists, delete it. fileSystem.delete(journalFileTmp) // If a backup file exists, use it instead. if (fileSystem.exists(journalFileBackup)) { // If journal file also exists just delete backup file. if (fileSystem.exists(journalFile)) { fileSystem.delete(journalFileBackup) } else { fileSystem.atomicMove(journalFileBackup, journalFile) } } // Prefer to pick up where we left off. if (fileSystem.exists(journalFile)) { try { readJournal() processJournal() initialized = true return } catch (_: IOException) { // The journal is corrupt. } // The cache is corrupted; attempt to delete the contents of the directory. // This can throw and we'll let that propagate out as it likely means there // is a severe filesystem problem. try { delete() } finally { closed = false } } writeJournal() initialized = true } /** * Reads the journal and initializes [lruEntries]. */ private fun readJournal() { fileSystem.read(journalFile) { val magic = readUtf8LineStrict() val version = readUtf8LineStrict() val appVersionString = readUtf8LineStrict() val valueCountString = readUtf8LineStrict() val blank = readUtf8LineStrict() if (MAGIC != magic || VERSION != version || appVersion.toString() != appVersionString || valueCount.toString() != valueCountString || blank.isNotEmpty() ) { throw IOException("unexpected journal header: " + "[$magic, $version, $appVersionString, $valueCountString, $blank]") } var lineCount = 0 while (true) { try { readJournalLine(readUtf8LineStrict()) lineCount++ } catch (_: EOFException) { break // End of journal. } } operationsSinceRewrite = lineCount - lruEntries.size // If we ended on a truncated line, rebuild the journal before appending to it. if (!exhausted()) { writeJournal() } else { journalWriter = newJournalWriter() } } } private fun newJournalWriter(): BufferedSink { val fileSink = fileSystem.appendingSink(journalFile) val faultHidingSink = FaultHidingSink(fileSink) { hasJournalErrors = true } return faultHidingSink.buffer() } private fun readJournalLine(line: String) { val firstSpace = line.indexOf(' ') if (firstSpace == -1) throw IOException("unexpected journal line: $line") val keyBegin = firstSpace + 1 val secondSpace = line.indexOf(' ', keyBegin) val key: String if (secondSpace == -1) { key = line.substring(keyBegin) if (firstSpace == REMOVE.length && line.startsWith(REMOVE)) { lruEntries.remove(key) return } } else { key = line.substring(keyBegin, secondSpace) } val entry = lruEntries.getOrPut(key) { Entry(key) } when { secondSpace != -1 && firstSpace == CLEAN.length && line.startsWith(CLEAN) -> { val parts = line.substring(secondSpace + 1).split(' ') entry.readable = true entry.currentEditor = null entry.setLengths(parts) } secondSpace == -1 && firstSpace == DIRTY.length && line.startsWith(DIRTY) -> { entry.currentEditor = Editor(entry) } secondSpace == -1 && firstSpace == READ.length && line.startsWith(READ) -> { // This work was already done by calling lruEntries.get(). } else -> throw IOException("unexpected journal line: $line") } } /** * Computes the current size and collects garbage as a part of initializing the cache. * Dirty entries are assumed to be inconsistent and will be deleted. */ private fun processJournal() { var size = 0L val iterator = lruEntries.values.iterator() while (iterator.hasNext()) { val entry = iterator.next() if (entry.currentEditor == null) { for (i in 0 until valueCount) { size += entry.lengths[i] } } else { entry.currentEditor = null for (i in 0 until valueCount) { fileSystem.delete(entry.cleanFiles[i]) fileSystem.delete(entry.dirtyFiles[i]) } iterator.remove() } } this.size = size } /** * Writes [lruEntries] to a new journal file. This replaces the current journal if it exists. */ @Synchronized private fun writeJournal() { journalWriter?.close() fileSystem.write(journalFileTmp) { writeUtf8(MAGIC).writeByte('\n'.code) writeUtf8(VERSION).writeByte('\n'.code) writeDecimalLong(appVersion.toLong()).writeByte('\n'.code) writeDecimalLong(valueCount.toLong()).writeByte('\n'.code) writeByte('\n'.code) for (entry in lruEntries.values) { if (entry.currentEditor != null) { writeUtf8(DIRTY) writeByte(' '.code) writeUtf8(entry.key) writeByte('\n'.code) } else { writeUtf8(CLEAN) writeByte(' '.code) writeUtf8(entry.key) entry.writeLengths(this) writeByte('\n'.code) } } } if (fileSystem.exists(journalFile)) { fileSystem.atomicMove(journalFile, journalFileBackup) fileSystem.atomicMove(journalFileTmp, journalFile) fileSystem.delete(journalFileBackup) } else { fileSystem.atomicMove(journalFileTmp, journalFile) } journalWriter = newJournalWriter() operationsSinceRewrite = 0 hasJournalErrors = false mostRecentRebuildFailed = false } /** * Returns a snapshot of the entry named [key], or null if it doesn't exist or is not currently * readable. If a value is returned, it is moved to the head of the LRU queue. */ @Synchronized operator fun get(key: String): Snapshot? { checkNotClosed() validateKey(key) initialize() val snapshot = lruEntries[key]?.snapshot() ?: return null operationsSinceRewrite++ journalWriter!!.apply { writeUtf8(READ) writeByte(' '.code) writeUtf8(key) writeByte('\n'.code) } if (journalRewriteRequired()) { launchCleanup() } return snapshot } /** Returns an editor for the entry named [key], or null if another edit is in progress. */ @Synchronized fun edit(key: String): Editor? { checkNotClosed() validateKey(key) initialize() var entry = lruEntries[key] if (entry?.currentEditor != null) { return null // Another edit is in progress. } if (entry != null && entry.lockingSnapshotCount != 0) { return null // We can't write this file because a reader is still reading it. } if (mostRecentTrimFailed || mostRecentRebuildFailed) { // The OS has become our enemy! If the trim job failed, it means we are storing more // data than requested by the user. Do not allow edits so we do not go over that limit // any further. If the journal rebuild failed, the journal writer will not be active, // meaning we will not be able to record the edit, causing file leaks. In both cases, // we want to retry the clean up so we can get out of this state! launchCleanup() return null } // Flush the journal before creating files to prevent file leaks. journalWriter!!.apply { writeUtf8(DIRTY) writeByte(' '.code) writeUtf8(key) writeByte('\n'.code) flush() } if (hasJournalErrors) { return null // Don't edit; the journal can't be written. } if (entry == null) { entry = Entry(key) lruEntries[key] = entry } val editor = Editor(entry) entry.currentEditor = editor return editor } /** * Returns the number of bytes currently being used to store the values in this cache. * This may be greater than the max size if a background deletion is pending. */ @Synchronized fun size(): Long { initialize() return size } @Synchronized private fun completeEdit(editor: Editor, success: Boolean) { val entry = editor.entry check(entry.currentEditor == editor) if (success && !entry.zombie) { // Ensure all files that have been written to have an associated dirty file. for (i in 0 until valueCount) { if (editor.written[i] && !fileSystem.exists(entry.dirtyFiles[i])) { editor.abort() return } } // Replace the clean files with the dirty ones. for (i in 0 until valueCount) { val dirty = entry.dirtyFiles[i] val clean = entry.cleanFiles[i] if (fileSystem.exists(dirty)) { fileSystem.atomicMove(dirty, clean) } else { // Ensure every entry is complete. fileSystem.createFile(entry.cleanFiles[i]) } val oldLength = entry.lengths[i] val newLength = fileSystem.metadata(clean).size ?: 0 entry.lengths[i] = newLength size = size - oldLength + newLength } } else { // Discard any dirty files. for (i in 0 until valueCount) { fileSystem.delete(entry.dirtyFiles[i]) } } entry.currentEditor = null if (entry.zombie) { removeEntry(entry) return } operationsSinceRewrite++ journalWriter!!.apply { if (success || entry.readable) { entry.readable = true writeUtf8(CLEAN) writeByte(' '.code) writeUtf8(entry.key) entry.writeLengths(this) writeByte('\n'.code) } else { lruEntries.remove(entry.key) writeUtf8(REMOVE) writeByte(' '.code) writeUtf8(entry.key) writeByte('\n'.code) } flush() } if (size > maxSize || journalRewriteRequired()) { launchCleanup() } } /** * We rewrite [lruEntries] to the on-disk journal after a sufficient number of operations. */ private fun journalRewriteRequired() = operationsSinceRewrite >= 2000 /** * Drops the entry for [key] if it exists and can be removed. If the entry for [key] is * currently being edited, that edit will complete normally but its value will not be stored. * * @return true if an entry was removed. */ @Synchronized fun remove(key: String): Boolean { checkNotClosed() validateKey(key) initialize() val entry = lruEntries[key] ?: return false val removed = removeEntry(entry) if (removed && size <= maxSize) mostRecentTrimFailed = false return removed } private fun removeEntry(entry: Entry): Boolean { // If we can't delete files that are still open, mark this entry as a zombie so its files // will be deleted when those files are closed. if (entry.lockingSnapshotCount > 0) { // Mark this entry as 'DIRTY' so that if the process crashes this entry won't be used. journalWriter?.apply { writeUtf8(DIRTY) writeByte(' '.code) writeUtf8(entry.key) writeByte('\n'.code) flush() } } if (entry.lockingSnapshotCount > 0 || entry.currentEditor != null) { entry.zombie = true return true } for (i in 0 until valueCount) { fileSystem.delete(entry.cleanFiles[i]) size -= entry.lengths[i] entry.lengths[i] = 0 } operationsSinceRewrite++ journalWriter?.apply { writeUtf8(REMOVE) writeByte(' '.code) writeUtf8(entry.key) writeByte('\n'.code) } lruEntries.remove(entry.key) if (journalRewriteRequired()) { launchCleanup() } return true } private fun checkNotClosed() { check(!closed) { "cache is closed" } } /** Closes this cache. Stored values will remain on the filesystem. */ @Synchronized override fun close() { if (!initialized || closed) { closed = true return } // Copying for concurrent iteration. for (entry in lruEntries.values.toTypedArray()) { // Prevent the edit from completing normally. entry.currentEditor?.detach() } trimToSize() cleanupScope.cancel() journalWriter!!.close() journalWriter = null closed = true } @Synchronized override fun flush() { if (!initialized) return checkNotClosed() trimToSize() journalWriter!!.flush() } private fun trimToSize() { while (size > maxSize) { if (!removeOldestEntry()) return } mostRecentTrimFailed = false } /** Returns true if an entry was removed. This will return false if all entries are zombies. */ private fun removeOldestEntry(): Boolean { for (toEvict in lruEntries.values) { if (!toEvict.zombie) { removeEntry(toEvict) return true } } return false } /** * Closes the cache and deletes all of its stored values. This will delete all files in the * cache directory including files that weren't created by the cache. */ private fun delete() { close() fileSystem.deleteContents(directory) } /** * Deletes all stored values from the cache. In-flight edits will complete normally but their * values will not be stored. */ @Synchronized fun evictAll() { initialize() // Copying for concurrent iteration. for (entry in lruEntries.values.toTypedArray()) { removeEntry(entry) } mostRecentTrimFailed = false } /** * Launch an asynchronous operation to trim files from the disk cache and update the journal. */ private fun launchCleanup() { cleanupScope.launch { synchronized(this@DiskLruCache) { if (!initialized || closed) return@launch try { trimToSize() } catch (_: IOException) { mostRecentTrimFailed = true } try { if (journalRewriteRequired()) { writeJournal() } } catch (_: IOException) { mostRecentRebuildFailed = true journalWriter = blackholeSink().buffer() } } } } private fun validateKey(key: String) { require(LEGAL_KEY_PATTERN matches key) { "keys must match regex [a-z0-9_-]{1,120}: \"$key\"" } } /** A snapshot of the values for an entry. */ inner class Snapshot(val entry: Entry) : Closeable { private var closed = false fun file(index: Int): Path { check(!closed) { "snapshot is closed" } return entry.cleanFiles[index] } override fun close() { if (!closed) { closed = true synchronized(this@DiskLruCache) { entry.lockingSnapshotCount-- if (entry.lockingSnapshotCount == 0 && entry.zombie) { removeEntry(entry) } } } } fun closeAndEdit(): Editor? { synchronized(this@DiskLruCache) { close() return edit(entry.key) } } } /** Edits the values for an entry. */ inner class Editor(val entry: Entry) { private var closed = false /** * True for a given index if that index's file has been written to. */ val written = BooleanArray(valueCount) /** * Get the file to read from/write to for [index]. * This file will become the new value for this index if committed. */ fun file(index: Int): Path { synchronized(this@DiskLruCache) { check(!closed) { "editor is closed" } written[index] = true return entry.dirtyFiles[index].also(fileSystem::createFile) } } /** * Prevents this editor from completing normally. * This is necessary if the target entry is evicted while this editor is active. */ fun detach() { if (entry.currentEditor == this) { entry.zombie = true // We can't delete it until the current edit completes. } } /** * Commits this edit so it is visible to readers. * This releases the edit lock so another edit may be started on the same key. */ fun commit() = complete(true) /** * Commit the edit and open a new [Snapshot] atomically. */ fun commitAndGet(): Snapshot? { synchronized(this@DiskLruCache) { commit() return get(entry.key) } } /** * Aborts this edit. * This releases the edit lock so another edit may be started on the same key. */ fun abort() = complete(false) /** * Complete this edit either successfully or unsuccessfully. */ private fun complete(success: Boolean) { synchronized(this@DiskLruCache) { check(!closed) { "editor is closed" } if (entry.currentEditor == this) { completeEdit(this, success) } closed = true } } } inner class Entry(val key: String) { /** Lengths of this entry's files. */ val lengths = LongArray(valueCount) val cleanFiles = ArrayList<Path>(valueCount) val dirtyFiles = ArrayList<Path>(valueCount) /** True if this entry has ever been published. */ var readable = false /** True if this entry must be deleted when the current edit or read completes. */ var zombie = false /** * The ongoing edit or null if this entry is not being edited. When setting this to null * the entry must be removed if it is a zombie. */ var currentEditor: Editor? = null /** * Snapshots currently reading this entry before a write or delete can proceed. When * decrementing this to zero, the entry must be removed if it is a zombie. */ var lockingSnapshotCount = 0 init { // The names are repetitive so re-use the same builder to avoid allocations. val fileBuilder = StringBuilder(key).append('.') val truncateTo = fileBuilder.length for (i in 0 until valueCount) { fileBuilder.append(i) cleanFiles += directory / fileBuilder.toString() fileBuilder.append(".tmp") dirtyFiles += directory / fileBuilder.toString() fileBuilder.setLength(truncateTo) } } /** Set lengths using decimal numbers like "10123". */ fun setLengths(strings: List<String>) { if (strings.size != valueCount) { throw IOException("unexpected journal line: $strings") } try { for (i in strings.indices) { lengths[i] = strings[i].toLong() } } catch (_: NumberFormatException) { throw IOException("unexpected journal line: $strings") } } /** Append space-prefixed lengths to [writer]. */ fun writeLengths(writer: BufferedSink) { for (length in lengths) { writer.writeByte(' '.code).writeDecimalLong(length) } } /** Returns a snapshot of this entry. */ fun snapshot(): Snapshot? { if (!readable) return null if (currentEditor != null || zombie) return null // Ensure that the entry's files still exist. cleanFiles.forEachIndices { file -> if (!fileSystem.exists(file)) { // Since the entry is no longer valid, remove it so the metadata is accurate // (i.e. the cache size). try { removeEntry(this) } catch (_: IOException) {} return null } } lockingSnapshotCount++ return Snapshot(this) } } companion object { @VisibleForTesting internal const val JOURNAL_FILE = "journal" @VisibleForTesting internal const val JOURNAL_FILE_TMP = "journal.tmp" @VisibleForTesting internal const val JOURNAL_FILE_BACKUP = "journal.bkp" @VisibleForTesting internal const val MAGIC = "libcore.io.DiskLruCache" @VisibleForTesting internal const val VERSION = "1" private const val CLEAN = "CLEAN" private const val DIRTY = "DIRTY" private const val REMOVE = "REMOVE" private const val READ = "READ" private val LEGAL_KEY_PATTERN = "[a-z0-9_-]{1,120}".toRegex() } }
apache-2.0
56008f9b3c5f1323b51bad9a4665ea6d
34.182028
104
0.577772
5.030143
false
false
false
false
MichaelRocks/lightsaber
processor/src/main/java/io/michaelrocks/lightsaber/processor/watermark/WatermarkChecker.kt
1
1916
/* * Copyright 2019 Michael Rozumyanskiy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.michaelrocks.lightsaber.processor.watermark import io.michaelrocks.lightsaber.processor.io.readBytes import org.objectweb.asm.Attribute import org.objectweb.asm.ClassReader import org.objectweb.asm.ClassVisitor import org.objectweb.asm.Opcodes import java.io.File import java.io.IOException class WatermarkChecker : ClassVisitor(Opcodes.ASM5) { companion object { private val CLASS_EXTENSION = "class" @Throws(IOException::class) @JvmStatic fun isLightsaberClass(file: File): Boolean { if (!file.extension.equals(CLASS_EXTENSION, true)) { return false } val classReader = ClassReader(file.readBytes()) val checker = WatermarkChecker() classReader.accept( checker, arrayOf<Attribute>(LightsaberAttribute()), ClassReader.SKIP_CODE or ClassReader.SKIP_DEBUG or ClassReader.SKIP_FRAMES ) return checker.isLightsaberClass } } var isLightsaberClass: Boolean = false private set override fun visit( version: Int, access: Int, name: String, signature: String?, superName: String?, interfaces: Array<String>? ) { isLightsaberClass = false } override fun visitAttribute(attr: Attribute) { if (attr is LightsaberAttribute) { isLightsaberClass = true } } }
apache-2.0
1960717775fba81b168ada4e23d97d2c
27.597015
82
0.718163
4.201754
false
false
false
false
cbeyls/fosdem-companion-android
app/src/main/java/be/digitalia/fosdem/fragments/RoomImageDialogFragment.kt
1
2222
package be.digitalia.fosdem.fragments import android.annotation.SuppressLint import android.app.Dialog import android.os.Bundle import android.view.LayoutInflater import android.widget.ImageView import androidx.annotation.DrawableRes import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import be.digitalia.fosdem.R import be.digitalia.fosdem.activities.RoomImageDialogActivity import be.digitalia.fosdem.api.FosdemApi import be.digitalia.fosdem.utils.invertImageColors import be.digitalia.fosdem.utils.isLightTheme import com.google.android.material.dialog.MaterialAlertDialogBuilder import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class RoomImageDialogFragment : DialogFragment() { @Inject lateinit var api: FosdemApi @SuppressLint("InflateParams") override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val args = requireArguments() val dialogBuilder: AlertDialog.Builder = MaterialAlertDialogBuilder(requireContext()) val contentView = LayoutInflater.from(dialogBuilder.context).inflate(R.layout.dialog_room_image, null) contentView.findViewById<ImageView>(R.id.room_image).apply { if (!context.isLightTheme) { invertImageColors() } setImageResource(args.getInt(ARG_ROOM_IMAGE_RESOURCE_ID)) } RoomImageDialogActivity.configureToolbar( api, this, contentView.findViewById(R.id.toolbar), args.getString(ARG_ROOM_NAME)!! ) return dialogBuilder .setView(contentView) .create() .apply { window?.attributes?.windowAnimations = R.style.RoomImageDialogAnimations } } companion object { const val TAG = "room" private const val ARG_ROOM_NAME = "roomName" private const val ARG_ROOM_IMAGE_RESOURCE_ID = "imageResId" fun createArguments(roomName: String, @DrawableRes imageResId: Int) = Bundle(2).apply { putString(ARG_ROOM_NAME, roomName) putInt(ARG_ROOM_IMAGE_RESOURCE_ID, imageResId) } } }
apache-2.0
6632891b60a0dc05eec2588ec9598207
33.734375
110
0.69757
4.75803
false
false
false
false
yongce/DevTools
app/src/main/java/me/ycdev/android/devtools/security/unmarshall/IntentUnmarshallScanner.kt
1
5155
package me.ycdev.android.devtools.security.unmarshall import android.content.ComponentName import android.content.Context import android.content.Intent import android.os.SystemClock import me.ycdev.android.devtools.root.cmd.AppsKillerCmd import me.ycdev.android.devtools.security.foo.ParcelableTest import me.ycdev.android.lib.common.utils.PackageUtils import me.ycdev.android.lib.common.wrapper.BroadcastHelper import timber.log.Timber object IntentUnmarshallScanner { private const val TAG = "IntentUnmarshallScanner" private fun buildScanIntent(target: ComponentName): Intent { val intent = Intent() intent.component = target intent.putExtra("extra.oom_attack", ParcelableTest(1014 * 1024 * 1024)) return intent } private fun scanReceiverTarget(cxt: Context, target: ComponentName, perm: String?): Boolean { Timber.tag(TAG).i("scan receiver: $target, with perm: $perm") try { val intent = buildScanIntent(target) BroadcastHelper.sendToExternal(cxt, intent, perm) return true } catch (e: Exception) { Timber.tag(TAG).w(e, "failed to send broadcast") } return false } private fun scanServiceTarget(cxt: Context, target: ComponentName): Boolean { Timber.tag(TAG).i("scan service: %s", target) try { val intent = buildScanIntent(target) cxt.startService(intent) return true } catch (e: Exception) { Timber.tag(TAG).w(e, "failed to start service") } return false } private fun scanActivityTarget(cxt: Context, target: ComponentName): Boolean { Timber.tag(TAG).i("scan activity: %s", target) try { val intent = buildScanIntent(target) intent.flags = (Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) cxt.startActivity(intent) return true } catch (e: Exception) { Timber.tag(TAG).w(e, "failed to start activity") } return false } fun scanAllReceivers(cxt: Context, controller: IScanController) { val pkgName = controller.targetPackageName val allReceivers = PackageUtils.getAllReceivers(cxt, pkgName, true) if (allReceivers.isEmpty()) { return } Timber.tag(TAG).i("%s receivers to scan...", allReceivers.size) var appsKillerCmd: AppsKillerCmd? = null if (controller.needKillApp) { appsKillerCmd = AppsKillerCmd(cxt, listOf(pkgName)) } for (receiverInfo in allReceivers) { if (controller.isCanceled) { Timber.tag(TAG).i("scan canceled") return } appsKillerCmd?.run() val cn = ComponentName(receiverInfo.packageName, receiverInfo.name) scanReceiverTarget(cxt, cn, receiverInfo.permission) if (appsKillerCmd != null) { SystemClock.sleep(5000) } else { SystemClock.sleep(500) } } Timber.tag(TAG).i("receivers scan done") } fun scanAllServices(cxt: Context, controller: IScanController) { val pkgName = controller.targetPackageName val allServices = PackageUtils.getAllServices(cxt, pkgName, true) if (allServices.isEmpty()) { return } Timber.tag(TAG).i("%s services to check...", allServices.size) var appsKillerCmd: AppsKillerCmd? = null if (controller.needKillApp) { appsKillerCmd = AppsKillerCmd(cxt, listOf(pkgName)) } for (serviceInfo in allServices) { if (controller.isCanceled) { Timber.tag(TAG).i("scan canceled") return } appsKillerCmd?.run() val cn = ComponentName(serviceInfo.packageName, serviceInfo.name) scanServiceTarget(cxt, cn) if (appsKillerCmd != null) { SystemClock.sleep(5000) } else { SystemClock.sleep(500) } } Timber.tag(TAG).i("services scan done") } fun scanAllActivities(cxt: Context, controller: IScanController) { val pkgName = controller.targetPackageName val allActivities = PackageUtils.getAllActivities(cxt, pkgName, true) if (allActivities.isEmpty()) { return } Timber.tag(TAG).i("%s activities to check...", allActivities.size) var appsKillerCmd: AppsKillerCmd? = null if (controller.needKillApp) { appsKillerCmd = AppsKillerCmd(cxt, listOf(pkgName)) } for (activityInfo in allActivities) { if (controller.isCanceled) { Timber.tag(TAG).i("scan canceled") return } appsKillerCmd?.run() val cn = ComponentName(activityInfo.packageName, activityInfo.name) scanActivityTarget(cxt, cn) SystemClock.sleep(5000) } Timber.tag(TAG).i("activities scan done") } }
apache-2.0
e09a4b505926c9655e873e14671ab68e
35.560284
97
0.602716
4.428694
false
false
false
false
marcorighini/PullableView
lib/src/main/java/com/marcorighini/lib/Direction.kt
1
326
package com.marcorighini.lib enum class Direction(val value: Int){ UP(0), DOWN(1), BOTH(2); companion object { fun from(findValue: Int): Direction = Direction.values().first { it.value == findValue } } fun upEnabled() = this == UP || this == BOTH fun downEnabled() = this == UP || this == BOTH }
apache-2.0
758304f6e6aca094146ddffda96364ab
26.25
96
0.613497
3.622222
false
false
false
false
fabmax/calculator
app/src/main/kotlin/de/fabmax/calc/ui/Layout.kt
1
4366
package de.fabmax.calc.ui import android.content.Context import de.fabmax.lightgl.BoundingBox import de.fabmax.lightgl.Ray import de.fabmax.lightgl.util.Painter import java.util.* /** * Base class for UI layouts. Currently this is the only container UI element which can hold * child elements. */ class Layout(context: Context) : UiElement<LayoutConfig>(LayoutConfig(), context) { private val mChildComparator = Comparator<UiElement<*>> { a, b -> java.lang.Float.compare(a.bounds.maxZ, b.bounds.maxZ) } private val mChildren = ArrayList<UiElement<*>>() private val mLocalRay = Ray() /** * Adds a child UI element to this layout */ fun add(child: UiElement<*>) { mChildren.add(child) } /** * Searches for a child element with the given ID, returns that element or null if no element * was found. */ fun findById(id: String): UiElement<*>? { for (i in mChildren.indices) { val c = mChildren[i] if (c.id == id) { return c } else if (c is Layout) { val r = c.findById(id) if (r != null) { return r } } } return null } /** * Lays out this layout element and all children. */ override fun doLayout(orientation: Int, parentBounds: BoundingBox, ctx: Context): BoundingBox { val bounds = super.doLayout(orientation, parentBounds, ctx) for (elem in mChildren) { elem.doLayout(orientation, bounds, ctx) } return bounds } /** * Interpolates this layout and all children between portrait and landscape. */ override fun mixConfigs(portLandMix: Float) { super.mixConfigs(portLandMix) for (elem in mChildren) { elem.mixConfigs(portLandMix) } } /** * Draws all child elements. */ override fun paint(painter: Painter) { // todo: Collections.sort is quite heap intensive... Collections.sort(mChildren, mChildComparator) // using i in IntRange saves an Iterator allocation for (i in mChildren.indices) { val elem = mChildren[i] painter.pushTransform() painter.translate(elem.x, elem.y, elem.z) elem.paint(painter) painter.commit() painter.reset() painter.popTransform() } } /** * Checks whether the touch event is relevant for one of the children elements. */ override fun processTouch(ray: Ray, action: Int) { super.processTouch(ray, action) val dist = bounds.computeHitDistanceSqr(ray) if (dist < Float.MAX_VALUE) { // naive transformation of pick ray (considers only translation) mLocalRay.setDirection(ray.direction[0], ray.direction[1], ray.direction[2]) mLocalRay.setOrigin(ray.origin[0] - bounds.minX, ray.origin[1] - bounds.minY, ray.origin[2] - bounds.minZ) mChildren.forEach { c -> c.processTouch(mLocalRay, action) } } } } /** * Builder for layouts. Offers functions to add buttons, etc. */ class LayoutBuilder(context: Context) : UiElementBuilder<Layout>(context) { override fun create(): Layout { return Layout(context) } protected fun <T : UiElement<*>, U : UiElementBuilder<T>> initElement(builder: U, init: U.() -> Unit): T { builder.init() val elem = builder.element element.add(elem) return elem } /** * Adds a button to the layout. */ fun button(init: ButtonBuilder.() -> Unit): Button = initElement(ButtonBuilder(context), init) /** * Adds a calculator panel to the layout. */ fun calcPanel(init: CalcPanelBuilder.() -> Unit): CalcPanel = initElement(CalcPanelBuilder(context), init) /** * Adds a panel to the layout. */ fun panel(init: PanelBuilder.() -> Unit): Panel<PanelConfig> = initElement(PanelBuilder(context), init) } /** * Entrance function for layout definitions. */ fun layout(context: Context, init: LayoutBuilder.() -> Unit): Layout { val builder = LayoutBuilder(context) builder.init() return builder.element }
apache-2.0
be944b01143b75d077e8f0a8581947d7
27.723684
97
0.593449
4.255361
false
false
false
false
spark/photon-tinker-android
mesh/src/main/java/io/particle/mesh/common/android/SimpleAsync.kt
1
2159
package io.particle.mesh.common.android import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.LifecycleOwner import io.particle.mesh.common.QATool import io.particle.mesh.setup.flow.Scopes import kotlinx.coroutines.* /** * Everything necessary to create a mini "DSL" for async operations based coroutines * that are scoped to a given [LifecycleOwner] * * Pulled from: https://hellsoft.se/simple-asynchronous-loading-with-kotlin-coroutines-f26408f97f46 */ class CoroutineOnDestroyListener(val deferred: Deferred<*>) : DefaultLifecycleObserver { override fun onDestroy(owner: LifecycleOwner) { if (!deferred.isCancelled) { deferred.cancel() } } } class CoroutineOnStopListener(val deferred: Deferred<*>) : DefaultLifecycleObserver { override fun onStop(owner: LifecycleOwner) { if (!deferred.isCancelled) { deferred.cancel() } } } enum class LifecycleCancellationPoint { ON_STOP, ON_DESTROY } /** * Creates a lazily started coroutine that runs <code>loader()</code>. * The coroutine is automatically cancelled using the CoroutineLifecycleListener. */ fun <T> LifecycleOwner.load( scopes: Scopes, cancelWhen: LifecycleCancellationPoint = LifecycleCancellationPoint.ON_DESTROY, loader: () -> T ): Deferred<T> { val deferred = scopes.backgroundScope.async(start = CoroutineStart.LAZY, block = { loader() }) val listener = when (cancelWhen) { LifecycleCancellationPoint.ON_STOP -> CoroutineOnStopListener(deferred) LifecycleCancellationPoint.ON_DESTROY -> CoroutineOnDestroyListener(deferred) } lifecycle.addObserver(listener) return deferred } /** * Extension function on <code>Deferred<T><code> that creates a launches a coroutine which * will call <code>await()</code> and pass the returned value to <code>block()</code>. */ infix fun <T> Deferred<T>.then(block: (T) -> Unit): Job { return GlobalScope.launch { try { block([email protected]()) } catch (ex: Exception) { QATool.report(ex) throw ex } } }
apache-2.0
f7881206fd302919b4a4e1b0e4051512
25.329268
99
0.691061
4.309381
false
false
false
false
toastkidjp/Jitte
rss/src/main/java/jp/toastkid/rss/setting/RssSettingFragment.kt
1
2639
/* * Copyright (c) 2019 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.rss.setting import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import jp.toastkid.lib.ContentViewModel import jp.toastkid.lib.fragment.CommonFragmentAction import jp.toastkid.lib.preference.PreferenceApplier import jp.toastkid.lib.view.swipe.SwipeActionAttachment import jp.toastkid.rss.R import jp.toastkid.rss.databinding.FragmentRssSettingBinding /** * @author toastkidjp */ class RssSettingFragment : Fragment(), CommonFragmentAction { private lateinit var binding: FragmentRssSettingBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { super.onCreateView(inflater, container, savedInstanceState) binding = DataBindingUtil.inflate(inflater, R.layout.fragment_rss_setting, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val context = view.context val fragmentActivity = activity ?: return val preferenceApplier = PreferenceApplier(fragmentActivity) val adapter = Adapter(preferenceApplier) binding.rssSettingList.adapter = adapter binding.rssSettingList.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false) SwipeActionAttachment().invoke(binding.rssSettingList) val rssReaderTargets = preferenceApplier.readRssReaderTargets() if (rssReaderTargets.isEmpty()) { ViewModelProvider(fragmentActivity).get(ContentViewModel::class.java) .snackShort(R.string.message_rss_reader_launch_failed) fragmentActivity.supportFragmentManager.popBackStack() return } adapter.replace(rssReaderTargets) adapter.notifyDataSetChanged() } override fun pressBack(): Boolean { activity?.supportFragmentManager?.popBackStack() return true } }
epl-1.0
0cbf2819ccec0b11c1fc3f7adc3c4f23
34.2
100
0.741569
5.124272
false
false
false
false
anton-okolelov/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/ext/RsMacroCall.kt
1
1625
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.psi.ext import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.stubs.IStubElementType import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiModificationTracker import org.rust.lang.core.macros.ExpansionResult import org.rust.lang.core.macros.expandMacro import org.rust.lang.core.psi.RsElementTypes.IDENTIFIER import org.rust.lang.core.psi.RsMacroCall import org.rust.lang.core.resolve.ref.RsMacroCallReferenceImpl import org.rust.lang.core.resolve.ref.RsReference import org.rust.lang.core.stubs.RsMacroCallStub abstract class RsMacroCallImplMixin : RsStubbedElementImpl<RsMacroCallStub>, RsMacroCall { constructor(node: ASTNode) : super(node) constructor(stub: RsMacroCallStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType) override fun getReference(): RsReference = RsMacroCallReferenceImpl(this) override val referenceName: String get() = macroName override val referenceNameElement: PsiElement get() = findChildByType(IDENTIFIER)!! } val RsMacroCall.macroName: String get() { val stub = stub if (stub != null) return stub.macroName return referenceNameElement.text } val RsMacroCall.expansion: List<ExpansionResult>? get() = CachedValuesManager.getCachedValue(this) { CachedValueProvider.Result.create(expandMacro(this), PsiModificationTracker.MODIFICATION_COUNT) }
mit
cc5cdcc45ef052442b38637b754ab937
32.854167
103
0.773538
4.391892
false
false
false
false
CarrotCodes/Warren
src/main/kotlin/chat/willow/warren/event/WarrenEventDispatcherRunner.kt
1
1838
package chat.willow.warren.event import chat.willow.kale.irc.prefix.Prefix import chat.willow.kale.irc.tag.TagStore import chat.willow.warren.IClientMessageSending import chat.willow.warren.WarrenChannel import chat.willow.warren.WarrenChannelUser import chat.willow.warren.state.LifecycleState import chat.willow.warren.state.emptyChannel import chat.willow.warren.state.generateUser object WarrenEventDispatcherRunner { @JvmStatic fun main(args: Array<String>) { val eventDispatcher = WarrenEventDispatcher() eventDispatcher.onAny { println("anything listener: $it") } eventDispatcher.on(ChannelMessageEvent::class) { println("channel message listener 1: $it") } eventDispatcher.on(PrivateMessageEvent::class) { println("private message listener 2: $it") } val client = DummyMessageSending() val channel = WarrenChannel(state = emptyChannel("#channel"), client = client) val someone = WarrenChannelUser(state = generateUser("someone"), channel = channel) eventDispatcher.fire(ChannelMessageEvent(user = someone, channel = channel, message = "something", metadata = TagStore())) eventDispatcher.fire(PrivateMessageEvent(user = Prefix(nick = "someone"), message = "something", metadata = TagStore())) eventDispatcher.fire(ConnectionLifecycleEvent(lifecycle = LifecycleState.CONNECTED)) } } private class DummyMessageSending: IClientMessageSending { override fun <M : Any> send(message: M) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun send(message: String, target: String) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } }
isc
52ad26f73ed6bcc812875d2f74a38e43
38.978261
130
0.713275
4.676845
false
false
false
false
google/horologist
composables/src/main/java/com/google/android/horologist/composables/SegmentedProgressIndicator.kt
1
8319
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.composables import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.progressSemantics import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Dp import androidx.wear.compose.material.MaterialTheme import androidx.wear.compose.material.ProgressIndicatorDefaults import kotlin.math.asin /** * Represents a segment of the track in a [SegmentedProgressIndicator]. * * @param weight The proportion of the overall progress indicator that this segment should take up, * as a proportion of the sum of the weights of all the other segments. * @param indicatorColor The color of the indicator bar. * @param trackColor The color of the background progress track. This is optional and if not * specified will default to the [trackColor] of the overall [SegmentedProgressIndicator]. * @param inProgressTrackColor The color of the background progress track when this segment is in * progress. This is optional, and if specified will take precedence to the [trackColor] of the * segment or the overall [SegmentedProgressIndicator], when the segment is in progress. */ public data class ProgressIndicatorSegment( val weight: Float, val indicatorColor: Color, val trackColor: Color? = null, val inProgressTrackColor: Color? = null ) /** * Represents a segmented progress indicator. * * @param modifier [Modifier] to be applied to the [SegmentedProgressIndicator] * @param trackSegments A list of [ProgressIndicatorSegment] definitions, specifying the properties * of each segment. * @param progress The progress of this progress indicator where 0.0 represents no progress and 1.0 * represents completion. Values outside of this range are coerced into the range 0..1. * @param startAngle The starting position of the progress arc, * measured clockwise in degrees (0 to 360) from the 3 o'clock position. For example, 0 and 360 * represent 3 o'clock, 90 and 180 represent 6 o'clock and 9 o'clock respectively. * Default is -90 degrees (top of the screen) * @param endAngle The ending position of the progress arc, * measured clockwise in degrees (0 to 360) from the 3 o'clock position. For example, 0 and 360 * represent 3 o'clock, 90 and 180 represent 6 o'clock and 9 o'clock respectively. * By default equal to 270 degrees. * @param strokeWidth The stroke width for the progress indicator. * @param paddingAngle The gap to place between segments. Defaults to 0 degrees. * @param trackColor The background track color. If a segment specifies [trackColor] then the * segment value takes preference. Defaults to [Color.Black] */ @ExperimentalHorologistComposablesApi @Composable public fun SegmentedProgressIndicator( trackSegments: List<ProgressIndicatorSegment>, progress: Float, modifier: Modifier = Modifier, startAngle: Float = -90.0f, endAngle: Float = 270.0f, strokeWidth: Dp = ProgressIndicatorDefaults.StrokeWidth, paddingAngle: Float = 0.0f, trackColor: Color = MaterialTheme.colors.onBackground.copy(alpha = 0.1f) ) { val localDensity = LocalDensity.current val totalWeight = remember(trackSegments) { trackSegments.sumOf { it.weight.toDouble() }.toFloat() } // The degrees of the circle that are available for progress indication, once any padding // between segments is accounted for. This will be shared by weighting across the segments. val segmentableAngle = (endAngle - startAngle) - trackSegments.size * paddingAngle // This code is heavily inspired from the implementation of CircularProgressIndicator // Please see https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:wear/compose/compose-material/src/commonMain/kotlin/androidx/wear/compose/material/ProgressIndicator.kt?q=CircularProgressIndicator val stroke = with(localDensity) { Stroke(width = strokeWidth.toPx(), cap = StrokeCap.Round) } Canvas( modifier = modifier .fillMaxSize() .progressSemantics(progress) ) { // The progress bar uses rounded ends. The small delta requires calculation to take account // for the rounded end to ensure that neighbouring segments meet correctly. val endDelta = ( asin( strokeWidth.toPx() / (size.minDimension - strokeWidth.toPx()) ) * 180 / Math.PI ).toFloat() // The first segment needs half a padding between it and the start point. var currentStartAngle = startAngle + paddingAngle / 2 var remainingProgress = progress.coerceIn(0.0f, 1.0f) * segmentableAngle trackSegments.forEach { segment -> val segmentAngle = (segment.weight * segmentableAngle) / totalWeight val currentEndAngle = currentStartAngle + segmentAngle - endDelta val startAngleWithDelta = currentStartAngle + endDelta val backgroundSweep = 360f - ((startAngleWithDelta - currentEndAngle) % 360 + 360) % 360 val sectionProgress = remainingProgress / segmentAngle val progressSweep = backgroundSweep * sectionProgress.coerceIn(0f..1f) val diameterOffset = stroke.width / 2 val arcDimen = size.minDimension - 2 * diameterOffset drawCircularProgressIndicator( segment = segment, currentStartAngle = currentStartAngle, endDelta = endDelta, backgroundSweep = backgroundSweep, diameterOffset = diameterOffset, diameter = size.minDimension, arcDimen = arcDimen, stroke = stroke, progressSweep = progressSweep, trackColor = trackColor ) currentStartAngle += segmentAngle + paddingAngle remainingProgress -= segmentAngle } } } private fun DrawScope.drawCircularProgressIndicator( segment: ProgressIndicatorSegment, currentStartAngle: Float, endDelta: Float, backgroundSweep: Float, diameterOffset: Float, diameter: Float, arcDimen: Float, stroke: Stroke, progressSweep: Float, trackColor: Color ) { val offset = Offset( diameterOffset + (size.width - diameter) / 2, diameterOffset + (size.height - diameter) / 2 ) val localTrackColor = when { segment.inProgressTrackColor != null && progressSweep > 0 && progressSweep < backgroundSweep -> segment.inProgressTrackColor segment.trackColor != null -> segment.trackColor else -> trackColor } // Draw Track drawArc( color = localTrackColor, startAngle = currentStartAngle + endDelta, sweepAngle = backgroundSweep, useCenter = false, topLeft = offset, size = Size(arcDimen, arcDimen), style = stroke ) // Draw Progress drawArc( color = segment.indicatorColor, startAngle = currentStartAngle + endDelta, sweepAngle = progressSweep, useCenter = false, topLeft = offset, size = Size(arcDimen, arcDimen), style = stroke ) }
apache-2.0
f61dbd64061854852b641c8269b558a8
41.015152
225
0.704291
4.732082
false
false
false
false
Kotlin/dokka
core/test-api/src/main/kotlin/testApi/logger/TestLogger.kt
1
1491
package org.jetbrains.dokka.testApi.logger import org.jetbrains.dokka.utilities.DokkaLogger class TestLogger(private val logger: DokkaLogger) : DokkaLogger { override var warningsCount: Int by logger::warningsCount override var errorsCount: Int by logger::errorsCount private var _debugMessages = mutableListOf<String>() val debugMessages: List<String> get() = _debugMessages.toList() private var _infoMessages = mutableListOf<String>() val infoMessages: List<String> get() = _infoMessages.toList() private var _progressMessages = mutableListOf<String>() val progressMessages: List<String> get() = _progressMessages.toList() private var _warnMessages = mutableListOf<String>() val warnMessages: List<String> get() = _warnMessages.toList() private var _errorMessages = mutableListOf<String>() val errorMessages: List<String> get() = _errorMessages.toList() override fun debug(message: String) { _debugMessages.add(message) logger.debug(message) } override fun info(message: String) { _infoMessages.add(message) logger.info(message) } override fun progress(message: String) { _progressMessages.add(message) logger.progress(message) } override fun warn(message: String) { _warnMessages.add(message) logger.warn(message) } override fun error(message: String) { _errorMessages.add(message) logger.error(message) } }
apache-2.0
6422c4519e1a09a3f99ded5db335db33
30.0625
73
0.691482
4.272206
false
false
false
false
chrisbanes/tivi
data/src/main/java/app/tivi/data/daos/FollowedShowsDao.kt
1
9053
/* * 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 app.tivi.data.daos import androidx.paging.PagingSource import androidx.room.Dao import androidx.room.Query import androidx.room.Transaction import app.tivi.data.entities.FollowedShowEntry import app.tivi.data.entities.PendingAction import app.tivi.data.entities.Season import app.tivi.data.resultentities.FollowedShowEntryWithShow import app.tivi.data.views.FollowedShowsWatchStats import kotlinx.coroutines.flow.Flow @Dao abstract class FollowedShowsDao : EntryDao<FollowedShowEntry, FollowedShowEntryWithShow>() { @Query("SELECT * FROM myshows_entries") abstract suspend fun entries(): List<FollowedShowEntry> @Transaction @Query(ENTRY_QUERY_SUPER_SORT) internal abstract fun pagedListSuperSort(): PagingSource<Int, FollowedShowEntryWithShow> @Transaction @Query(ENTRY_QUERY_SUPER_SORT_FILTER) internal abstract fun pagedListSuperSortFilter(filter: String): PagingSource<Int, FollowedShowEntryWithShow> @Transaction @Query(ENTRY_QUERY_ORDER_LAST_WATCHED) internal abstract fun pagedListLastWatched(): PagingSource<Int, FollowedShowEntryWithShow> @Transaction @Query(ENTRY_QUERY_ORDER_LAST_WATCHED_FILTER) internal abstract fun pagedListLastWatchedFilter(filter: String): PagingSource<Int, FollowedShowEntryWithShow> @Transaction @Query(ENTRY_QUERY_ORDER_ALPHA) internal abstract fun pagedListAlpha(): PagingSource<Int, FollowedShowEntryWithShow> @Transaction @Query(ENTRY_QUERY_ORDER_ALPHA_FILTER) internal abstract fun pagedListAlphaFilter(filter: String): PagingSource<Int, FollowedShowEntryWithShow> @Transaction @Query(ENTRY_QUERY_ORDER_ADDED) internal abstract fun pagedListAdded(): PagingSource<Int, FollowedShowEntryWithShow> @Transaction @Query(ENTRY_QUERY_ORDER_ADDED_FILTER) internal abstract fun pagedListAddedFilter(filter: String): PagingSource<Int, FollowedShowEntryWithShow> @Transaction @Query( """ SELECT myshows_entries.* FROM myshows_entries INNER JOIN seasons AS s ON s.show_id = myshows_entries.show_id INNER JOIN followed_next_to_watch AS next ON next.id = myshows_entries.id INNER JOIN episodes AS eps ON eps.season_id = s.id INNER JOIN episode_watch_entries AS ew ON ew.episode_id = eps.id WHERE s.number != ${Season.NUMBER_SPECIALS} AND s.ignored = 0 ORDER BY datetime(ew.watched_at) DESC LIMIT 1 """ ) abstract fun observeNextShowToWatch(): Flow<FollowedShowEntryWithShow?> @Query("DELETE FROM myshows_entries") abstract override suspend fun deleteAll() @Transaction @Query("SELECT * FROM myshows_entries WHERE id = :id") abstract suspend fun entryWithId(id: Long): FollowedShowEntryWithShow? @Query("SELECT * FROM myshows_entries WHERE show_id = :showId") abstract suspend fun entryWithShowId(showId: Long): FollowedShowEntry? @Query("SELECT COUNT(*) FROM myshows_entries WHERE show_id = :showId AND pending_action != 'delete'") abstract fun entryCountWithShowIdNotPendingDeleteObservable(showId: Long): Flow<Int> @Query("SELECT COUNT(*) FROM myshows_entries WHERE show_id = :showId") abstract suspend fun entryCountWithShowId(showId: Long): Int @Transaction @Query( """ SELECT stats.* FROM FollowedShowsWatchStats as stats INNER JOIN myshows_entries ON stats.id = myshows_entries.id WHERE show_id = :showId """ ) abstract fun entryShowViewStats(showId: Long): Flow<FollowedShowsWatchStats> suspend fun entriesWithNoPendingAction() = entriesWithPendingAction(PendingAction.NOTHING.value) suspend fun entriesWithSendPendingActions() = entriesWithPendingAction(PendingAction.UPLOAD.value) suspend fun entriesWithDeletePendingActions() = entriesWithPendingAction(PendingAction.DELETE.value) @Query("SELECT * FROM myshows_entries WHERE pending_action = :pendingAction") internal abstract suspend fun entriesWithPendingAction(pendingAction: String): List<FollowedShowEntry> @Query("UPDATE myshows_entries SET pending_action = :pendingAction WHERE id IN (:ids)") abstract suspend fun updateEntriesToPendingAction(ids: List<Long>, pendingAction: String): Int @Query("DELETE FROM myshows_entries WHERE id IN (:ids)") abstract suspend fun deleteWithIds(ids: List<Long>): Int companion object { private const val ENTRY_QUERY_SUPER_SORT = """ SELECT fs.* FROM myshows_entries as fs LEFT JOIN seasons AS s ON fs.show_id = s.show_id LEFT JOIN episodes AS eps ON eps.season_id = s.id LEFT JOIN episode_watch_entries as ew ON ew.episode_id = eps.id LEFT JOIN followed_next_to_watch as nw ON nw.id = fs.id WHERE s.number != ${Season.NUMBER_SPECIALS} AND s.ignored = 0 GROUP BY fs.id ORDER BY /* shows with aired episodes to watch first */ SUM(CASE WHEN datetime(first_aired) < datetime('now') THEN 1 ELSE 0 END) = COUNT(watched_at) ASC, /* latest event */ MAX( MAX(datetime(coalesce(next_ep_to_watch_air_date, 0))), /* next episode to watch */ MAX(datetime(coalesce(watched_at, 0))), /* last watch */ MAX(datetime(coalesce(followed_at, 0))) /* when followed */ ) DESC """ private const val ENTRY_QUERY_SUPER_SORT_FILTER = """ SELECT fs.* FROM myshows_entries as fs INNER JOIN shows_fts AS s_fts ON fs.show_id = s_fts.docid LEFT JOIN seasons AS s ON fs.show_id = s.show_id LEFT JOIN episodes AS eps ON eps.season_id = s.id LEFT JOIN episode_watch_entries as ew ON ew.episode_id = eps.id LEFT JOIN followed_next_to_watch as nw ON nw.id = fs.id WHERE s.number != ${Season.NUMBER_SPECIALS} AND s.ignored = 0 AND s_fts.title MATCH :filter GROUP BY fs.id ORDER BY /* shows with aired episodes to watch first */ SUM(CASE WHEN datetime(first_aired) < datetime('now') THEN 1 ELSE 0 END) = COUNT(watched_at) ASC, /* latest event */ MAX( MAX(datetime(coalesce(next_ep_to_watch_air_date, 0))), /* next episode to watch */ MAX(datetime(coalesce(watched_at, 0))), /* last watch */ MAX(datetime(coalesce(followed_at, 0))) /* when followed */ ) DESC """ private const val ENTRY_QUERY_ORDER_LAST_WATCHED = """ SELECT fs.* FROM myshows_entries as fs LEFT JOIN seasons AS s ON fs.show_id = s.show_id LEFT JOIN episodes AS eps ON eps.season_id = s.id LEFT JOIN episode_watch_entries as ew ON ew.episode_id = eps.id GROUP BY fs.id ORDER BY MAX(datetime(ew.watched_at)) DESC """ private const val ENTRY_QUERY_ORDER_LAST_WATCHED_FILTER = """ SELECT fs.* FROM myshows_entries as fs INNER JOIN shows_fts AS s_fts ON fs.show_id = s_fts.docid LEFT JOIN seasons AS s ON fs.show_id = s.show_id LEFT JOIN episodes AS eps ON eps.season_id = s.id LEFT JOIN episode_watch_entries as ew ON ew.episode_id = eps.id WHERE s_fts.title MATCH :filter GROUP BY fs.id ORDER BY MAX(datetime(ew.watched_at)) DESC """ private const val ENTRY_QUERY_ORDER_ALPHA = """ SELECT fs.* FROM myshows_entries as fs INNER JOIN shows_fts AS s_fts ON fs.show_id = s_fts.docid ORDER BY title ASC """ private const val ENTRY_QUERY_ORDER_ALPHA_FILTER = """ SELECT fs.* FROM myshows_entries as fs INNER JOIN shows_fts AS s_fts ON fs.show_id = s_fts.docid WHERE s_fts.title MATCH :filter ORDER BY title ASC """ private const val ENTRY_QUERY_ORDER_ADDED = """ SELECT * FROM myshows_entries ORDER BY datetime(followed_at) DESC """ private const val ENTRY_QUERY_ORDER_ADDED_FILTER = """ SELECT fs.* FROM myshows_entries as fs INNER JOIN shows_fts AS s_fts ON fs.show_id = s_fts.docid WHERE s_fts.title MATCH :filter ORDER BY datetime(followed_at) DESC """ } }
apache-2.0
48621ff7532c0f4444be0121c2c83241
41.905213
114
0.659671
4.202878
false
false
false
false
dya-tel/TSU-Schedule
src/main/kotlin/ru/dyatel/tsuschedule/layout/TeacherItem.kt
1
2776
package ru.dyatel.tsuschedule.layout import android.content.Context import android.support.v4.content.ContextCompat import android.text.Spanned import android.view.View import android.view.ViewGroup import android.widget.TextView import com.mikepenz.fastadapter.FastAdapter import com.mikepenz.fastadapter.items.AbstractItem import org.jetbrains.anko.Bold import org.jetbrains.anko.bottomPadding import org.jetbrains.anko.buildSpanned import org.jetbrains.anko.find import org.jetbrains.anko.frameLayout import org.jetbrains.anko.leftPadding import org.jetbrains.anko.matchParent import org.jetbrains.anko.rightPadding import org.jetbrains.anko.textColor import org.jetbrains.anko.textView import org.jetbrains.anko.topPadding import ru.dyatel.tsuschedule.ADAPTER_TEACHER_ITEM_ID import ru.dyatel.tsuschedule.R import ru.dyatel.tsuschedule.model.Teacher import org.jetbrains.anko.append as ankoAppend class TeacherItem(val teacher: Teacher) : AbstractItem<TeacherItem, TeacherItem.ViewHolder>() { private companion object { val nameViewId = View.generateViewId() val NAME_PATTERN = Regex("^(.+?) (.+)$") } init { withIdentifier(teacher.id.hashCode().toLong()) } class ViewHolder(view: View) : FastAdapter.ViewHolder<TeacherItem>(view) { private val nameView = view.find<TextView>(nameViewId) override fun bindView(item: TeacherItem, payloads: List<Any>) { val parts = NAME_PATTERN.matchEntire(item.teacher.name)!!.groups val text = buildSpanned { ankoAppend(parts[1]!!.value, Bold, Spanned.SPAN_INCLUSIVE_EXCLUSIVE) ankoAppend(" " + parts[2]!!.value) } nameView.text = text } override fun unbindView(item: TeacherItem) { nameView.text = null } } override fun createView(ctx: Context, parent: ViewGroup?): View { return ctx.frameLayout { lparams(width = matchParent) { leftPadding = DIM_TEXT_ITEM_HORIZONTAL_PADDING rightPadding = DIM_TEXT_ITEM_HORIZONTAL_PADDING topPadding = DIM_TEXT_ITEM_VERTICAL_PADDING bottomPadding = DIM_TEXT_ITEM_VERTICAL_PADDING } textView { id = nameViewId textSize = SP_TEXT_MEDIUM textColor = ContextCompat.getColor(ctx, R.color.text_color) } } } override fun getType() = ADAPTER_TEACHER_ITEM_ID override fun getViewHolder(view: View) = ViewHolder(view) override fun getLayoutRes() = throw UnsupportedOperationException() override fun equals(other: Any?): Boolean { return super.equals(other) && (other as TeacherItem).teacher == teacher } }
mit
ced0361f11f8710ea5653080a80057fe
32.853659
95
0.682637
4.413355
false
false
false
false
NordicSemiconductor/Android-nRF-Toolbox
profile_prx/src/main/java/no/nordicsemi/android/prx/data/PRXManager.kt
1
7579
/* * Copyright (c) 2022, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be * used to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package no.nordicsemi.android.prx.data import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothGatt import android.bluetooth.BluetoothGattCharacteristic import android.bluetooth.BluetoothGattServer import android.content.Context import android.util.Log import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import no.nordicsemi.android.ble.BleManager import no.nordicsemi.android.ble.common.callback.alert.AlertLevelDataCallback import no.nordicsemi.android.ble.common.callback.battery.BatteryLevelResponse import no.nordicsemi.android.ble.common.data.alert.AlertLevelData import no.nordicsemi.android.ble.ktx.asValidResponseFlow import no.nordicsemi.android.ble.ktx.suspend import no.nordicsemi.android.logger.NordicLogger import no.nordicsemi.android.service.ConnectionObserverAdapter import no.nordicsemi.android.utils.launchWithCatch import java.util.* val PRX_SERVICE_UUID = UUID.fromString("00001802-0000-1000-8000-00805f9b34fb") val LINK_LOSS_SERVICE_UUID = UUID.fromString("00001803-0000-1000-8000-00805f9b34fb") val ALERT_LEVEL_CHARACTERISTIC_UUID = UUID.fromString("00002A06-0000-1000-8000-00805f9b34fb") private val BATTERY_SERVICE_UUID = UUID.fromString("0000180F-0000-1000-8000-00805f9b34fb") private val BATTERY_LEVEL_CHARACTERISTIC_UUID = UUID.fromString("00002A19-0000-1000-8000-00805f9b34fb") internal class PRXManager( context: Context, private val scope: CoroutineScope, private val logger: NordicLogger ) : BleManager(context) { private var batteryLevelCharacteristic: BluetoothGattCharacteristic? = null private var alertLevelCharacteristic: BluetoothGattCharacteristic? = null private var linkLossCharacteristic: BluetoothGattCharacteristic? = null private var localAlertLevelCharacteristic: BluetoothGattCharacteristic? = null private var linkLossServerCharacteristic: BluetoothGattCharacteristic? = null private var isAlertEnabled = false private val data = MutableStateFlow(PRXData()) val dataHolder = ConnectionObserverAdapter<PRXData>() init { connectionObserver = dataHolder data.onEach { dataHolder.setValue(it) }.launchIn(scope) } override fun log(priority: Int, message: String) { logger.log(priority, message) } override fun getMinLogPriority(): Int { return Log.VERBOSE } private inner class ProximityManagerGattCallback : BleManagerGattCallback() { override fun initialize() { super.initialize() setWriteCallback(localAlertLevelCharacteristic) .with(object : AlertLevelDataCallback() { override fun onAlertLevelChanged(device: BluetoothDevice, level: Int) { data.value = data.value.copy(localAlarmLevel = AlarmLevel.create(level)) } }) setWriteCallback(linkLossServerCharacteristic) .with(object : AlertLevelDataCallback() { override fun onAlertLevelChanged(device: BluetoothDevice, level: Int) { data.value = data.value.copy(linkLossAlarmLevel = AlarmLevel.create(level)) } }) writeCharacteristic( linkLossCharacteristic, AlertLevelData.highAlert(), BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT ).enqueue() setNotificationCallback(batteryLevelCharacteristic) .asValidResponseFlow<BatteryLevelResponse>() .onEach { data.value = data.value.copy(batteryLevel = it.batteryLevel) }.launchIn(scope) enableNotifications(batteryLevelCharacteristic).enqueue() } override fun onServerReady(server: BluetoothGattServer) { val immediateAlertService = server.getService(PRX_SERVICE_UUID) if (immediateAlertService != null) { localAlertLevelCharacteristic = immediateAlertService.getCharacteristic(ALERT_LEVEL_CHARACTERISTIC_UUID) } val linkLossService = server.getService(LINK_LOSS_SERVICE_UUID) if (linkLossService != null) { linkLossServerCharacteristic = linkLossService.getCharacteristic(ALERT_LEVEL_CHARACTERISTIC_UUID) } } override fun isRequiredServiceSupported(gatt: BluetoothGatt): Boolean { gatt.getService(LINK_LOSS_SERVICE_UUID)?.run { linkLossCharacteristic = getCharacteristic(ALERT_LEVEL_CHARACTERISTIC_UUID) } gatt.getService(BATTERY_SERVICE_UUID)?.run { batteryLevelCharacteristic = getCharacteristic(BATTERY_LEVEL_CHARACTERISTIC_UUID) } gatt.getService(PRX_SERVICE_UUID)?.run { alertLevelCharacteristic = getCharacteristic(ALERT_LEVEL_CHARACTERISTIC_UUID) } return linkLossCharacteristic != null } override fun onServicesInvalidated() { batteryLevelCharacteristic = null alertLevelCharacteristic = null linkLossCharacteristic = null localAlertLevelCharacteristic = null linkLossServerCharacteristic = null isAlertEnabled = false } } fun writeImmediateAlert(on: Boolean) { if (!isConnected) return scope.launchWithCatch { writeCharacteristic( alertLevelCharacteristic, if (on) AlertLevelData.highAlert() else AlertLevelData.noAlert(), BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE ).suspend() isAlertEnabled = on data.value = data.value.copy(isRemoteAlarm = on) } } override fun getGattCallback(): BleManagerGattCallback { return ProximityManagerGattCallback() } }
bsd-3-clause
156924e1ba0a0f882aeac012b6e31188
41.578652
120
0.70669
4.889677
false
false
false
false
javiersantos/PiracyChecker
library/src/main/java/com/github/javiersantos/piracychecker/Extensions.kt
1
1795
@file:Suppress("unused") package com.github.javiersantos.piracychecker import android.content.Context import androidx.fragment.app.Fragment import com.github.javiersantos.piracychecker.callbacks.AllowCallback import com.github.javiersantos.piracychecker.callbacks.DoNotAllowCallback import com.github.javiersantos.piracychecker.callbacks.OnErrorCallback import com.github.javiersantos.piracychecker.callbacks.PiracyCheckerCallbacksDSL import com.github.javiersantos.piracychecker.enums.PiracyCheckerError import com.github.javiersantos.piracychecker.enums.PirateApp fun Context.piracyChecker(builder: PiracyChecker.() -> Unit): PiracyChecker { val checker = PiracyChecker(this) checker.builder() return checker } fun Fragment.piracyChecker(builder: PiracyChecker.() -> Unit): PiracyChecker = activity?.piracyChecker(builder) ?: requireContext().piracyChecker(builder) inline fun PiracyChecker.allow(crossinline allow: () -> Unit = {}) = apply { allowCallback(object : AllowCallback { override fun allow() = allow() }) } inline fun PiracyChecker.doNotAllow(crossinline doNotAllow: (PiracyCheckerError, PirateApp?) -> Unit = { _, _ -> }) = apply { doNotAllowCallback(object : DoNotAllowCallback { override fun doNotAllow(error: PiracyCheckerError, app: PirateApp?) = doNotAllow(error, app) }) } inline fun PiracyChecker.onError(crossinline onError: (PiracyCheckerError) -> Unit = {}) = apply { onErrorCallback(object : OnErrorCallback { override fun onError(error: PiracyCheckerError) { super.onError(error) onError(error) } }) } fun PiracyChecker.callback(callbacks: PiracyCheckerCallbacksDSL.() -> Unit) { PiracyCheckerCallbacksDSL(this).callbacks() }
apache-2.0
be09eebdec6f12d636406d982163d46c
36.416667
117
0.740947
4.107551
false
false
false
false
paronos/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/data/backup/serializer/MangaTypeAdapter.kt
4
1010
package eu.kanade.tachiyomi.data.backup.serializer import com.github.salomonbrys.kotson.typeAdapter import com.google.gson.TypeAdapter import eu.kanade.tachiyomi.data.database.models.MangaImpl /** * JSON Serializer used to write / read [MangaImpl] to / from json */ object MangaTypeAdapter { fun build(): TypeAdapter<MangaImpl> { return typeAdapter { write { beginArray() value(it.url) value(it.title) value(it.source) value(it.viewer) value(it.chapter_flags) endArray() } read { beginArray() val manga = MangaImpl() manga.url = nextString() manga.title = nextString() manga.source = nextLong() manga.viewer = nextInt() manga.chapter_flags = nextInt() endArray() manga } } } }
apache-2.0
01594c88554be859d05a53a255a087d6
26.324324
66
0.509901
5.024876
false
false
false
false
Sjtek/sjtekcontrol-core
core/src/main/kotlin/nl/sjtek/control/core/SunsetCalculator.kt
1
1601
package nl.sjtek.control.core import com.luckycatlabs.sunrisesunset.SunriseSunsetCalculator import com.luckycatlabs.sunrisesunset.dto.Location import nl.sjtek.control.core.settings.SettingsManager import org.slf4j.LoggerFactory import java.time.Instant import java.time.ZoneId import java.time.ZonedDateTime import java.util.* object SunsetCalculator { private val logger = LoggerFactory.getLogger(javaClass) private val calculator: SunriseSunsetCalculator private val timeZoneString: String private val timeZone: TimeZone val now: Calendar get() { return Calendar.getInstance(timeZone) } val nowHour: Int get() { val instant = Instant.now() val zoneId = ZoneId.of(timeZoneString) val zonedDateTime = ZonedDateTime.ofInstant(instant, zoneId) return zonedDateTime.hour } val sunrise: Int get() = calculator.getCivilSunriseCalendarForDate(now).get(Calendar.HOUR_OF_DAY) val sunset: Int get() = calculator.getCivilSunsetCalendarForDate(now).get(Calendar.HOUR_OF_DAY) val night: Boolean get() { logger.info("now: $nowHour sunrise: $sunrise sunset: $sunset") return nowHour >= sunset || nowHour <= sunrise } init { val settings = SettingsManager.settings.sunset val location = Location(settings.latitude, settings.longitude) timeZoneString = settings.timeZone timeZone = TimeZone.getTimeZone(timeZoneString) calculator = SunriseSunsetCalculator(location, timeZone) } }
gpl-3.0
5a9e894488fc680ee6046ddeda24c64a
33.06383
88
0.693941
4.422652
false
false
false
false
http4k/http4k
http4k-contract/src/test/kotlin/org/http4k/contract/ContractRendererContract.kt
1
12092
package org.http4k.contract import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import org.http4k.contract.security.ApiKeySecurity import org.http4k.contract.security.AuthCodeOAuthSecurity import org.http4k.contract.security.BasicAuthSecurity import org.http4k.contract.security.BearerAuthSecurity import org.http4k.contract.security.and import org.http4k.contract.security.or import org.http4k.core.Body import org.http4k.core.ContentType import org.http4k.core.ContentType.Companion.APPLICATION_FORM_URLENCODED import org.http4k.core.ContentType.Companion.APPLICATION_JSON import org.http4k.core.ContentType.Companion.APPLICATION_XML import org.http4k.core.ContentType.Companion.OCTET_STREAM import org.http4k.core.ContentType.Companion.TEXT_PLAIN import org.http4k.core.Credentials import org.http4k.core.HttpMessage import org.http4k.core.Method.GET import org.http4k.core.Method.POST import org.http4k.core.Method.PUT import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status.Companion.FORBIDDEN import org.http4k.core.Status.Companion.OK import org.http4k.core.Uri import org.http4k.core.with import org.http4k.format.Json import org.http4k.format.auto import org.http4k.lens.ContentNegotiation import org.http4k.lens.Cookies import org.http4k.lens.FormField import org.http4k.lens.Header import org.http4k.lens.Invalid import org.http4k.lens.LensFailure import org.http4k.lens.Meta import org.http4k.lens.Missing import org.http4k.lens.MultipartFormField import org.http4k.lens.MultipartFormFile import org.http4k.lens.ParamMeta.NumberParam import org.http4k.lens.ParamMeta.ObjectParam import org.http4k.lens.ParamMeta.StringParam import org.http4k.lens.Path import org.http4k.lens.Query import org.http4k.lens.Validator.Strict import org.http4k.lens.boolean import org.http4k.lens.enum import org.http4k.lens.int import org.http4k.lens.multipartForm import org.http4k.lens.string import org.http4k.lens.webForm import org.http4k.routing.bind import org.http4k.security.FakeOAuthPersistence import org.http4k.security.OAuthProvider import org.http4k.security.gitHub import org.http4k.testing.Approver import org.http4k.testing.JsonApprovalTest import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(JsonApprovalTest::class) abstract class ContractRendererContract<NODE : Any>( private val json: Json<NODE>, protected val rendererToUse: ContractRenderer ) { @Test fun `can build 400`() { val response = rendererToUse.badRequest( LensFailure( listOf( Missing(Meta(true, "location1", StringParam, "name1")), Invalid(Meta(false, "location2", NumberParam, "name2")) ) ) ) assertThat( response.bodyString(), equalTo("""{"message":"Missing/invalid parameters","params":[{"name":"name1","type":"location1","datatype":"string","required":true,"reason":"Missing"},{"name":"name2","type":"location2","datatype":"number","required":false,"reason":"Invalid"}]}""") ) } @Test fun `can build 404`() { val response = rendererToUse.notFound() assertThat( response.bodyString(), equalTo("""{"message":"No route found on this path. Have you used the correct HTTP verb?"}""") ) } @Test open fun `renders as expected`(approver: Approver) { val customBody = json.body("the body of the message").toLens() val negotiator = ContentNegotiation.auto( Body.string(ContentType("custom/v1")).toLens(), Body.string(ContentType("custom/v2")).toLens() ) val router = "/basepath" bind contract { renderer = rendererToUse tags += Tag("hello", "world") security = ApiKeySecurity(Query.required("the_api_key"), { true }) routes += "/nometa" bindContract GET to { _ -> Response(OK) } routes += "/descriptions" meta { summary = "endpoint" description = "some rambling description of what this thing actually does" operationId = "echoMessage" tags += Tag("tag3", "tag3 description") tags += Tag("tag1") markAsDeprecated() } bindContract GET to { _ -> Response(OK) } routes += "/paths" / Path.of("firstName") / "bertrand" / Path.boolean().of("age") / Path.enum<Foo>() .of("foo") bindContract POST to { a, _, _, _ -> { Response(OK).body(a) } } routes += "/queries" meta { queries += Query.boolean().multi.required("b", "booleanQuery") queries += Query.string().optional("s", "stringQuery") queries += Query.int().optional("i", "intQuery") queries += Query.enum<Foo>().optional("e", "enumQuery") queries += json.jsonLens(Query).optional("j", "jsonQuery") } bindContract POST to { _ -> Response(OK).body("hello") } routes += "/cookies" meta { cookies += Cookies.required("b", "requiredCookie") cookies += Cookies.optional("s", "optionalCookie") } bindContract POST to { _ -> Response(OK).body("hello") } routes += "/headers" meta { headers += Header.boolean().required("b", "booleanHeader") headers += Header.string().optional("s", "stringHeader") headers += Header.int().optional("i", "intHeader") headers += Header.enum<HttpMessage, Foo>().optional("e", "enumHeader") headers += json.jsonLens(Header).optional("j", "jsonHeader") } bindContract POST to { _ -> Response(OK).body("hello") } routes += "/body_receiving_string" meta { summary = "body_receiving_string" receiving(Body.string(TEXT_PLAIN).toLens() to "hello from the land of receiving plaintext") } bindContract POST to { _ -> Response(OK) } routes += "/body_string" meta { returning(OK, Body.string(TEXT_PLAIN).toLens() to "hello from the land of sending plaintext") } bindContract GET to { _ -> Response(OK) } routes += "/body_json_noschema" meta { receiving(json.body("json").toLens()) } bindContract POST to { _ -> Response(OK) } routes += "/body_json_response" meta { returning("normal" to json { val obj = obj("aNullField" to nullNode(), "aNumberField" to number(123)) Response(OK).with(body("json").toLens() of obj) }) } bindContract POST to { _ -> Response(OK) } routes += "/body_json_schema" meta { receiving(json.body("json").toLens() to json { obj("anAnotherObject" to obj("aNullField" to nullNode(), "aNumberField" to number(123))) }, "someDefinitionId", "prefix_") } bindContract POST to { _ -> Response(OK) } routes += "/body_json_list_schema" meta { receiving(json.body("json").toLens() to json { array(obj("aNumberField" to number(123))) }) } bindContract POST to { _ -> Response(OK) } routes += "/basic_auth" meta { security = BasicAuthSecurity("realm", credentials) } bindContract POST to { _ -> Response(OK) } routes += "/and_auth" meta { security = BasicAuthSecurity("foo", credentials, "and1").and(BasicAuthSecurity("foo", credentials, "and2")) } bindContract POST to { _ -> Response(OK) } routes += "/or_auth" meta { security = BasicAuthSecurity("foo", credentials, "or1").or(BasicAuthSecurity("foo", credentials, "or2")) } bindContract POST to { _ -> Response(OK) } routes += "/oauth2_auth" meta { security = AuthCodeOAuthSecurity( OAuthProvider.gitHub( { Response(OK) }, credentials, Uri.of("http://localhost/callback"), FakeOAuthPersistence(), listOf("user") ) ) } bindContract POST to { _ -> Response(OK) } routes += "/body_form" meta { receiving( Body.webForm( Strict, FormField.boolean().required("b", "booleanField"), FormField.int().multi.optional("i", "intField"), FormField.string().optional("s", "stringField"), FormField.enum<Foo>().optional("e", "enumField"), json.jsonLens(FormField).required("j", "jsonField") ).toLens() ) } bindContract POST to { _ -> Response(OK) } routes += "/produces_and_consumes" meta { produces += APPLICATION_JSON produces += APPLICATION_XML consumes += OCTET_STREAM consumes += APPLICATION_FORM_URLENCODED } bindContract GET to { _ -> Response(OK) } routes += "/returning" meta { returning("no way jose" to Response(FORBIDDEN).with(customBody of json { obj("aString" to string("a message of some kind")) })) } bindContract POST to { _ -> Response(OK) } routes += "/multipart-fields" meta { val field = MultipartFormField.multi.required("stringField") val pic = MultipartFormFile.required("fileField") val json = MultipartFormField.mapWithNewMeta({it}, {it}, ObjectParam).required("jsonField") receiving(Body.multipartForm(Strict, field, pic, json).toLens()) } bindContract PUT to { _ -> Response(OK) } routes += "/bearer_auth" meta { security = BearerAuthSecurity("foo") } bindContract POST to { _ -> Response(OK) } routes += "/body_negotiated" meta { receiving(negotiator to "john") returning(OK, negotiator to "john") } bindContract POST to { _ -> Response(OK) } } approver.assertApproved(router(Request(GET, "/basepath?the_api_key=somevalue"))) } @Test fun `when enabled renders description including its own path`(approver: Approver) { val router = "/" bind contract { renderer = rendererToUse security = ApiKeySecurity(Query.required("the_api_key"), { true }) routes += "/" bindContract GET to { _ -> Response(OK) } descriptionPath = "/docs" includeDescriptionRoute = true } approver.assertApproved(router(Request(GET, "/docs?the_api_key=somevalue"))) } @Test fun `duplicate schema models are not rendered`(approver: Approver) { val router = "/" bind contract { renderer = rendererToUse routes += Path.enum<Foo>() .of("enum") bindContract POST to { _ -> { _: Request -> Response(OK) } } routes += Path.enum<Foo>() .of("enum") bindContract GET to { _ -> { _: Request -> Response(OK) } } descriptionPath = "/docs" } approver.assertApproved(router(Request(GET, "/docs"))) } } private val credentials = Credentials("user", "password") enum class Foo { bar, bing } data class ArbObject1(val anotherString: Foo) data class ArbObject2(val string: String, val child: ArbObject1?, val numbers: List<Int>, val bool: Boolean) data class ArbObject3(val uri: Uri, val additional: Map<String, *>) data class ArbObject4(val anotherString: Foo) interface ObjInterface data class Impl1(val value: String = "bob") : ObjInterface data class Impl2(val value: Int = 123) : ObjInterface data class InterfaceHolder(val obj: ObjInterface)
apache-2.0
380e1e81ab7edf6b91db2ab8ed76ea2a
45.507692
261
0.600232
4.235377
false
false
false
false
openMF/android-client
mifosng-android/src/main/java/com/mifos/mifosxdroid/online/collectionsheetindividualdetails/IndividualCollectionSheetDetailsPresenter.kt
1
4104
package com.mifos.mifosxdroid.online.collectionsheetindividualdetails import com.mifos.api.DataManager import com.mifos.api.GenericResponse import com.mifos.api.datamanager.DataManagerCollectionSheet import com.mifos.api.model.IndividualCollectionSheetPayload import com.mifos.mifosxdroid.base.BasePresenter import com.mifos.objects.accounts.loan.PaymentTypeOptions import com.mifos.objects.collectionsheet.ClientCollectionSheet import com.mifos.objects.collectionsheet.LoanAndClientName import com.mifos.utils.MFErrorParser import retrofit2.adapter.rxjava.HttpException import rx.Observable import rx.Subscriber import rx.android.schedulers.AndroidSchedulers import rx.plugins.RxJavaPlugins import rx.schedulers.Schedulers import rx.subscriptions.CompositeSubscription import java.util.* import javax.inject.Inject /** * Created by aksh on 20/6/18. */ class IndividualCollectionSheetDetailsPresenter @Inject internal constructor(private val mDataManager: DataManager, private val mDataManagerCollection: DataManagerCollectionSheet) : BasePresenter<IndividualCollectionSheetDetailsMvpView?>() { private val mSubscription: CompositeSubscription? override fun attachView(mvpView: IndividualCollectionSheetDetailsMvpView?) { super.attachView(mvpView) } override fun detachView() { super.detachView() mSubscription?.unsubscribe() } fun submitIndividualCollectionSheet(individualCollectionSheetPayload: IndividualCollectionSheetPayload?) { checkViewAttached() mvpView!!.showProgressbar(true) mSubscription!!.add(mDataManagerCollection .saveIndividualCollectionSheet(individualCollectionSheetPayload) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(object : Subscriber<GenericResponse?>() { override fun onCompleted() {} override fun onError(e: Throwable) { mvpView!!.showProgressbar(false) try { if (e is HttpException) { val errorMessage = e.response().errorBody() .string() mvpView!!.showError(MFErrorParser.parseError(errorMessage) .errors[0].defaultUserMessage) } } catch (throwable: Throwable) { RxJavaPlugins.getInstance().errorHandler.handleError(e) } } override fun onNext(genericResponse: GenericResponse?) { mvpView!!.showProgressbar(false) mvpView!!.showSuccess() } })) } fun filterPaymentTypeOptions(paymentTypeOptionsList: List<PaymentTypeOptions>?): List<String> { val paymentList: MutableList<String> = ArrayList() Observable.from(paymentTypeOptionsList) .subscribe { paymentTypeOption -> paymentList.add(paymentTypeOption.name) } return paymentList } fun filterLoanAndClientNames(clientCollectionSheets: List<ClientCollectionSheet>?): List<LoanAndClientName> { val loansAndClientNames: MutableList<LoanAndClientName> = ArrayList() Observable.from(clientCollectionSheets) .subscribe { clientCollectionSheet -> if (clientCollectionSheet.loans != null) { for (loanCollectionSheet in clientCollectionSheet.loans) { loansAndClientNames.add(LoanAndClientName(loanCollectionSheet, clientCollectionSheet.clientName, clientCollectionSheet.clientId)) } } } return loansAndClientNames } init { mSubscription = CompositeSubscription() } }
mpl-2.0
62b8d66c1d36e8fc8bd365bb3d63d831
43.619565
202
0.628899
6.053097
false
false
false
false
square/duktape-android
zipline-loader/src/jniMain/kotlin/app/cash/zipline/loader/loaderJni.kt
1
1350
/* * Copyright (C) 2022 Block, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.cash.zipline.loader import app.cash.zipline.EventListener import app.cash.zipline.loader.internal.systemEpochMsClock import kotlinx.coroutines.CoroutineDispatcher import okhttp3.OkHttpClient fun ZiplineLoader( dispatcher: CoroutineDispatcher, manifestVerifier: ManifestVerifier, httpClient: OkHttpClient, eventListener: EventListener = EventListener.NONE, nowEpochMs: () -> Long = systemEpochMsClock, ): ZiplineLoader { return ZiplineLoader( dispatcher = dispatcher, manifestVerifier = manifestVerifier, httpClient = httpClient.asZiplineHttpClient(), eventListener = eventListener, nowEpochMs = nowEpochMs, ) } fun OkHttpClient.asZiplineHttpClient(): ZiplineHttpClient = OkHttpZiplineHttpClient(this)
apache-2.0
12c2a402938a1e3fadf52233a9af26f2
33.615385
89
0.768889
4.455446
false
false
false
false
mingdroid/tumbviewer
app/src/main/java/com/nutrition/express/ui/post/tagged/TaggedViewModel.kt
1
1113
package com.nutrition.express.ui.post.tagged import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.switchMap import androidx.lifecycle.viewModelScope import com.nutrition.express.model.api.Resource import com.nutrition.express.model.api.repo.TaggedRepo class TaggedViewModel : ViewModel() { private val taggedRepo = TaggedRepo(viewModelScope.coroutineContext) private val filter = "html" private val limit = 20 private val _postData = MutableLiveData<TaggedRequest>() val postData = _postData.switchMap { taggedRepo.getTaggedPosts(it.tag, null, it.featuredTimestamp, limit) } fun retryIfFailed() { if (postData.value is Resource.Error) { _postData.value = _postData.value } } fun setTag(tag: String) { _postData.value = TaggedRequest(tag, null) } fun getNextPage(featuredTimestamp: Long?) { _postData.value?.let { _postData.value = TaggedRequest(it.tag, featuredTimestamp) } } data class TaggedRequest(val tag: String, val featuredTimestamp: Long?); }
apache-2.0
5bd7b16cf3c2066d34bea47ecc41efda
29.944444
91
0.720575
4.091912
false
false
false
false
rascarlo/AURdroid
app/src/main/java/com/rascarlo/aurdroid/searchResult/SearchResultAdapter.kt
1
2211
package com.rascarlo.aurdroid.searchResult import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.rascarlo.aurdroid.databinding.SearchResultItemBinding import com.rascarlo.aurdroid.network.SearchResult /** * list adapter for [SearchResultFragment] */ class SearchResultAdapter(private val onClickListener: OnClickListener) : ListAdapter<SearchResult, SearchResultAdapter.SearchResultViewHolder>(DiffCallback) { /** * diff util callback for [SearchResult] * wrapper into a companion object * use [SearchResult] to compare if [areItemsTheSame] * use [SearchResult.id] to compare if [areContentsTheSame] */ private companion object DiffCallback : DiffUtil.ItemCallback<SearchResult>() { override fun areItemsTheSame(oldItem: SearchResult, newItem: SearchResult): Boolean { return oldItem == newItem } override fun areContentsTheSame(oldItem: SearchResult, newItem: SearchResult): Boolean { return oldItem.id == newItem.id } } // view holder class SearchResultViewHolder(private var binding: SearchResultItemBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(searchResult: SearchResult) { binding.searchResult = searchResult binding.executePendingBindings() } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SearchResultViewHolder { val layoutInflater = LayoutInflater.from(parent.context) return SearchResultViewHolder( SearchResultItemBinding.inflate(layoutInflater, parent, false) ) } override fun onBindViewHolder(holder: SearchResultViewHolder, position: Int) { val searchResult = getItem(position) holder.bind(searchResult) holder.itemView.setOnClickListener { onClickListener.onClick(searchResult) } } class OnClickListener(val clickListener: (searchResult: SearchResult) -> Unit) { fun onClick(searchResult: SearchResult) = clickListener(searchResult) } }
gpl-3.0
848a01462268e4da28fdd9700a77612b
37.137931
96
0.730439
5.392683
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/dialogs/ScopedStorageMigrationDialog.kt
1
7122
/* * Copyright (c) 2021 David Allison <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.anki.dialogs import android.annotation.SuppressLint import android.app.Dialog import android.content.Context import android.net.Uri import android.view.ContextThemeWrapper import android.view.LayoutInflater import android.view.View import android.widget.CheckBox import androidx.appcompat.app.AlertDialog import androidx.core.text.parseAsHtml import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.customview.customView import com.afollestad.materialdialogs.utils.MDUtil import com.ichi2.anki.AnkiActivity import com.ichi2.anki.AnkiDroidApp import com.ichi2.anki.R import com.ichi2.anki.UIUtils import com.ichi2.anki.preferences.Preferences import com.ichi2.themes.Themes import com.ichi2.ui.FixedTextView import makeLinksClickable import org.intellij.lang.annotations.Language import timber.log.Timber typealias OpenUri = (Uri) -> Unit /** * Informs the user that a scoped storage migration will occur * * Explains risks of not migrating * Explains time taken to migrate * Obtains consent * * For info, see: docs\scoped_storage\README.md * For design decisions, see: docs\scoped_storage\consent.md */ object ScopedStorageMigrationDialog { @Suppress("Deprecation") // Material dialog neutral button deprecation @SuppressLint("CheckResult") fun showDialog(ctx: Context, openUri: OpenUri, initiateScopedStorage: Runnable): Dialog { return MaterialDialog(ctx).show { title(R.string.scoped_storage_title) message(R.string.scoped_storage_initial_message) positiveButton(R.string.scoped_storage_migrate) { run { ScopedStorageMigrationConfirmationDialog.showDialog(ctx, initiateScopedStorage) dismiss() } } neutralButton(R.string.scoped_storage_learn_more) { // TODO: Discuss regarding alternatives to using a neutral button here // since it is deprecated and not recommended in material guidelines openMoreInfo(ctx, openUri) } negativeButton(R.string.scoped_storage_postpone) { dismiss() } cancelable(false) noAutoDismiss() } } } /** * Obtains explicit consent that: * * * User will not uninstall the app * * User has either * * performed an AnkiWeb sync (if an account is found) * * performed a regular backup * * Then performs a migration to scoped storage */ object ScopedStorageMigrationConfirmationDialog { @SuppressLint("CheckResult") fun showDialog(ctx: Context, initiateScopedStorage: Runnable): Dialog { val li = LayoutInflater.from(ctx) val view = li.inflate(R.layout.scoped_storage_confirmation, null) // scoped_storage_terms_message requires a format arg: estimated time taken val textView = view.findViewById<FixedTextView>(R.id.scoped_storage_content) textView.text = ctx.getString(R.string.scoped_storage_terms_message, "??? minutes") val userWillNotUninstall = view.findViewById<CheckBox>(R.id.scoped_storage_no_uninstall) val noAnkiWeb = view.findViewById<CheckBox>(R.id.scoped_storage_no_ankiweb) val ifAnkiWeb = view.findViewById<CheckBox>(R.id.scoped_storage_ankiweb) // If the user has an AnkiWeb account, ask them to sync, otherwise ask them to backup val hasAnkiWebAccount = Preferences.hasAnkiWebAccount(AnkiDroidApp.getSharedPrefs(ctx)) val backupMethodToDisable = if (hasAnkiWebAccount) noAnkiWeb else ifAnkiWeb val backupMethodToUse = if (hasAnkiWebAccount) ifAnkiWeb else noAnkiWeb backupMethodToDisable.visibility = View.GONE // hack: should be performed in custom_material_dialog_content style getContentColor(ctx)?.let { textView.setTextColor(it) userWillNotUninstall.setTextColor(it) noAnkiWeb.setTextColor(it) ifAnkiWeb.setTextColor(it) } val checkboxesRequiredToContinue = listOf(userWillNotUninstall, backupMethodToUse) return MaterialDialog(ctx).show { customView(view = view, scrollable = true) title(R.string.scoped_storage_title) positiveButton(R.string.scoped_storage_migrate) { if (checkboxesRequiredToContinue.all { x -> x.isChecked }) { Timber.i("starting scoped storage migration") dismiss() initiateScopedStorage.run() } else { UIUtils.showThemedToast(ctx, R.string.scoped_storage_select_all_terms, true) } } negativeButton(R.string.scoped_storage_postpone) { dismiss() } cancelable(false) noAutoDismiss() } } private fun getContentColor(ctx: Context): Int? { return try { val theme = if (Themes.currentTheme.isNightMode) com.afollestad.materialdialogs.R.style.MD_Dark else com.afollestad.materialdialogs.R.style.MD_Light val contextThemeWrapper = ContextThemeWrapper(ctx, theme) val contentColorFallback = MDUtil.resolveColor(contextThemeWrapper, android.R.attr.textColorSecondary) MDUtil.resolveColor(contextThemeWrapper, com.afollestad.materialdialogs.R.attr.md_color_content, contentColorFallback) } catch (e: Exception) { null } } } /** Opens more info about scoped storage (AnkiDroid wiki) */ private fun openMoreInfo(ctx: Context, openUri: (Uri) -> (Unit)) { val faqUri = Uri.parse(ctx.getString(R.string.link_scoped_storage_faq)) openUri(faqUri) } fun openUrl(activity: AnkiActivity): OpenUri = activity::openUrl /** * Set [message] as the dialog message, followed by "Learn More", as a link to Scoped Storage faq. * Then show the dialog. * @return the dialog */ fun AlertDialog.Builder.addScopedStorageLearnMoreLinkAndShow(@Language("HTML") message: String): AlertDialog { @Language("HTML") val messageWithLink = """$message <br> <br><a href='${context.getString(R.string.link_scoped_storage_faq)}'>${context.getString(R.string.scoped_storage_learn_more)}</a> """.trimIndent().parseAsHtml() setMessage(messageWithLink) return makeLinksClickable().apply { show() } }
gpl-3.0
e25e82a0a765c1a32e7b88ca643b2196
39.237288
160
0.690677
4.372007
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/test/java/com/ichi2/libanki/FinderTest.kt
1
20218
/* Copyright (c) 2020 David Allison <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.libanki import android.content.Intent import androidx.test.ext.junit.runners.AndroidJUnit4 import com.ichi2.anki.CardBrowser import com.ichi2.anki.RobolectricTest import com.ichi2.anki.exception.ConfirmModSchemaException import com.ichi2.libanki.Consts.CARD_TYPE_REV import com.ichi2.libanki.Consts.QUEUE_TYPE_REV import com.ichi2.libanki.Consts.QUEUE_TYPE_SUSPENDED import com.ichi2.libanki.sched.SchedV2 import com.ichi2.libanki.stats.Stats import com.ichi2.libanki.utils.TimeManager import com.ichi2.testutils.AnkiAssert import net.ankiweb.rsdroid.BackendFactory import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.greaterThan import org.hamcrest.Matchers.hasItem import org.hamcrest.Matchers.hasSize import org.junit.Assert.* import org.junit.Test import org.junit.runner.RunWith import org.robolectric.annotation.Config import timber.log.Timber import java.util.* @RunWith(AndroidJUnit4::class) class FinderTest : RobolectricTest() { @Test @Config(qualifiers = "en") @Throws( ConfirmModSchemaException::class ) fun searchForBuriedReturnsManuallyAndSiblingBuried() { val searchQuery = "is:buried" val sched = upgradeToSchedV2() // needs to be first enableBurySiblings() super.addNoteUsingModelName("Basic (and reversed card)", "Front", "Back") val toAnswer: Card = sched.card!! // act val siblingBuried = burySiblings(sched, toAnswer) val manuallyBuriedCard = buryManually(sched, toAnswer.id) // perform the search val buriedCards = Finder(col).findCards(searchQuery, SortOrder.NoOrdering()) // assert assertThat( "A manually buried card should be returned", buriedCards, hasItem(manuallyBuriedCard.id) ) assertThat( "A sibling buried card should be returned", buriedCards, hasItem(siblingBuried.id) ) assertThat( "sibling and manually buried should be the only cards returned", buriedCards, hasSize(2) ) } private fun enableBurySiblings() { val config = col.decks.allConf()[0] config.getJSONObject("new").put("bury", true) col.decks.save(config) } private fun burySiblings(sched: SchedV2, toManuallyBury: Card): Card { sched.answerCard(toManuallyBury, Consts.BUTTON_ONE) val siblingBuried = Note(col, toManuallyBury.nid).cards()[1] assertThat(siblingBuried.queue, equalTo(Consts.QUEUE_TYPE_SIBLING_BURIED)) return siblingBuried } private fun buryManually(sched: SchedV2, id: Long): Card { sched.buryCards(longArrayOf(id), true) val manuallyBuriedCard = Card(col, id) assertThat( manuallyBuriedCard.queue, equalTo(Consts.QUEUE_TYPE_MANUALLY_BURIED) ) return manuallyBuriedCard } /***************** * autogenerated from https://github.com/ankitects/anki/blob/2c73dcb2e547c44d9e02c20a00f3c52419dc277b/pylib/tests/test_cards.py* */ private fun isNearCutoff(): Boolean { val hour = TimeManager.time.calendar()[Calendar.HOUR_OF_DAY] return (hour >= 2) && (hour < 4) } @Test fun test_findCards() { TimeManager.reset() val col = col var note = col.newNote() note.setItem("Front", "dog") note.setItem("Back", "cat") note.addTag("monkey animal_1 * %") col.addNote(note) val n1id = note.id val firstCardId = note.cards()[0].id note = col.newNote() note.setItem("Front", "goats are fun") note.setItem("Back", "sheep") note.addTag("sheep goat horse animal11") col.addNote(note) val n2id = note.id note = col.newNote() note.setItem("Front", "cat") note.setItem("Back", "sheep") col.addNote(note) val catCard = note.cards()[0] var m = col.models.current() m = col.models.copy(m!!) val mm = col.models val t = Models.newTemplate("Reverse") t.put("qfmt", "{{Back}}") t.put("afmt", "{{Front}}") mm.addTemplateModChanged(m, t) mm.save(m) note = col.newNote() note.setItem("Front", "test") note.setItem("Back", "foo bar") col.addNote(note) col.save() val latestCardIds = note.cids() // tag searches assertEquals(5, col.findCards("tag:*").size) assertEquals(1, col.findCards("tag:\\*").size) assertEquals( if (BackendFactory.defaultLegacySchema) { 5 } else { 1 }, col.findCards("tag:%").size ) assertEquals(2, col.findCards("tag:animal_1").size) assertEquals(1, col.findCards("tag:animal\\_1").size) assertEquals(0, col.findCards("tag:donkey").size) assertEquals(1, col.findCards("tag:sheep").size) assertEquals(1, col.findCards("tag:sheep tag:goat").size) assertEquals(0, col.findCards("tag:sheep tag:monkey").size) assertEquals(1, col.findCards("tag:monkey").size) assertEquals(1, col.findCards("tag:sheep -tag:monkey").size) assertEquals(4, col.findCards("-tag:sheep").size) col.tags.bulkAdd(col.db.queryLongList("select id from notes"), "foo bar") assertEquals(5, col.findCards("tag:foo").size) assertEquals(5, col.findCards("tag:bar").size) col.tags.bulkAdd(col.db.queryLongList("select id from notes"), "foo", add = false) assertEquals(0, col.findCards("tag:foo").size) assertEquals(5, col.findCards("tag:bar").size) // text searches assertEquals(2, col.findCards("cat").size) assertEquals(1, col.findCards("cat -dog").size) assertEquals(1, col.findCards("cat -dog").size) assertEquals(1, col.findCards("are goats").size) assertEquals(0, col.findCards("\"are goats\"").size) assertEquals(1, col.findCards("\"goats are\"").size) // card states var c = note.cards()[0] c.queue = QUEUE_TYPE_REV c.type = CARD_TYPE_REV assertEquals(0, col.findCards("is:review").size) c.flush() AnkiAssert.assertEqualsArrayList(arrayOf(c.id), col.findCards("is:review")) assertEquals(0, col.findCards("is:due").size) c.due = 0 c.queue = QUEUE_TYPE_REV c.flush() AnkiAssert.assertEqualsArrayList(arrayOf(c.id), col.findCards("is:due")) assertEquals(4, col.findCards("-is:due").size) c.queue = QUEUE_TYPE_SUSPENDED // ensure this card gets a later mod time c.flush() col.db.execute("update cards set mod = mod + 1 where id = ?", c.id) AnkiAssert.assertEqualsArrayList(arrayOf(c.id), col.findCards("is:suspended")) // nids assertEquals(0, col.findCards("nid:54321").size) assertEquals(2, col.findCards("nid:" + note.id).size) assertEquals(2, col.findCards("nid:$n1id,$n2id").size) // templates assertEquals(0, col.findCards("card:foo").size) assertEquals(4, col.findCards("\"card:card 1\"").size) assertEquals(1, col.findCards("card:reverse").size) assertEquals(4, col.findCards("card:1").size) assertEquals(1, col.findCards("card:2").size) // fields assertEquals(1, col.findCards("front:dog").size) assertEquals(4, col.findCards("-front:dog").size) assertEquals(0, col.findCards("front:sheep").size) assertEquals(2, col.findCards("back:sheep").size) assertEquals(3, col.findCards("-back:sheep").size) assertEquals(0, col.findCards("front:do").size) assertEquals(5, col.findCards("front:*").size) // ordering col.set_config("sortType", "noteCrt") col.flush() assertTrue( latestCardIds.contains( col.findCards( "front:*", SortOrder.UseCollectionOrdering() ).last() ) ) assertTrue( latestCardIds.contains( col.findCards( "", SortOrder.UseCollectionOrdering() ).last() ) ) col.set_config("sortType", "noteFld") col.flush() assertEquals(catCard.id, col.findCards("", SortOrder.UseCollectionOrdering())[0]) assertTrue( latestCardIds.contains( col.findCards( "", SortOrder.UseCollectionOrdering() ).last() ) ) col.set_config("sortType", "cardMod") col.flush() assertTrue( latestCardIds.contains( col.findCards( "", SortOrder.UseCollectionOrdering() ).last() ) ) assertEquals(firstCardId, col.findCards("", SortOrder.UseCollectionOrdering())[0]) col.set_config("sortBackwards", true) col.flush() assertTrue(latestCardIds.contains(col.findCards("", SortOrder.UseCollectionOrdering())[0])) /* TODO: Port BuiltinSortKind assertEquals(firstCardId, col.findCards("", BuiltinSortKind.CARD_DUE, reverse=false).get(0) ); assertNotEquals(firstCardId, col.findCards("", BuiltinSortKind.CARD_DUE, reverse=true).get(0)); */ // model assertEquals(3, col.findCards("note:basic").size) assertEquals(2, col.findCards("-note:basic").size) assertEquals(5, col.findCards("-note:foo").size) // col assertEquals(5, col.findCards("deck:default").size) assertEquals(0, col.findCards("-deck:default").size) assertEquals(5, col.findCards("-deck:foo").size) assertEquals(5, col.findCards("deck:def*").size) assertEquals(5, col.findCards("deck:*EFAULT").size) assertEquals(0, col.findCards("deck:*cefault").size) // full search note = col.newNote() note.setItem("Front", "hello<b>world</b>") note.setItem("Back", "abc") col.addNote(note) // as it's the sort field, it matches assertEquals(2, col.findCards("helloworld").size) // assertEquals(, col.findCards("helloworld", full=true).size())2 This is commented upstream // if we put it on the back, it won't val noteFront = note.getItem("Front") val noteBack = note.getItem("Back") note.setItem("Front", noteBack) note.setItem("Back", noteFront) note.flush() assertEquals(0, col.findCards("helloworld").size) //  Those lines are commented above // assertEquals(, col.findCards("helloworld", full=true).size())2 // assertEquals(, col.findCards("back:helloworld", full=true).size()G)2 // searching for an invalid special tag should not error // TODO: ensure the search fail // assertThrows(Exception.class, () -> col.findCards("is:invalid").size()); // should be able to limit to parent col, no children var id = col.db.queryLongScalar("select id from cards limit 1") col.db.execute( "update cards set did = ? where id = ?", addDeck("Default::Child"), id ) col.save() assertEquals(7, col.findCards("deck:default").size) assertEquals(1, col.findCards("deck:default::child").size) assertEquals(6, col.findCards("deck:default -deck:default::*").size) // properties id = col.db.queryLongScalar("select id from cards limit 1") col.db.execute( "update cards set queue=2, ivl=10, reps=20, due=30, factor=2200 where id = ?", id ) assertEquals(1, col.findCards("prop:ivl>5").size) assertThat(col.findCards("prop:ivl<5").size, greaterThan(1)) assertEquals(1, col.findCards("prop:ivl>=5").size) assertEquals(0, col.findCards("prop:ivl=9").size) assertEquals(1, col.findCards("prop:ivl=10").size) assertThat(col.findCards("prop:ivl!=10").size, greaterThan(1)) assertEquals(1, col.findCards("prop:due>0").size) // due dates should work assertEquals(0, col.findCards("prop:due=29").size) assertEquals(1, col.findCards("prop:due=30").size) // ease factors assertEquals(0, col.findCards("prop:ease=2.3").size) assertEquals(1, col.findCards("prop:ease=2.2").size) assertEquals(1, col.findCards("prop:ease>2").size) assertThat(col.findCards("-prop:ease>2").size, greaterThan(1)) // recently failed if (!isNearCutoff()) { assertEquals(0, col.findCards("rated:1:1").size) assertEquals(0, col.findCards("rated:1:2").size) c = card!! col.sched.answerCard(c, Consts.BUTTON_TWO) assertEquals(0, col.findCards("rated:1:1").size) assertEquals(1, col.findCards("rated:1:2").size) c = card!! col.sched.answerCard(c, Consts.BUTTON_ONE) assertEquals(1, col.findCards("rated:1:1").size) assertEquals(1, col.findCards("rated:1:2").size) assertEquals(2, col.findCards("rated:1").size) assertEquals(1, col.findCards("rated:2:2").size) // added if (BackendFactory.defaultLegacySchema) { assertEquals(0, col.findCards("added:0").size) col.db.execute( "update cards set id = id - " + Stats.SECONDS_PER_DAY * 1000 + " where id = ?", id ) assertEquals( (col.cardCount() - 1), col.findCards("added:1").size ) assertEquals(col.cardCount(), col.findCards("added:2").size) } } else { Timber.w("some find tests disabled near cutoff") } // empty field assertEquals(0, col.findCards("front:").size) note = col.newNote() note.setItem("Front", "") note.setItem("Back", "abc2") assertEquals(1, col.addNote(note)) assertEquals(1, col.findCards("front:").size) // OR searches and nesting assertEquals(2, col.findCards("tag:monkey or tag:sheep").size) assertEquals(2, col.findCards("(tag:monkey OR tag:sheep)").size) assertEquals(6, col.findCards("-(tag:monkey OR tag:sheep)").size) assertEquals(2, col.findCards("tag:monkey or (tag:sheep sheep)").size) assertEquals(1, col.findCards("tag:monkey or (tag:sheep octopus)").size) // flag // Todo: ensure it fails // assertThrows(Exception.class, () -> col.findCards("flag:12")); } @Test fun test_findCardsHierarchyTag() { val col = col var note = col.newNote() note.setItem("Front", "foo") note.setItem("Back", "bar") note.addTag("cat1::some") col.addNote(note) note = col.newNote() note.setItem("Front", "foo") note.setItem("Back", "bar") note.addTag("cat1::something") col.addNote(note) note = col.newNote() note.setItem("Front", "foo") note.setItem("Front", "bar") note.addTag("cat2::some") col.addNote(note) note = col.newNote() note.setItem("Front", "foo") note.setItem("Back", "bar") note.addTag("cat2::some::something") col.addNote(note) col.save() assertEquals(0, col.findCards("tag:cat").size) assertEquals(4, col.findCards("tag:cat*").size) assertEquals(2, col.findCards("tag:cat1").size) assertEquals(2, col.findCards("tag:cat2").size) assertEquals(1, col.findCards("tag:cat1::some").size) assertEquals(2, col.findCards("tag:cat1::some*").size) assertEquals(1, col.findCards("tag:cat1::something").size) assertEquals(2, col.findCards("tag:cat2::some").size) assertEquals( if (BackendFactory.defaultLegacySchema) { 1 } else { 0 }, col.findCards("tag:cat2::some::").size ) } @Test fun test_deckNameContainingWildcardCanBeSearched() { val deck = "*Yr1::Med2::CAS4::F4: Renal::BRS (zanki)::HY" val col = col val currentDid = addDeck(deck) col.decks.select(currentDid) val note = col.newNote() note.setItem("Front", "foo") note.setItem("Back", "bar") note.model().put("did", currentDid) col.addNote(note) val did = note.firstCard().did assertEquals(currentDid, did) val cb = super.startActivityNormallyOpenCollectionWithIntent( CardBrowser::class.java, Intent() ) cb.deckSpinnerSelection!!.updateDeckPosition(currentDid) advanceRobolectricLooperWithSleep() assertEquals(1L, cb.cardCount.toLong()) } @Test fun test_findReplace() { val col = col val note = col.newNote() note.setItem("Front", "foo") note.setItem("Back", "bar") col.addNote(note) val note2 = col.newNote() note2.setItem("Front", "baz") note2.setItem("Back", "foo") col.addNote(note2) val nids = listOf(note.id, note2.id) // should do nothing assertEquals(0, col.findReplace(nids, "abc", "123")) // global replace assertEquals(2, col.findReplace(nids, "foo", "qux")) note.load() assertEquals("qux", note.getItem("Front")) note2.load() assertEquals("qux", note2.getItem("Back")) // single field replace assertEquals(1, col.findReplace(nids, "qux", "foo", "Front")) note.load() assertEquals("foo", note.getItem("Front")) note2.load() assertEquals("qux", note2.getItem("Back")) // regex replace assertEquals(0, col.findReplace(nids, "B.r", "reg")) note.load() assertNotEquals("reg", note.getItem("Back")) assertEquals(1, col.findReplace(nids, "B.r", "reg", true)) note.load() assertEquals(note.getItem("Back"), "reg") } @Test fun test_findDupes() { val col = col val note = col.newNote() note.setItem("Front", "foo") note.setItem("Back", "bar") col.addNote(note) val note2 = col.newNote() note2.setItem("Front", "baz") note2.setItem("Back", "bar") col.addNote(note2) val note3 = col.newNote() note3.setItem("Front", "quux") note3.setItem("Back", "bar") col.addNote(note3) val note4 = col.newNote() note4.setItem("Front", "quuux") note4.setItem("Back", "nope") col.addNote(note4) var r: List<Pair<String, List<Long>>> = col.findDupes("Back") var r0 = r[0] assertEquals("bar", r0.first) assertEquals(3, r0.second.size) // valid search r = col.findDupes("Back", "bar") r0 = r[0] assertEquals("bar", r0.first) assertEquals(3, r0.second.size) // excludes everything r = col.findDupes("Back", "invalid") assertEquals(0, r.size) // front isn't dupe assertEquals(0, col.findDupes("Front").size) } }
gpl-3.0
a23f3f9de500d05872f18f1962e6ee85
38.563601
132
0.592175
3.867802
false
true
false
false
fan123199/V2ex-simple
app/src/main/java/im/fdx/v2ex/view/ZoomOutPageTransform.kt
1
1836
package im.fdx.v2ex.view import android.annotation.SuppressLint import android.util.Log import android.view.View import androidx.viewpager.widget.ViewPager import kotlin.math.abs import kotlin.math.max class ZoomOutPageTransform : ViewPager.PageTransformer { @SuppressLint("NewApi") override fun transformPage(view: View, position: Float) { val pageWidth = view.width val pageHeight = view.height Log.e("TAG", "$view , $position") when { position < -1 -> // [-Infinity,-1) // This page is way off-screen to the left. view.alpha = 0f position <= 1 //a页滑动至b页 ; a页从 0.0 -1 ;b页从1 ~ 0.0 -> { // [-1,1] // Modify the default slide transition to shrink the page as well val scaleFactor = max(MIN_SCALE, 1 - abs(position)) val vertMargin = pageHeight * (1 - scaleFactor) / 2 val horzMargin = pageWidth * (1 - scaleFactor) / 2 if (position < 0) { view.translationX = horzMargin - vertMargin / 2 } else { view.translationX = -horzMargin + vertMargin / 2 } // Scale the page down (between MIN_SCALE and 1) view.scaleX = scaleFactor view.scaleY = scaleFactor // Fade the page relative to its size. view.alpha = MIN_ALPHA + (scaleFactor - MIN_SCALE) / (1 - MIN_SCALE) * (1 - MIN_ALPHA) } else -> // (1,+Infinity] // This page is way off-screen to the right. view.alpha = 0f } } companion object { private const val MIN_SCALE = 0.95f private const val MIN_ALPHA = 1f } }
apache-2.0
a91940fedaeb039b34e0d6ac9ade54a3
32
102
0.535832
4.238318
false
false
false
false
hubme/WorkHelperApp
app/src/main/java/com/king/app/workhelper/location/SomeSingleton.kt
1
739
package com.king.app.workhelper.location import android.content.Context class SomeSingleton(context: Context) { private val mContext: Context = context companion object { @Volatile private var instance: SomeSingleton? = null fun getInstance(context: Context): SomeSingleton { val i = instance if (i != null) { return i } return synchronized(this) { val i2 = instance if (i2 != null) { i2 } else { val created = SomeSingleton(context) instance = created created } } } } }
apache-2.0
12bb9b40b2bd78ed52cfbf11e4b942f5
23.666667
58
0.476319
5.394161
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/network/item/NetworkItemHelper.kt
1
2222
/* * 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.item import io.netty.handler.codec.DecoderException import io.netty.handler.codec.EncoderException import org.lanternpowered.api.item.ItemType import org.lanternpowered.server.network.buffer.ByteBuffer object NetworkItemHelper { fun readTypeFrom(buf: ByteBuffer): ItemType { val networkId = buf.readVarInt() return NetworkItemTypeRegistry.getByNetworkId(networkId)?.type ?: throw DecoderException("Received ItemStack with unknown network id: $networkId") } fun writeTypeTo(buf: ByteBuffer, type: ItemType) { val networkType = NetworkItemTypeRegistry.getByType(type) ?: throw EncoderException("Item type isn't registered: $type") buf.writeVarInt(networkType.networkId) } fun readRawFrom(buf: ByteBuffer): RawItemStack? { val exists = buf.readBoolean() if (!exists) return null val networkId = buf.readVarInt() if (networkId == -1) return null val key = NetworkItemTypeRegistry.getVanillaKeyByNetworkId(networkId) ?: throw DecoderException("Received ItemStack with unknown network id: $networkId") val amount = buf.readByte().toInt() val dataView = buf.readDataView() return RawItemStack(key, amount, dataView) } fun writeRawTo(buf: ByteBuffer, itemStack: RawItemStack?) { if (itemStack == null || itemStack.amount <= 0) { buf.writeBoolean(false) } else { val networkType = NetworkItemTypeRegistry.getByKey(itemStack.type) ?: throw EncoderException("Invalid item type: ${itemStack.type}") buf.writeBoolean(true) buf.writeVarInt(networkType.networkId) buf.writeByte(itemStack.amount.toByte()) buf.writeDataView(itemStack.dataView) } } }
mit
bbe37c7eb5c5d85a56c825f337b56a67
37.310345
99
0.668767
4.543967
false
false
false
false
Mithrandir21/Duopoints
app/src/main/java/com/duopoints/android/ui/views/ValueLabel.kt
1
2569
package com.duopoints.android.ui.views import android.content.Context import android.graphics.Color import android.util.AttributeSet import android.util.TypedValue import android.view.Gravity import android.view.View import android.widget.LinearLayout import com.duopoints.android.R import kotlinx.android.synthetic.main.custom_view_pointlabel.view.* class ValueLabel @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, defStyleRes: Int = 0) : LinearLayout(context, attrs, defStyleAttr, defStyleRes) { init { attrs?.let { val ta = context.obtainStyledAttributes(it, R.styleable.ValueLabel, 0, 0) val gravity: Int val pointText: String? val pointSize: Float val pointColor: Int val subtextText: String? val subtextSize: Float val subtextColor: Int try { gravity = ta.getInt(R.styleable.ValueLabel_pl_gravity, Gravity.CENTER) pointText = ta.getString(R.styleable.ValueLabel_pl_title_text) pointSize = ta.getDimension(R.styleable.ValueLabel_pl_title_size, 14.0f) pointColor = ta.getColor(R.styleable.ValueLabel_pl_title_color, Color.WHITE) subtextText = ta.getString(R.styleable.ValueLabel_pl_subtext_text) subtextSize = ta.getDimension(R.styleable.ValueLabel_pl_subtext_size, 14.0f) subtextColor = ta.getColor(R.styleable.ValueLabel_pl_subtext_color, Color.WHITE) } finally { ta.recycle() } View.inflate(context, R.layout.custom_view_pointlabel, this) this.gravity = gravity this.orientation = LinearLayout.VERTICAL pointLabelPoint.text = pointText pointLabelPoint.setTextSize(TypedValue.COMPLEX_UNIT_PX, pointSize) pointLabelPoint.setTextColor(pointColor) if (!subtextText.isNullOrBlank()) { pointLabelSubtext.text = subtextText pointLabelSubtext.setTextSize(TypedValue.COMPLEX_UNIT_PX, subtextSize) pointLabelSubtext.setTextColor(subtextColor) } else { pointLabelSubtext.visibility = View.GONE } } } fun setPoints(points: Int) { pointLabelPoint.text = points.toString() } fun setPoints(text: String) { pointLabelPoint.text = text } fun setSubtext(text: String) { pointLabelSubtext.text = text } }
gpl-3.0
c18e78e54ecbd242553902a3f0f87427
33.716216
136
0.640327
4.34687
false
false
false
false
clappr/clappr-android
clappr/src/main/kotlin/io/clappr/player/plugin/Loader.kt
1
3231
package io.clappr.player.plugin import io.clappr.player.base.BaseObject import io.clappr.player.base.Options import io.clappr.player.components.Container import io.clappr.player.components.Core import io.clappr.player.components.Playback import io.clappr.player.components.PlaybackEntry import io.clappr.player.plugin.container.ContainerPlugin import io.clappr.player.plugin.core.CorePlugin typealias PluginFactory<Context, Plugin> = (Context) -> Plugin typealias CorePluginFactory = PluginFactory<Core, CorePlugin?> typealias ContainerPluginFactory = PluginFactory<Container, ContainerPlugin?> sealed class PluginEntry(val name: String) { class Core(name: String, val factory: CorePluginFactory) : PluginEntry(name) class Container(name: String, val factory: ContainerPluginFactory) : PluginEntry(name) } object Loader { @JvmStatic private val registeredPlugins = mutableMapOf<String, PluginEntry>() @JvmStatic private val registeredPlaybacks = mutableListOf<PlaybackEntry>() @JvmStatic fun clearPlaybacks() { registeredPlaybacks.clear() } @JvmStatic fun clearPlugins() { registeredPlugins.clear() } @JvmStatic fun register(pluginEntry: PluginEntry) = pluginEntry.takeUnless { it.name.isEmpty() }?.let { registeredPlugins[it.name] = it true } ?: false @JvmStatic fun register(playbackEntry: PlaybackEntry) = playbackEntry.takeUnless { it.name.isEmpty() }?.let { entry -> registeredPlaybacks.removeAll { it.name == entry.name } registeredPlaybacks.add(0, entry) true } ?: false @JvmStatic fun unregisterPlugin(name: String) = name.takeIf { it.isNotEmpty() && registeredPlugins.containsKey(it) }?.let { registeredPlugins.remove(it) != null } ?: false @JvmStatic fun unregisterPlayback(name: String) = registeredPlaybacks.run { val entry = find { it.name == name } if (entry != null) remove(entry) else false } fun <Context : BaseObject> loadPlugins(context: Context, externalPlugins: List<PluginEntry> = emptyList()): List<Plugin> = mergeExternalPlugins(externalPlugins).values.mapNotNull { loadPlugin(context, it) } private fun mergeExternalPlugins(plugins: List<PluginEntry>): Map<String, PluginEntry> = plugins.filter { it.name.isNotEmpty() }.fold(HashMap(registeredPlugins)) { resultingMap, entry -> resultingMap[entry.name] = entry resultingMap } fun loadPlayback(source: String, mimeType: String? = null, options: Options): Playback? = try { val playbackEntry = registeredPlaybacks.first { it.supportsSource(source, mimeType) } playbackEntry.factory(source, mimeType, options) } catch (e: Exception) { null } private fun <C : BaseObject> loadPlugin(component: C, pluginEntry: PluginEntry): Plugin? = try { when (pluginEntry) { is PluginEntry.Core -> pluginEntry.factory(component as Core) is PluginEntry.Container -> pluginEntry.factory(component as Container) } } catch (e: Exception) { null } }
bsd-3-clause
8fdadcefdcc9c99ee60c625c915bc010
34.516484
126
0.680285
4.360324
false
false
false
false