repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
pdvrieze/ProcessManager
|
PMEditor/src/main/java/nl/adaptivity/android/graphics/AbstractLightView.kt
|
1
|
2083
|
/*
* Copyright (c) 2016.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.android.graphics
import nl.adaptivity.diagram.Drawable
import nl.adaptivity.diagram.android.LightView
abstract class AbstractLightView : LightView {
private var state = 0
override var isFocussed: Boolean
get() = hasState(Drawable.STATE_FOCUSSED)
set(focussed) {
setState(Drawable.STATE_FOCUSSED, focussed)
state = state or Drawable.STATE_FOCUSSED
}
override var isSelected: Boolean
get() = hasState(Drawable.STATE_SELECTED)
set(selected) {
setState(Drawable.STATE_SELECTED, selected)
state = state or Drawable.STATE_SELECTED
}
override var isTouched: Boolean
get() = hasState(Drawable.STATE_TOUCHED)
set(touched) {
setState(Drawable.STATE_TOUCHED, touched)
state = state or Drawable.STATE_TOUCHED
}
override var isActive: Boolean
get() = hasState(Drawable.STATE_ACTIVE)
set(active) {
setState(Drawable.STATE_ACTIVE, active)
state = state or Drawable.STATE_ACTIVE
}
protected fun setState(flag: Int, isFlagged: Boolean) {
if (isFlagged) {
state = state or flag
} else {
state = state and flag.inv()
}
}
protected fun hasState(state: Int): Boolean {
return this.state and state != 0
}
}
|
lgpl-3.0
|
11c8211bb6954fce4184191698e83d90
| 30.104478 | 112 | 0.659626 | 4.441365 | false | false | false | false |
pdvrieze/ProcessManager
|
PE-common/src/jvmMain/kotlin/nl/adaptivity/process/processModel/XPathHolder.kt
|
1
|
7131
|
/*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.processModel
import nl.adaptivity.process.util.Constants
import nl.adaptivity.util.MyGatheringNamespaceContext
import nl.adaptivity.xmlutil.*
import nl.adaptivity.xmlutil.util.CombiningNamespaceContext
import java.util.*
import java.util.logging.Level
import java.util.logging.Logger
import javax.xml.XMLConstants
import javax.xml.bind.annotation.XmlAttribute
import javax.xml.namespace.NamespaceContext
import javax.xml.namespace.QName
import javax.xml.xpath.XPathExpression
import javax.xml.xpath.XPathExpressionException
import javax.xml.xpath.XPathFactory
@OptIn(XmlUtilInternal::class)
actual abstract class XPathHolder : XMLContainer {
/**
* @see nl.adaptivity.process.processModel.IXmlResultType#setName(java.lang.String)
*/
actual var _name: String? = null
// @Volatile private var path: XPathExpression? = null // This is merely a cache.
private var pathString: String? = null
// TODO support a functionresolver
@Volatile
private var path: XPathExpression? = null
get() {
field?.let { return it }
return if (pathString == null) {
return SELF_PATH
} else {
XPathFactory.newInstance().newXPath().apply {
if (originalNSContext.iterator().hasNext()) {
namespaceContext = SimpleNamespaceContext.from(originalNSContext)
}
}.compile(pathString)
}.apply { field = this }
}
val xPath: XPathExpression? get() = path
actual constructor() : super()
actual constructor(
name: String?,
path: String?,
content: CharArray?,
originalNSContext: Iterable<Namespace>
) : super(originalNSContext, content ?: CharArray(0)) {
_name = name
setPath(originalNSContext, path)
}
actual fun getName() = _name ?: throw NullPointerException("Name not set")
actual fun setName(value: String) {
_name = value
}
@XmlAttribute(name = "xpath")
actual fun getPath(): String? {
return pathString
}
actual fun setPath(namespaceContext: Iterable<Namespace>, value: String?) {
if (pathString != null && pathString == value) {
return
}
path = null
pathString = value
updateNamespaceContext(namespaceContext)
assert(value == null || xPath != null)
}
@Throws(XmlException::class)
actual
override fun deserializeChildren(reader: XmlReader) {
val origContext = reader.namespaceContext
super.deserializeChildren(reader)
val namespaces = TreeMap<String, String>()
val gatheringNamespaceContext = CombiningNamespaceContext(
SimpleNamespaceContext.from(originalNSContext),
MyGatheringNamespaceContext(namespaces, origContext)
)
visitNamespaces(gatheringNamespaceContext)
if (namespaces.size > 0) {
addNamespaceContext(SimpleNamespaceContext(namespaces))
}
}
@Throws(XmlException::class)
actual override fun serializeAttributes(out: XmlWriter) {
super.serializeAttributes(out)
if (pathString != null) {
val namepaces = TreeMap<String, String>()
// Have a namespace that gathers those namespaces that are not known already in the outer context
val referenceContext = out.namespaceContext
// TODO streamline this, the right context should not require the filtering on the output context later.
val nsc = MyGatheringNamespaceContext(
namepaces,
referenceContext,
SimpleNamespaceContext.from(originalNSContext)
)
visitXpathUsedPrefixes(pathString, nsc)
for ((key, value) in namepaces) {
if (value != referenceContext.getNamespaceURI(key)) {
out.namespaceAttr(key, value)
}
}
out.attribute(null, "xpath", null, pathString!!)
}
out.writeAttribute("name", _name)
}
@Throws(XmlException::class)
protected actual override fun visitNamespaces(baseContext: NamespaceContext) {
path = null
if (pathString != null) {
visitXpathUsedPrefixes(pathString, baseContext)
}
super.visitNamespaces(baseContext)
}
actual override fun visitNamesInAttributeValue(
referenceContext: NamespaceContext,
owner: QName,
attributeName: QName,
attributeValue: CharSequence
) {
if (Constants.MODIFY_NS_STR == owner.getNamespaceURI() && (XMLConstants.NULL_NS_URI == attributeName.getNamespaceURI() || XMLConstants.DEFAULT_NS_PREFIX == attributeName.getPrefix()) && "xpath" == attributeName.getLocalPart()) {
visitXpathUsedPrefixes(attributeValue, referenceContext)
}
}
actual override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
if (!super.equals(other)) return false
other as XPathHolder
if (_name != other._name) return false
if (pathString != other.pathString) return false
return true
}
actual override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + (_name?.hashCode() ?: 0)
result = 31 * result + (pathString?.hashCode() ?: 0)
return result
}
companion object {
private val SELF_PATH: XPathExpression
init {
try {
SELF_PATH = XPathFactory.newInstance().newXPath().compile(".")
} catch (e: XPathExpressionException) {
throw RuntimeException(e)
}
}
}
}
internal actual fun visitXpathUsedPrefixes(path: CharSequence?, namespaceContext: NamespaceContext) {
if (! path.isNullOrEmpty()) {
try {
val xpf = XPathFactory.newInstance()
val xpath = xpf.newXPath()
xpath.namespaceContext = namespaceContext
xpath.compile(path.toString())
} catch (e: XPathExpressionException) {
Logger.getLogger(XPathHolder::class.java.simpleName).log(
Level.WARNING,
"The path used is not valid (" + path + ") - " + e.message,
e
)
}
}
}
|
lgpl-3.0
|
0f389b2de4915917de9fa113870cbcab
| 33.283654 | 236 | 0.635535 | 5.011244 | false | false | false | false |
WijayaPrinting/wp-javafx
|
openpss-client/src/com/hendraanggrian/openpss/api/PaymentsApi.kt
|
1
|
1228
|
package com.hendraanggrian.openpss.api
import com.hendraanggrian.openpss.nosql.StringId
import com.hendraanggrian.openpss.schema.Employee
import com.hendraanggrian.openpss.schema.Invoice
import com.hendraanggrian.openpss.schema.Payment
import com.hendraanggrian.openpss.schema.Payments
import io.ktor.client.request.get
import io.ktor.client.request.post
import io.ktor.http.HttpMethod
interface PaymentsApi : Api {
suspend fun getPayments(dateTime: Any): List<Payment> = client.get {
apiUrl(Payments.schemaName)
parameters("dateTime" to dateTime)
}
suspend fun addPayment(payment: Payment): Invoice = client.post {
apiUrl(Payments.schemaName)
jsonBody(payment)
}
suspend fun deletePayment(login: Employee, payment: Payment): Boolean = client.requestStatus(HttpMethod.Delete) {
apiUrl(Payments.schemaName)
jsonBody(payment)
parameters("login" to login.name)
}
suspend fun getPayments(invoiceId: StringId<*>): List<Payment> = client.get {
apiUrl("${Payments.schemaName}/$invoiceId")
}
suspend fun getPaymentDue(invoiceId: StringId<*>): Double = client.get {
apiUrl("${Payments.schemaName}/$invoiceId/due")
}
}
|
apache-2.0
|
67c29d6d49c7c60985518e170edf92be
| 32.189189 | 117 | 0.724756 | 4.35461 | false | false | false | false |
LanternPowered/LanternServer
|
src/main/kotlin/org/lanternpowered/server/statistic/LanternStatisticCategoryForCatalogType.kt
|
1
|
1767
|
/*
* 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.statistic
import com.google.common.reflect.TypeToken
import org.lanternpowered.api.key.NamespacedKey
import org.lanternpowered.api.catalog.CatalogType
import org.spongepowered.api.statistic.Statistic
import org.spongepowered.api.statistic.StatisticCategory
import org.spongepowered.api.text.translation.Translation
import java.util.Collections
class LanternStatisticCategoryForCatalogType<T : CatalogType>(
key: NamespacedKey, translation: Translation, private val catalogType: TypeToken<T>
) : AbstractStatisticCategory<Statistic.ForCatalog<T>>(key, translation), StatisticCategory.ForCatalogType<T> {
private val statistics = hashMapOf<T, Statistic.ForCatalog<T>>()
private val unmodifiableStatistics = Collections.unmodifiableCollection(this.statistics.values)
override fun getCatalogType() = this.catalogType
override fun getStatistics(): MutableCollection<Statistic.ForCatalog<T>> = this.unmodifiableStatistics
override fun addStatistic(statistic: Statistic.ForCatalog<T>) {
this.statistics[statistic.catalogType] = statistic
}
override fun getStatistic(catalogType: T): Statistic.ForCatalog<T> {
return this.statistics[catalogType] ?: throw IllegalStateException("Unable to find statistic for ${catalogType.key}")
}
override fun toStringHelper() = super.toStringHelper()
.add("catalogType", this.catalogType.rawType.name)
}
|
mit
|
37261e2a7630d7647f27a55405de89bb
| 42.097561 | 125 | 0.77193 | 4.554124 | false | false | false | false |
ntlv/BasicLauncher2
|
app/src/main/java/se/ntlv/basiclauncher/appgrid/DoubleTapMenuHandler.kt
|
1
|
1674
|
package se.ntlv.basiclauncher.appgrid
import android.content.Context
import android.util.Log
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import org.jetbrains.anko.AlertDialogBuilder
import rx.android.schedulers.AndroidSchedulers
import se.ntlv.basiclauncher.database.AppDetailRepository
import se.ntlv.basiclauncher.tag
class DoubleTapMenuHandler {
private val mDetector: GestureDetector
private val mDb: AppDetailRepository
private val mContext: Context
constructor(context: Context, db: AppDetailRepository) {
val simpleDetector = object : GestureDetector.SimpleOnGestureListener() {
override fun onDoubleTap(e: MotionEvent?): Boolean {
showMenu()
return true
}
}
mDb = db
mContext = context
mDetector = GestureDetector(context, simpleDetector)
}
private fun showMenu() {
mDb.getIgnoredApps()
.take(1)
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
val apps = it
val builder = AlertDialogBuilder(mContext)
builder.title("Restore ignored app")
builder.items(it.map { it.label }, {
mDb.updateAppDetails(apps[it].packageName, ignore = false)
})
builder.show()
}
}
val TAG = tag()
fun bind(eventOrigin: View?) {
eventOrigin?.setOnTouchListener { view, event ->
Log.d(TAG, "sample")
mDetector.onTouchEvent(event)
}
}
}
|
mit
|
45e1a0874fdc7c3839298ffb2781d220
| 29.436364 | 82 | 0.608722 | 5.150769 | false | false | false | false |
AgileVentures/MetPlus_resumeCruncher
|
crunchers/naiveBayes/src/main/kotlin/org/metplus/curriculum/cruncher/naivebayes/NaiveBayesMetaData.kt
|
1
|
631
|
package org.metplus.curriculum.cruncher.naivebayes
import org.metplus.cruncher.rating.CruncherMetaData
class NaiveBayesMetaData {
var metaData = CruncherMetaData(mutableMapOf())
var bestMatchCategory: String? = null
var totalProbability = 0.0
fun addToTotalProbability(probability: Double) {
totalProbability += probability
}
/**
* Function used to add a new category to the data
* @param category Name of the category
* @param probability Probability
*/
fun addCategory(category: String, probability: Double) {
metaData.metaData[category] = probability
}
}
|
gpl-3.0
|
bed3abda7779296953ddb4881f4b9463
| 25.333333 | 60 | 0.708399 | 4.539568 | false | false | false | false |
FHannes/intellij-community
|
uast/uast-java/src/org/jetbrains/uast/java/expressions/JavaUSimpleNameReferenceExpression.kt
|
2
|
2223
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.java
import com.intellij.psi.*
import org.jetbrains.uast.UElement
import org.jetbrains.uast.USimpleNameReferenceExpression
import org.jetbrains.uast.UTypeReferenceExpression
class JavaUSimpleNameReferenceExpression(
override val psi: PsiElement?,
override val identifier: String,
override val uastParent: UElement?,
val reference: PsiReference? = null
) : JavaAbstractUExpression(), USimpleNameReferenceExpression {
override fun resolve() = (reference ?: psi as? PsiReference)?.resolve()
override val resolvedName: String?
get() = ((reference ?: psi as? PsiReference)?.resolve() as? PsiNamedElement)?.name
}
class JavaUTypeReferenceExpression(
override val psi: PsiTypeElement,
override val uastParent: UElement?
) : JavaAbstractUExpression(), UTypeReferenceExpression {
override val type: PsiType
get() = psi.type
}
class LazyJavaUTypeReferenceExpression(
override val psi: PsiElement,
override val uastParent: UElement?,
private val typeSupplier: () -> PsiType
) : JavaAbstractUExpression(), UTypeReferenceExpression {
override val type: PsiType by lz { typeSupplier() }
}
class JavaClassUSimpleNameReferenceExpression(
override val identifier: String,
val ref: PsiJavaReference,
override val psi: PsiElement?,
override val uastParent: UElement?
) : JavaAbstractUExpression(), USimpleNameReferenceExpression {
override fun resolve() = ref.resolve()
override val resolvedName: String?
get() = (ref.resolve() as? PsiNamedElement)?.name
}
|
apache-2.0
|
2dcb90944fb9b44ac1cfce2eb90cbc94
| 36.694915 | 90 | 0.728745 | 4.984305 | false | false | false | false |
milos85vasic/Pussycat
|
Pussycat/src/main/kotlin/net/milosvasic/pussycat/color/Color.kt
|
1
|
313
|
package net.milosvasic.pussycat.color
object Color {
val RESET = "\u001B[0m"
val BLACK = "\u001B[30m"
val RED = "\u001B[31m"
val GREEN = "\u001B[32m"
val YELLOW = "\u001B[33m"
val BLUE = "\u001B[34m"
val PURPLE = "\u001B[35m"
val CYAN = "\u001B[36m"
val WHITE = "\u001B[37m"
}
|
apache-2.0
|
8c66807b50450f7bf99ee1910bc023dd
| 23.153846 | 37 | 0.591054 | 2.544715 | false | false | false | false |
SuperAwesomeLTD/sa-mobile-sdk-android
|
superawesome-common/src/main/java/tv/superawesome/sdk/publisher/common/ui/video/player/VideoPlayerController.kt
|
1
|
5025
|
package tv.superawesome.sdk.publisher.common.ui.video.player
import android.content.Context
import android.media.MediaPlayer
import android.media.MediaPlayer.*
import android.net.Uri
import android.os.CountDownTimer
class VideoPlayerController :
MediaPlayer(),
IVideoPlayerController,
OnPreparedListener,
OnErrorListener,
OnCompletionListener,
OnSeekCompleteListener {
private var listener: IVideoPlayerController.Listener? = null
private var countDownTimer: CountDownTimer? = null
// //////////////////////////////////////////////////////////////////////////////////////////////
// Custom safe play & prepare method
// //////////////////////////////////////////////////////////////////////////////////////////////
override fun play(context: Context, uri: Uri) {
try {
setDataSource(context, uri)
prepare()
} catch (e: Exception) {
listener?.onError(this, e, 0, 0)
}
}
override fun playAsync(context: Context, uri: Uri) {
try {
setDataSource(context, uri)
prepareAsync()
} catch (e: Exception) {
listener?.onError(this, e, 0, 0)
}
}
// //////////////////////////////////////////////////////////////////////////////////////////////
// Safe Media Player overrides
// //////////////////////////////////////////////////////////////////////////////////////////////
override fun destroy() {
try {
stop()
setDisplay(null)
release()
removeTimer()
} catch (ignored: Throwable) {
}
}
override fun reset() {
try {
removeTimer()
super.reset()
} catch (ignored: Exception) {
}
}
override val isIVideoPlaying: Boolean = false
override val iVideoDuration: Int = 10
override val currentIVideoPosition: Int = 0
override var videoIVideoWidth: Int = 100
private set
override var videoIVideoHeight: Int = 100
private set
override fun seekTo(position: Int) {
createTimer()
super.seekTo(position)
}
// //////////////////////////////////////////////////////////////////////////////////////////////
// Media Constrol setters & getters for the listeners
// //////////////////////////////////////////////////////////////////////////////////////////////
override fun setListener(listener: IVideoPlayerController.Listener) {
this.listener = listener
}
// //////////////////////////////////////////////////////////////////////////////////////////////
// Media Player listeners
// //////////////////////////////////////////////////////////////////////////////////////////////
override fun onPrepared(mediaPlayer: MediaPlayer) {
createTimer()
listener?.onPrepared(this)
}
override fun onSeekComplete(mediaPlayer: MediaPlayer) {
listener?.onSeekComplete(this)
}
override fun onCompletion(mediaPlayer: MediaPlayer) {
removeTimer()
// todo: add a "reset" here and see how it goes
listener?.onMediaComplete(this, currentPosition, duration)
}
// todo: why doesn't the video player stop at the error?
override fun onError(mediaPlayer: MediaPlayer, error: Int, payload: Int): Boolean {
removeTimer()
reset()
listener?.onError(this, Throwable(), 0, 0)
return false
}
// //////////////////////////////////////////////////////////////////////////////////////////////
// Timer
// //////////////////////////////////////////////////////////////////////////////////////////////
override fun createTimer() {
if (countDownTimer == null) {
countDownTimer = object : CountDownTimer(duration.toLong(), CountDownInterval) {
override fun onTick(remainingTime: Long) {
listener?.onTimeUpdated(
this@VideoPlayerController,
currentPosition,
duration
)
}
override fun onFinish() {
// not needed
}
}
countDownTimer?.start()
}
}
override fun removeTimer() {
countDownTimer?.cancel()
countDownTimer = null
}
override fun start() {
super.start()
createTimer()
}
override fun pause() {
super.pause()
removeTimer()
}
private fun onVideoSizeChanged(width: Int, height: Int) {
videoIVideoWidth = width
videoIVideoHeight = height
}
init {
setOnPreparedListener(this)
setOnCompletionListener(this)
setOnErrorListener(this)
setOnSeekCompleteListener(this)
setOnVideoSizeChangedListener { _, width, height ->
onVideoSizeChanged(width, height)
}
}
}
private const val CountDownInterval: Long = 500
|
lgpl-3.0
|
d0789727f838eefc75d0962f452008c0
| 30.4125 | 101 | 0.470448 | 6.150551 | false | false | false | false |
benkyokai/tumpaca
|
app/src/main/kotlin/com/tumpaca/tp/fragment/DashboardPageAdapter.kt
|
1
|
2255
|
package com.tumpaca.tp.fragment
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentStatePagerAdapter
import android.util.Log
import com.tumblr.jumblr.types.Post
import com.tumpaca.tp.fragment.post.*
import com.tumpaca.tp.model.AdPost
import com.tumpaca.tp.model.PostList
class DashboardPageAdapter(fm: FragmentManager, private val postList: PostList) : FragmentStatePagerAdapter(fm) {
companion object {
private const val TAG = "DashboardPageAdapter"
}
private val listener = object : PostList.ChangedListener {
override fun onChanged() {
Log.d(TAG, "call notifyDataSetChanged()")
notifyDataSetChanged()
}
}
// View に接続された
fun onBind() {
postList.addListeners(listener)
}
// View と切り離された
fun onUnbind() {
postList.removeListeners(listener)
}
override fun getItem(position: Int): Fragment {
val bundle = Bundle()
bundle.putInt("pageNum", position)
val post = postList.get(position)
val fragment = createFragment(post!!)
fragment.arguments = bundle
return fragment
}
override fun getCount(): Int {
return postList.size
}
private fun createFragment(post: Post): PostFragment {
if (post is AdPost) {
return AdPostFragment()
}
when (post.type) {
Post.PostType.TEXT -> {
return TextPostFragment()
}
Post.PostType.PHOTO -> {
return PhotoPostFragment()
}
Post.PostType.QUOTE -> {
return QuotePostFragment()
}
Post.PostType.LINK -> {
return LinkPostFragment()
}
Post.PostType.AUDIO -> {
return AudioPostFragment()
}
Post.PostType.VIDEO -> {
return VideoPostFragment()
}
else -> {
// CHAT, ANSWER, POSTCARDは来ないはず
throw IllegalArgumentException("post type is invalid: " + post.type.value)
}
}
}
}
|
gpl-3.0
|
830f9457f89fad3cdab147af775b046a
| 26.725 | 113 | 0.586829 | 4.798701 | false | false | false | false |
Saint1991/BindingSample
|
app/src/main/java/jp/co/saint/bindingsample/models/BindableUser.kt
|
1
|
937
|
package jp.co.saint.bindingsample.models
import android.databinding.BaseObservable
import android.databinding.Bindable
import jp.co.saint.bindingsample.BR
/**
* Created by Seiya on 2016/03/27.
*/
class BindableUser(firstName: String, lastName: String, age: Int): BaseObservable() {
private var _name: String = firstName + " " + lastName
var name: String
@Bindable get() = _name
set (value) {
_name = value
notifyPropertyChanged(BR.name)
}
private var _age: Int = age
var age: String
@Bindable get() = _age.toString()
set (value) {
this._age = Integer.parseInt(value)
notifyPropertyChanged(BR.age)
}
fun increaseAge() {
age = (_age + 1).toString()
}
fun decreaseAge() {
age = (_age - 1).toString()
}
// Primary Constructor
init {
this.name = firstName + " " + lastName
this.age = age.toString()
}
}
|
apache-2.0
|
d8b0c6ced2e99b885ba37f8d72797364
| 22.45 | 85 | 0.609392 | 3.855967 | false | false | false | false |
nemerosa/ontrack
|
ontrack-model/src/main/java/net/nemerosa/ontrack/model/security/TokenAuthenticationToken.kt
|
1
|
1523
|
package net.nemerosa.ontrack.model.security
import org.springframework.security.authentication.AbstractAuthenticationToken
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.util.DigestUtils
class TokenAuthenticationToken
private constructor(
private var token: String,
private val encodedToken: String,
authorities: Collection<GrantedAuthority>,
private val principal: Any
) : AbstractAuthenticationToken(authorities) {
/**
* Constructor used by filters.
*/
constructor(token: String) : this(
token = token,
encodedToken = "",
authorities = emptyList(),
principal = token
)
/**
* Constructor after authentication
*/
constructor(token: String, authorities: Collection<GrantedAuthority>, principal: UserDetails) : this(
token = "",
encodedToken = encode(token),
authorities = authorities,
principal = principal
) {
super.setAuthenticated(true)
}
override fun getCredentials(): Any = token
override fun getPrincipal(): Any = principal
override fun eraseCredentials() {
super.eraseCredentials()
token = ""
}
fun matches(token: String): Boolean = encodedToken == encode(token)
companion object {
private fun encode(token: String) = DigestUtils.md5DigestAsHex(token.toByteArray())
}
}
|
mit
|
2fe1f41acfa18763227f6e67f35b673c
| 28.307692 | 105 | 0.669731 | 5.251724 | false | false | false | false |
alpha-cross/ararat
|
library/src/main/java/org/akop/ararat/core/Crossword.kt
|
1
|
22908
|
// Copyright (c) Akop Karapetyan
//
// 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 org.akop.ararat.core
import android.os.Parcel
import android.os.Parcelable
import org.akop.ararat.util.sha1
import org.akop.ararat.util.toHexString
import java.io.ByteArrayOutputStream
import java.util.ArrayList
import java.util.HashSet
class Crossword internal constructor(val width: Int = 0,
val height: Int = 0,
val squareCount: Int = 0,
val flags: Int = 0,
val title: String? = null,
val description: String? = null,
val author: String? = null,
val copyright: String? = null,
val comment: String? = null,
val date: Long = 0,
wordsAcross: List<Word>? = null,
wordsDown: List<Word>? = null,
alphabet: Set<Char>? = null) : Parcelable {
val wordsAcross: List<Word> = ArrayList()
val wordsDown: List<Word> = ArrayList()
val alphabet: Set<Char> = HashSet()
private constructor(source: Parcel): this(
width = source.readInt(),
height = source.readInt(),
squareCount = source.readInt(),
flags = source.readInt(),
title = source.readString(),
description = source.readString(),
author = source.readString(),
copyright = source.readString(),
comment = source.readString(),
date = source.readLong(),
wordsAcross = source.createTypedArrayList(Word.CREATOR),
wordsDown = source.createTypedArrayList(Word.CREATOR),
alphabet = source.createCharArray()!!.toSet())
init {
wordsAcross?.let { (this.wordsAcross as MutableList) += it }
wordsDown?.let { (this.wordsDown as MutableList) += it }
alphabet?.let { (this.alphabet as MutableSet) += it }
}
val cellMap: Array<Array<Cell?>> by lazy { buildMap() }
val hash: String by lazy { femputeHash() }
class Builder() {
@set:JvmName("width")
var width: Int = 0
@set:JvmName("height")
var height: Int = 0
@set:JvmName("title")
var title: String? = null
@set:JvmName("description")
var description: String? = null
@set:JvmName("author")
var author: String? = null
@set:JvmName("copyright")
var copyright: String? = null
@set:JvmName("comment")
var comment: String? = null
@set:JvmName("date")
var date: Long = 0
@set:JvmName("flags")
var flags: Int = 0
val alphabet: MutableSet<Char> = HashSet(ALPHABET_ENGLISH)
val words: MutableList<Word> = ArrayList()
constructor(crossword: Crossword): this() {
width = crossword.width
height = crossword.height
title = crossword.title
description = crossword.description
author = crossword.author
comment = crossword.comment
copyright = crossword.copyright
date = crossword.date
flags = crossword.flags
alphabet.clear()
alphabet += crossword.alphabet
words += crossword.wordsAcross + crossword.wordsDown
}
fun setWidth(value: Int): Builder {
width = value
return this
}
fun setHeight(value: Int): Builder {
height = value
return this
}
fun setTitle(text: String?): Builder {
title = text
return this
}
fun setDescription(text: String?): Builder {
description = text
return this
}
fun setAuthor(text: String?): Builder {
author = text
return this
}
fun setCopyright(text: String?): Builder {
copyright = text
return this
}
fun setComment(text: String?): Builder {
comment = text
return this
}
fun setDate(value: Long): Builder {
date = value
return this
}
fun setFlags(value: Int): Builder {
flags = value
return this
}
fun addWord(word: Word): Builder {
words += word
return this
}
fun setAlphabet(alphabet: Set<Char>): Builder {
this.alphabet.clear()
this.alphabet += alphabet
return this
}
private fun countSquares(): Int {
var count = 0
val done = Array(height) { BooleanArray(width) }
for (word in words) {
when {
word.direction == Word.DIR_ACROSS -> {
word.directionRange
.filter { !done[word.startRow][it] }
.forEach {
count++
done[word.startRow][it] = true
}
}
word.direction == Word.DIR_DOWN -> {
word.directionRange
.filter { !done[it][word.startColumn] }
.forEach {
count++
done[it][word.startColumn] = true
}
}
}
}
return count
}
/* FIXME
fun autoNumber() {
// autonumber left-to-right, top-to-bottom
val tuples = Array(words.size) { IntArray(4) }
var i = 0
val n = words.size
while (i < n) {
val word = words[i]
tuples[i] = intArrayOf(i, word.startRow, word.startColumn, word.direction)
i++
}
Arrays.sort(tuples, Comparator { lhs, rhs ->
if (lhs[1] != rhs[1]) { // sort by row
return@Comparator lhs[1] - rhs[1]
}
if (lhs[2] != rhs[2]) { // sort by column
return@Comparator lhs[2] - rhs[2]
}
if (lhs[3] != rhs[3]) { // sort by direction
if (lhs[3] == Word.DIR_ACROSS) -1 else 1
} else 0
// Should never get here
})
var pr = -1
var pc = -1
var number = 0
for (tuple in tuples) {
if (pr != tuple[1] || pc != tuple[2]) {
number++
}
words[tuple[0]].number = number
pr = tuple[1]
pc = tuple[2]
}
}
*/
fun build(): Crossword = Crossword(
width = width,
height = height,
squareCount = countSquares(),
flags = flags,
title = title,
description = description,
author = author,
copyright = copyright,
comment = comment,
date = date,
wordsAcross = words
.filter { it.direction == Word.DIR_ACROSS }
.sortedBy { it.number },
wordsDown = words
.filter { it.direction == Word.DIR_DOWN }
.sortedBy { it.number },
alphabet = alphabet)
}
fun newState(): CrosswordState = CrosswordState(width, height)
fun previousWord(word: Word?): Word? {
if (word != null) {
val index = indexOf(word.direction, word.number)
when {
index > -1 && word.direction == Word.DIR_ACROSS -> when {
index > 0 -> return wordsAcross[index - 1]
wordsDown.isNotEmpty() -> return wordsDown.last()
}
index > -1 && word.direction == Word.DIR_DOWN -> when {
index > 0 -> return wordsDown[index - 1]
wordsAcross.isNotEmpty() -> return wordsAcross.last()
}
}
}
return when {
wordsDown.isNotEmpty() -> wordsDown.last()
wordsAcross.isNotEmpty() -> wordsAcross.last()
else -> null
}
}
fun nextWord(word: Word?): Word? {
if (word != null) {
val index = indexOf(word.direction, word.number)
when {
index > -1 && word.direction == Word.DIR_ACROSS -> when {
index < wordsAcross.lastIndex -> return wordsAcross[index + 1]
wordsDown.isNotEmpty() -> return wordsDown.first()
}
index > -1 && word.direction == Word.DIR_DOWN -> when {
index < wordsDown.lastIndex -> return wordsDown[index + 1]
wordsAcross.isNotEmpty() -> return wordsAcross.first()
}
}
}
return when {
wordsAcross.isNotEmpty() -> wordsAcross.first()
wordsDown.isNotEmpty() -> wordsDown.first()
else -> null
}
}
fun findWord(direction: Int, number: Int): Word? {
val index = indexOf(direction, number)
if (index < 0) return null
return when (direction) {
Word.DIR_ACROSS -> wordsAcross[index]
Word.DIR_DOWN -> wordsDown[index]
else -> throw IllegalArgumentException("Invalid word direction")
}
}
fun findWord(direction: Int, row: Int, column: Int): Word? {
return when (direction) {
Word.DIR_ACROSS -> wordsAcross.firstOrNull {
it.startRow == row && column >= it.startColumn
&& column < it.startColumn + it.length
}
Word.DIR_DOWN -> wordsDown.firstOrNull {
it.startColumn == column && row >= it.startRow
&& row < it.startRow + it.length
}
else -> throw IllegalArgumentException("Invalid word direction")
}
}
private fun indexOf(direction: Int, number: Int): Int {
return when (direction) {
Word.DIR_ACROSS -> wordsAcross.indexOfFirst { it.number == number }
Word.DIR_DOWN -> wordsDown.indexOfFirst { it.number == number }
else -> throw IllegalArgumentException("Invalid word direction")
}
}
private fun femputeHash(): String = ByteArrayOutputStream().use { s ->
CrosswordWriter(s).use { it.writeForHash(this) }
s.toByteArray()
}.sha1().toHexString()
private fun buildMap(): Array<Array<Cell?>> {
val map = Array(height) { arrayOfNulls<Cell>(width) }
wordsAcross.forEach { word ->
word.directionRange
.forEachIndexed { ix, col -> map[word.startRow][col] = word.cells[ix] }
}
wordsDown.forEach { word ->
word.directionRange
.forEachIndexed { ix, row -> map[row][word.startColumn] = word.cells[ix] }
}
return map
}
// FIXME: this shouldn't be here
fun updateStateStatistics(state: CrosswordState) {
if (state.width != width) {
throw RuntimeException("State width doesn't match puzzle width")
} else if (state.height != height) {
throw RuntimeException("State height doesn't match puzzle height")
}
var totalCount = 0
var solvedCount = 0
var cheatedCount = 0
var unknownCount = 0
var wrongCount = 0
val done = Array(height) { BooleanArray(width) }
val p = Pos()
for (word in wordsAcross + wordsDown) {
for (i in 0..word.cells.lastIndex) {
when (word.direction) {
Word.DIR_ACROSS -> p.set(word.startRow, word.startColumn + i)
Word.DIR_DOWN -> p.set(word.startRow + i, word.startColumn)
else -> throw RuntimeException("Unexpected direction")
}
if (done[p.r][p.c]) continue
totalCount++
val stateChar = state.charMatrix[p.r][p.c]
val cell = word.cells[i]
when {
(cell.attrFlags.toInt() and Cell.ATTR_NO_SOLUTION != 0)
&& stateChar != null -> unknownCount++
cell.contains(stateChar)
&& state.isFlagSet(CrosswordState.FLAG_CHEATED, p.r, p.c) -> cheatedCount++
cell.contains(stateChar) -> solvedCount++
stateChar != null -> wrongCount++
}
done[p.r][p.c] = true
}
}
state.setSquareStats(solvedCount, cheatedCount, wrongCount,
unknownCount, totalCount)
}
override fun describeContents(): Int = 0
override fun writeToParcel(dest: Parcel, parcelFlags: Int) {
dest.writeInt(width)
dest.writeInt(height)
dest.writeInt(squareCount)
dest.writeInt(flags)
dest.writeString(title)
dest.writeString(description)
dest.writeString(author)
dest.writeString(copyright)
dest.writeString(comment)
dest.writeLong(date)
dest.writeTypedList(wordsAcross)
dest.writeTypedList(wordsDown)
dest.writeCharArray(alphabet.toCharArray())
}
override fun hashCode(): Int = hash.hashCode()
override fun equals(other: Any?): Boolean = (other as? Crossword)?.hash == hash
class Cell internal constructor(val chars: String = "",
val attrFlags: Byte = 0): Parcelable {
val isEmpty: Boolean
get() = chars.isEmpty()
val isCircled: Boolean
get() = attrFlags.toInt() and ATTR_CIRCLED == ATTR_CIRCLED
private constructor(source: Parcel): this(
chars = source.readString()!!,
attrFlags = source.readByte())
fun chars(): String = chars
operator fun contains(charSought: String?): Boolean = chars == charSought
override fun describeContents(): Int = 0
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeString(chars)
dest.writeByte(attrFlags)
}
override fun toString(): String = when (chars.length) {
0 -> " "
1 -> chars[0].toString()
else -> "[$chars]"
}
companion object {
const val ATTR_CIRCLED = 1
const val ATTR_NO_SOLUTION = 2
@Suppress("unused")
@JvmField
val CREATOR: Parcelable.Creator<Cell> = object : Parcelable.Creator<Cell> {
override fun createFromParcel(source: Parcel): Cell = Cell(source)
override fun newArray(size: Int): Array<Cell?> = arrayOfNulls(size)
}
}
}
class Word internal constructor(val number: Int = 0,
val hint: String? = null,
val startRow: Int = 0,
val startColumn: Int = 0,
val direction: Int = 0,
val hintUrl: String? = null,
val citation: String? = null,
cells: Array<Cell>?) : Parcelable {
// FIXME: Mutable
internal val cells: Array<Cell>
init {
this.cells = cells?.copyOf() ?: EMPTY_CELL
if (direction != DIR_ACROSS && direction != DIR_DOWN) {
throw IllegalArgumentException("Direction not valid: $direction")
}
}
val length: Int
get() = cells.size
val directionRange: IntRange
get() = when (direction) {
DIR_ACROSS -> (startColumn..startColumn + cells.lastIndex)
DIR_DOWN -> (startRow..startRow + cells.lastIndex)
else -> throw RuntimeException("Unexpected direction: $direction")
}
class Builder {
@set:JvmName("number")
var number: Int = NUMBER_NONE
@set:JvmName("hint")
var hint: String? = null
@set:JvmName("startRow")
var startRow: Int = 0
@set:JvmName("startColumn")
var startColumn: Int = 0
@set:JvmName("direction")
var direction: Int = 0
@set:JvmName("hintUrl")
var hintUrl: String? = null
@set:JvmName("citation")
var citation: String? = null
val cells = ArrayList<Cell>()
fun setNumber(value: Int): Builder {
number = value
return this
}
fun setHint(text: String?): Builder {
hint = text
return this
}
fun setStartRow(value: Int): Builder {
startRow = value
return this
}
fun setStartColumn(value: Int): Builder {
startColumn = value
return this
}
fun setDirection(value: Int): Builder {
direction = value
return this
}
fun setHintUrl(text: String?): Builder {
hintUrl = text
return this
}
fun setCitation(text: String?): Builder {
citation = text
return this
}
fun addCell(ch: Char, attrFlags: Int = 0) = addCell(ch.toString(), attrFlags)
fun addCell(chars: String, attrFlags: Int = 0) {
cells.add(Cell(chars, attrFlags.toByte()))
}
fun build(): Word {
if (number == NUMBER_NONE)
throw RuntimeException("Missing hint number")
return Word(
number = number,
hint = hint,
startRow = startRow,
startColumn = startColumn,
direction = direction,
hintUrl = hintUrl,
citation = citation,
cells = cells.toTypedArray())
}
companion object {
const val NUMBER_NONE = -1
}
}
private constructor(source: Parcel): this(
number = source.readInt(),
hint = source.readString(),
startRow = source.readInt(),
startColumn = source.readInt(),
direction = source.readInt(),
hintUrl = source.readString(),
citation = source.readString(),
cells = source.readParcelableArray(Cell::class.java.classLoader)!!
.map { it as Cell }
.toTypedArray())
operator fun get(pos: Int): Cell = cells[pos]
fun cellAt(pos: Int): Cell = cells[pos]
override fun describeContents(): Int = 0
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeInt(number)
dest.writeString(hint)
dest.writeInt(startRow)
dest.writeInt(startColumn)
dest.writeInt(direction)
dest.writeString(hintUrl)
dest.writeString(citation)
dest.writeParcelableArray(cells, 0)
}
override fun equals(other: Any?): Boolean = (other as? Word)?.let {
it.direction == direction && it.number == number
} ?: false
override fun hashCode(): Int = "$direction-$number".hashCode()
override fun toString(): String = buildString {
append(number)
append(" ")
append(when (direction) {
DIR_ACROSS -> "Across"
DIR_DOWN -> "Down"
else -> "????"
})
append(": ")
append(hint)
append(" (")
append(cells.joinToString(""))
append(")")
}
companion object {
const val DIR_ACROSS = 0
const val DIR_DOWN = 1
private val EMPTY_CELL = arrayOf<Cell>()
@JvmField
val CREATOR: Parcelable.Creator<Word> = object : Parcelable.Creator<Word> {
override fun createFromParcel(source: Parcel): Word = Word(source)
override fun newArray(size: Int): Array<Word?> = arrayOfNulls(size)
}
}
}
companion object {
@JvmField
val ALPHABET_ENGLISH: Set<Char> = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray().toSet()
const val FLAG_NO_SOLUTION = 1
@JvmField
val CREATOR: Parcelable.Creator<Crossword> = object : Parcelable.Creator<Crossword> {
override fun createFromParcel(source: Parcel): Crossword = Crossword(source)
override fun newArray(size: Int): Array<Crossword?> = arrayOfNulls(size)
}
}
}
fun buildCrossword(block: Crossword.Builder.() -> Unit): Crossword =
Crossword.Builder().apply {
block(this)
}.build()
fun buildWord(block: Crossword.Word.Builder.() -> Unit): Crossword.Word =
Crossword.Word.Builder().apply {
block(this)
}.build()
|
mit
|
9c79b2e3f0420f159d625c2d2872a897
| 33.344828 | 103 | 0.501528 | 5.127126 | false | false | false | false |
d9n/intellij-rust
|
src/test/kotlin/org/rust/ide/refactoring/RsPromoteModuleToDirectoryActionTest.kt
|
1
|
1930
|
package org.rust.ide.refactoring
import com.intellij.idea.IdeaTestApplication
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.psi.PsiElement
import com.intellij.testFramework.TestDataProvider
import org.rust.FileTree
import org.rust.fileTree
import org.rust.lang.RsTestBase
import org.rust.lang.refactoring.RsPromoteModuleToDirectoryAction
class RsPromoteModuleToDirectoryActionTest : RsTestBase() {
fun `test works on file`() = checkAvailable(
"foo.rs",
fileTree {
rust("foo.rs", "fn hello() {}")
},
fileTree {
dir("foo") {
rust("mod.rs", "fn hello() {}")
}
}
)
fun `test not available on mod rs`() = checkNotAvailable(
"foo/mod.rs",
fileTree {
dir("foo") {
rust("mod.rs", "")
}
}
)
private fun checkAvailable(target: String, before: FileTree, after: FileTree) {
val baseDir = myFixture.findFileInTempDir(".")
val file = before.create(project, baseDir).psiFile(target)
testActionOnElement(file)
after.assertEquals(baseDir)
}
private fun checkNotAvailable(target: String, before: FileTree) {
val baseDir = myFixture.findFileInTempDir(".")
val file = before.create(project, baseDir).psiFile(target)
val presentation = testActionOnElement(file)
check(!presentation.isEnabled)
}
private fun testActionOnElement(element: PsiElement): Presentation {
IdeaTestApplication.getInstance().setDataProvider(object : TestDataProvider(project) {
override fun getData(dataId: String?): Any? =
if (CommonDataKeys.PSI_ELEMENT.`is`(dataId)) element else super.getData(dataId)
})
return myFixture.testAction(RsPromoteModuleToDirectoryAction())
}
}
|
mit
|
b39c9a59d225cffb8b196990f3818653
| 32.859649 | 95 | 0.654404 | 4.861461 | false | true | false | false |
d9n/intellij-rust
|
src/main/kotlin/org/rust/lang/core/resolve/ref/RsReferenceBase.kt
|
1
|
3238
|
package org.rust.lang.core.resolve.ref
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiPolyVariantReferenceBase
import com.intellij.psi.ResolveResult
import com.intellij.psi.impl.source.resolve.ResolveCache
import org.rust.lang.core.psi.RsElementTypes.IDENTIFIER
import org.rust.lang.core.psi.RsElementTypes.QUOTE_IDENTIFIER
import org.rust.lang.core.psi.RsPsiFactory
import org.rust.lang.core.psi.ext.RsCompositeElement
import org.rust.lang.core.psi.ext.RsNamedElement
import org.rust.lang.core.psi.ext.RsReferenceElement
import org.rust.lang.core.psi.ext.elementType
import org.rust.lang.core.types.BoundElement
abstract class RsReferenceBase<T : RsReferenceElement>(
element: T
) : PsiPolyVariantReferenceBase<T>(element),
RsReference {
abstract protected fun resolveInner(): List<BoundElement<RsCompositeElement>>
override fun resolve(): RsCompositeElement? = super.resolve() as? RsCompositeElement
override fun advancedResolve(): BoundElement<RsCompositeElement>? =
advancedCachedMultiResolve().firstOrNull()
final override fun multiResolve(incompleteCode: Boolean): Array<out ResolveResult> =
advancedCachedMultiResolve().toTypedArray()
final override fun multiResolve(): List<RsNamedElement> =
advancedCachedMultiResolve().mapNotNull { it.element as? RsNamedElement }
private fun advancedCachedMultiResolve(): List<BoundElement<RsCompositeElement>> {
return ResolveCache.getInstance(element.project)
.resolveWithCaching(this, Resolver,
/* needToPreventRecursion = */ true,
/* incompleteCode = */ false).orEmpty()
}
abstract val T.referenceAnchor: PsiElement
final override fun getRangeInElement(): TextRange = super.getRangeInElement()
final override fun calculateDefaultRangeInElement(): TextRange {
val anchor = element.referenceAnchor
check(anchor.parent === element)
return TextRange.from(anchor.startOffsetInParent, anchor.textLength)
}
override fun handleElementRename(newName: String): PsiElement {
doRename(element.referenceNameElement, newName)
return element
}
override fun equals(other: Any?): Boolean = other is RsReferenceBase<*> && element === other.element
override fun hashCode(): Int = element.hashCode()
private object Resolver : ResolveCache.AbstractResolver<RsReferenceBase<*>, List<BoundElement<RsCompositeElement>>> {
override fun resolve(ref: RsReferenceBase<*>, incompleteCode: Boolean): List<BoundElement<RsCompositeElement>> {
return ref.resolveInner()
}
}
companion object {
@JvmStatic protected fun doRename(identifier: PsiElement, newName: String) {
val factory = RsPsiFactory(identifier.project)
val newId = when (identifier.elementType) {
IDENTIFIER -> factory.createIdentifier(newName.replace(".rs", ""))
QUOTE_IDENTIFIER -> factory.createQuoteIdentifier(newName)
else -> error("Unsupported identifier type for `$newName` (${identifier.elementType})")
}
identifier.replace(newId)
}
}
}
|
mit
|
da7d1393dee81708355b91cdbe2158ae
| 40.512821 | 121 | 0.723904 | 5.147854 | false | false | false | false |
thatJavaNerd/JRAW
|
lib/src/test/kotlin/net/dean/jraw/test/unit/RedditModelAdapterFactoryTest.kt
|
1
|
15228
|
package net.dean.jraw.test.unit
import com.squareup.moshi.JsonDataException
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import com.winterbe.expekt.should
import net.dean.jraw.databind.*
import net.dean.jraw.models.KindConstants
import net.dean.jraw.models.Listing
import net.dean.jraw.models.Subreddit
import net.dean.jraw.models.internal.RedditModelEnvelope
import net.dean.jraw.test.expectException
import net.dean.jraw.test.models.Child
import net.dean.jraw.test.models.NonEnvelopedModel
import net.dean.jraw.test.models.OtherModel
import net.dean.jraw.test.models.Parent
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.xit
import kotlin.reflect.KClass
class RedditModelAdapterFactoryTest : Spek({
/**
* Create a Map<String, Class<Any>> where the keys are the lowercase simple names of each class and the values are
* the Java classes.
*
* ```kt
* registry(Subreddit::class) == mapOf("subreddit" to Subreddit::class.java)
* ```
*/
fun registry(vararg classes: KClass<*>) = classes
.map { it.simpleName!!.toLowerCase() }
.zip(classes.map { it.java })
.toMap()
fun factory(registry: Map<String, Class<*>> = mapOf()) = RedditModelAdapterFactory(registry)
fun moshi(registry: Map<String, Class<*>> = mapOf()) = Moshi.Builder()
.add(ModelAdapterFactory.create())
.add(UnixDateAdapterFactory())
.add(factory(registry))
.build()
fun childJson(kindValue: String = "child") = """
|{
| "kind": "$kindValue",
| "data": { "a": "some value" }
|}
""".trimMargin("|")
/**
* Parses the given JSON into a Map<String, Any> and invokes the provided `check` function on it. Returns the Map.
*/
fun checkJsonValue(json: String, check: (value: Map<String, Any>) -> Unit): Map<String, Any> {
val adapter = moshi().adapter<Map<String, Any>>(
Types.newParameterizedType(Map::class.java, String::class.java, Any::class.java))
val jsonValue = adapter.fromJson(json)!!
check(jsonValue)
return jsonValue
}
it("should return null when not given @Enveloped") {
val factory = factory(registry = mapOf())
factory.create(Subreddit::class.java, annotations = setOf(), moshi = moshi())
.should.be.`null`
}
it("should return a ListingAdapter when given a Listing type") {
val moshi = moshi(registry = registry(Child::class))
val adapter = moshi.adapter<Listing<Any>>(Types.newParameterizedType(Listing::class.java, Child::class.java), Enveloped::class.java)
adapter.should.not.be.`null`
adapter.should.be.an.instanceof(RedditModelAdapterFactory.ListingAdapter::class.java)
}
it("should return a StaticAdapter when the given type is marked with @RedditModel") {
val moshi = moshi(registry = registry(Child::class))
val adapter = moshi.adapter<Any>(Child::class.java, Enveloped::class.java)
// Sanity check
Child::class.java.isAnnotationPresent(RedditModel::class.java).should.be.`true`
adapter.should.be.an.instanceof(RedditModelAdapterFactory.StaticAdapter::class.java)
(adapter as RedditModelAdapterFactory.StaticAdapter).expectedKind.should.be.`null`
}
it("should return a StaticAdapter with a non-null expectedKind when the type is Subreddit") {
val adapter = moshi(registry = registry(Subreddit::class))
.adapter<Any>(Subreddit::class.java, Enveloped::class.java)
adapter.should.be.an.instanceof(RedditModelAdapterFactory.StaticAdapter::class.java)
(adapter as RedditModelAdapterFactory.StaticAdapter).expectedKind.should.equal(KindConstants.SUBREDDIT)
}
it("should return a DynamicAdapter when the given type is not marked with @RedditModel") {
// Sanity check
Parent::class.java.isAnnotationPresent(RedditModel::class.java).should.be.`false`
val adapter = moshi(registry = registry(Parent::class))
.adapter<Any>(Parent::class.java, Enveloped::class.java)
adapter.should.be.an.instanceof(RedditModelAdapterFactory.DynamicAdapter::class.java)
(adapter as RedditModelAdapterFactory.DynamicAdapter).upperBound.should.equal(Parent::class.java)
}
it("should return a different adapter when the class is marked with @RedditModel(enveloped = false)") {
// Sanity check
NonEnvelopedModel::class.java.getAnnotation(RedditModel::class.java).enveloped.should.be.`false`;
val adapter = moshi(registry = registry(NonEnvelopedModel::class))
.adapter<Any>(NonEnvelopedModel::class.java, Enveloped::class.java)
// Should eventually delegate to ClassJsonAdapter. The "$2" refers to JsonAdapter.nonNull()
adapter.javaClass.name.should.equal("com.squareup.moshi.JsonAdapter$2")
}
describe("StaticAdapter") {
describe("toJson") {
it("should throw an IllegalArgumentException if there is no JsonAdapter registered for the provided kind") {
// Nothing in the registry for Child
val moshi = moshi(registry = mapOf())
val adapter = moshi.adapter<Any>(Child::class.java, Enveloped::class.java)
as RedditModelAdapterFactory.StaticAdapter
expectException(IllegalArgumentException::class) {
adapter.toJson(Child("some value"))
}
}
it("should serialize to a RedditModelEnvelope") {
// Child is included in the registry, everything should be fine
val moshi = moshi(registry = registry(Child::class))
val original = Child("some value")
val adapter = moshi.adapter<Any>(Child::class.java, Enveloped::class.java)
as RedditModelAdapterFactory.StaticAdapter
val json = adapter.toJson(original)
checkJsonValue(json) {
it.keys.should.equal(setOf("kind", "data"))
it["kind"].should.equal("child")
it["data"].should.equal(mapOf("a" to original.a))
}
}
}
describe("fromJson") {
it("should not care about the value of 'kind' when expectedKind is null") {
val json = """
|{
| "kind": "value should not matter",
| "data": { "a": "some value" }
|}
""".trimMargin("|")
val adapter = moshi(registry(Child::class)).adapter<Child>(Child::class.java, Enveloped::class.java)
as RedditModelAdapterFactory.StaticAdapter
// Sanity check
adapter.expectedKind.should.be.`null`
adapter.fromJson(json).should.equal(Child("some value"))
}
it("should assert the value of 'kind' matches expectedKind when expectedKind is non-null") {
val registry = registry(Child::class)
// Create an adapter for RedditModelEnvelope<Child>
val envelopeAdapter = moshi(registry).adapter<RedditModelEnvelope<*>>(
Types.newParameterizedType(RedditModelEnvelope::class.java, Child::class.java))
val adapter = RedditModelAdapterFactory.StaticAdapter(
registry = registry(Child::class),
delegate = envelopeAdapter,
expectedKind = "child"
)
// This should be fine since the value of 'kind' matches expectedKind
adapter.fromJson(childJson(kindValue = "child")).should.equal(Child("some value"))
// This should cause a problem because 'kind' doesn't match expectedKind
expectException(JsonDataException::class) {
adapter.fromJson(childJson(kindValue = "some other value"))
}
}
}
it("should be able to deserialize JSON created by toJson() without loss of meaning") {
val original = Child("foo")
val adapter = moshi(registry = registry(Child::class))
.adapter<Any>(Child::class.java, Enveloped::class.java) as RedditModelAdapterFactory.StaticAdapter
adapter.fromJson(adapter.toJson(original)).should.equal(original)
}
}
describe("DynamicAdapter") {
describe("toJson") {
// TODO(mattbdean): https://github.com/mattbdean/JRAW/issues/237
xit("should be able to dynamically serialize JSON")
}
describe("fromJson") {
it("should throw an IllegalArgumentException if there is no JsonAdapter registered for the given kind") {
val adapter = moshi(registry = mapOf())
.adapter<Parent>(Parent::class.java, Enveloped::class.java) as RedditModelAdapterFactory.DynamicAdapter
val ex = expectException(IllegalArgumentException::class) {
adapter.fromJson(childJson())
}
ex.message.should.equal("No registered class for kind 'child'")
}
it("should throw a JsonDataException if 'kind' is missing, or an IllegalArgumentException if its value is not registered") {
val adapter = moshi(registry = registry(Child::class))
.adapter<Parent>(Parent::class.java, Enveloped::class.java) as RedditModelAdapterFactory.DynamicAdapter
val missingKindEx = expectException(JsonDataException::class) {
adapter.fromJson("""{ "data": { "a": "foo" } }""")
}
missingKindEx.message.should.equal("Expected value at '$.kind' to be non-null")
val notRegisteredEx = expectException(IllegalArgumentException::class) {
adapter.fromJson("""{ "kind": "some value", "data": { "a": "foo" } }""")
}
notRegisteredEx.message.should.equal("No registered class for kind 'some value'")
}
it("should dynamically find a JsonAdapter based on the value of 'kind' and deserialize that value") {
val adapter = moshi(registry = registry(Child::class))
.adapter<Parent>(Parent::class.java, Enveloped::class.java) as RedditModelAdapterFactory.DynamicAdapter
adapter.fromJson("""{ "kind": "child", "data": { "a": "some value" } }""").should.equal(Child("some value"))
}
it("should ensure the deserialized type is the same as or is a subclass of the upper bound") {
// OtherModel's superclass is Object, so trying to deserialize these guys as Parent objects
// should cause a problem
val adapter = moshi(registry = registry(OtherModel::class))
.adapter<Parent>(Parent::class.java, Enveloped::class.java) as RedditModelAdapterFactory.DynamicAdapter
val ex = expectException(IllegalArgumentException::class) {
adapter.fromJson("""{ "kind": "othermodel", "data": { "a": "some value" } }""")
}
ex.message.should.equal("Expected ${Parent::class.java.name} to be assignable from ${OtherModel("some value")}")
}
}
// TODO(mattbdean): https://github.com/mattbdean/JRAW/issues/237
xit("should be able to deserialize JSON created by toJson() without loss of meaning") {
val original = Child("foo")
val adapter = moshi(registry = registry(Child::class))
.adapter<Any>(Parent::class.java, Enveloped::class.java) as RedditModelAdapterFactory.DynamicAdapter
adapter.fromJson(adapter.toJson(original)).should.equal(original)
}
}
describe("ListingAdapter") {
fun <T : Any> listingType(dataType: KClass<T>) = Types.newParameterizedType(Listing::class.java, dataType.java)
describe("toJson") {
it("should produce a JSON object with 'kind' and 'data' properties") {
val original: Listing<Any> = Listing.create("next name", listOf(Child("some value")))
val adapter = moshi(registry = registry(Child::class))
.adapter<Listing<Child>>(listingType(Child::class), Enveloped::class.java) as RedditModelAdapterFactory.ListingAdapter
checkJsonValue(adapter.toJson(original)) {
it.keys.should.equal(setOf("kind", "data"))
it["kind"].should.equal(KindConstants.LISTING)
it["data"].should.be.instanceof(Map::class.java)
val data = it["data"] as Map<*, *>
data["after"].should.equal("next name")
val children = data["children"] as List<*>
children.should.have.size(1)
// The contents of 'children' is handled by the delegate adapter, no need to verify any more
}
}
}
describe("fromJson") {
val adapter = moshi(registry = registry(Child::class))
.adapter<Listing<Child>>(listingType(Child::class), Enveloped::class.java) as RedditModelAdapterFactory.ListingAdapter
it("should throw an IllegalArgumentException if 'kind' is not 'Listing'") {
val ex = expectException(IllegalArgumentException::class) {
adapter.fromJson("""{ "kind": "something", "data": {} }""")
}
ex.message.should.equal("Expected '${KindConstants.LISTING}' at $.kind, got 'something'")
}
it("should throw a JsonDataException if 'data' doesn't exist or its non-null") {
val nullDataEx = expectException(JsonDataException::class) {
adapter.fromJson("""{ "kind": "Listing", "data": null }""")
}
nullDataEx.message.should.equal("Expected a non-null value at $.data")
val noDataEx = expectException(JsonDataException::class) {
adapter.fromJson("""{ "kind": "Listing" }""")
}
noDataEx.message.should.equal("Expected a value at $.data")
}
it("should be able to deserialize Listings given valid JSON") {
adapter.fromJson("""{ "kind": "Listing", "data": { "next": null, "children": [] } }""")
.should.equal(Listing.create(null, listOf()))
}
}
it("should be able to deserialize JSON created by toJson() without loss of meaning") {
val original: Listing<Any> = Listing.create("next name", listOf(Child("some value"), Child("another value")))
val adapter = moshi(registry = registry(Child::class))
.adapter<Listing<Child>>(listingType(Child::class), Enveloped::class.java) as RedditModelAdapterFactory.ListingAdapter
adapter.fromJson(adapter.toJson(original)).should.equal(original)
}
}
})
|
mit
|
aafb230ecd47e856edefeb95f042d07b
| 45.426829 | 140 | 0.610651 | 4.808336 | false | false | false | false |
soywiz/korge
|
korge/src/commonMain/kotlin/com/soywiz/korge/service/storage/StorageItem.kt
|
1
|
1628
|
package com.soywiz.korge.service.storage
import com.soywiz.korio.dynamic.mapper.*
import com.soywiz.korio.dynamic.serialization.*
import com.soywiz.korio.serialization.json.*
import kotlin.reflect.*
class StorageItem<T : Any>(val storage: IStorage, val clazz: KClass<T>, val key: String, val mapper: ObjectMapper, val gen: (() -> T)?) {
val isDefined: Boolean get() = key in storage
@Suppress("UNCHECKED_CAST")
val realGen: (() -> T)? = when {
gen != null -> gen
else -> when (clazz) {
Boolean::class -> ({ false } as (() -> T))
Int::class -> ({ 0 } as (() -> T))
Long::class -> ({ 0L } as (() -> T))
Float::class -> ({ 0f } as (() -> T))
Double::class -> ({ 0.0 } as (() -> T))
String::class -> ({ "" } as (() -> T))
else -> null
}
}
var value: T
set(value) { storage[key] = Json.stringify(mapper.toUntyped(clazz, value)) }
get () {
if (!isDefined) storage[key] = Json.stringify(mapper.toUntyped(clazz,
realGen?.invoke()
?: error("Can't find '$key' and no default generator was defined")
))
return Json.parseTyped(clazz, storage[key], mapper)
}
fun remove() = storage.remove(key)
inline operator fun getValue(thisRef: Any, property: KProperty<*>): T = value
inline operator fun setValue(thisRef: Any, property: KProperty<*>, value: T): Unit { this.value = value }
}
inline fun <reified T : Any> IStorage.item(key: String, mapper: ObjectMapper = Mapper, noinline gen: (() -> T)? = null) = StorageItem(this, T::class, key, mapper, gen)
|
apache-2.0
|
6b76a38f1ddf6e7161a372086d7e5e6b
| 40.74359 | 167 | 0.580467 | 3.69161 | false | false | false | false |
cashapp/sqldelight
|
sqldelight-compiler/src/main/kotlin/app/cash/sqldelight/core/lang/SqlDelightQueriesFile.kt
|
1
|
6619
|
/*
* Copyright (C) 2016 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.cash.sqldelight.core.lang
import app.cash.sqldelight.core.SqlDelightFileIndex
import app.cash.sqldelight.core.compiler.integration.adapterProperty
import app.cash.sqldelight.core.compiler.integration.needsAdapters
import app.cash.sqldelight.core.compiler.model.BindableQuery
import app.cash.sqldelight.core.compiler.model.NamedExecute
import app.cash.sqldelight.core.compiler.model.NamedMutator.Delete
import app.cash.sqldelight.core.compiler.model.NamedMutator.Insert
import app.cash.sqldelight.core.compiler.model.NamedMutator.Update
import app.cash.sqldelight.core.compiler.model.NamedQuery
import app.cash.sqldelight.core.lang.psi.StmtIdentifierMixin
import app.cash.sqldelight.core.lang.util.argumentType
import app.cash.sqldelight.core.lang.util.parentOfTypeOrNull
import app.cash.sqldelight.core.lang.util.table
import app.cash.sqldelight.core.psi.SqlDelightStmtList
import com.alecstrong.sql.psi.core.SqlAnnotationHolder
import com.alecstrong.sql.psi.core.psi.SqlAnnotatedElement
import com.alecstrong.sql.psi.core.psi.SqlBindExpr
import com.alecstrong.sql.psi.core.psi.SqlInsertStmt
import com.alecstrong.sql.psi.core.psi.SqlStmt
import com.intellij.psi.FileViewProvider
import com.intellij.psi.PsiDirectory
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.PsiTreeUtil
class SqlDelightQueriesFile(
viewProvider: FileViewProvider,
) : SqlDelightFile(viewProvider, SqlDelightLanguage),
SqlAnnotatedElement {
override val packageName by lazy {
module?.let { module ->
SqlDelightFileIndex.getInstance(module).packageName(this)
}
}
val namedQueries by lazy {
transactions().filterIsInstance<NamedQuery>() + sqlStatements()
.filter { typeResolver.queryWithResults(it.statement) != null && it.identifier.name != null }
.map {
NamedQuery(
name = it.identifier.name!!,
queryable = typeResolver.queryWithResults(it.statement)!!,
statementIdentifier = it.identifier,
)
}
}
internal val namedMutators by lazy {
sqlStatements().filter { it.identifier.name != null && typeResolver.queryWithResults(it.statement) == null }
.mapNotNull {
when {
it.statement.deleteStmtLimited != null -> Delete(it.statement.deleteStmtLimited!!, it.identifier)
it.statement.insertStmt != null -> Insert(it.statement.insertStmt!!, it.identifier)
it.statement.updateStmtLimited != null -> Update(it.statement.updateStmtLimited!!, it.identifier)
else -> null
}
}
}
fun transactions(): Collection<BindableQuery> {
val sqlStmtList = PsiTreeUtil.getChildOfType(this, SqlDelightStmtList::class.java)!!
return sqlStmtList.stmtClojureList.map {
val statements = it.stmtClojureStmtList!!.children.filterIsInstance<SqlStmt>()
val lastQuery = typeResolver.queryWithResults(statements.last())
if (lastQuery != null) {
lastQuery.statement = it.stmtClojureStmtList!!
return@map NamedQuery(
statementIdentifier = it.stmtIdentifierClojure as StmtIdentifierMixin,
queryable = lastQuery,
name = it.stmtIdentifierClojure.name!!,
)
} else {
return@map NamedExecute(
identifier = it.stmtIdentifierClojure as StmtIdentifierMixin,
statement = it.stmtClojureStmtList!!,
)
}
}
}
internal val namedExecutes by lazy {
val statements = sqlStatements()
.filter {
it.identifier.name != null &&
it.statement.deleteStmtLimited == null &&
it.statement.insertStmt == null &&
it.statement.updateStmtLimited == null &&
it.statement.compoundSelectStmt == null
}
.map { NamedExecute(it.identifier, it.statement) }
return@lazy transactions().filterIsInstance<NamedExecute>() + statements
}
/**
* A collection of all the adapters needed for arguments or result columns in this query.
*/
internal val requiredAdapters by lazy {
val binders = PsiTreeUtil.findChildrenOfType(this, SqlBindExpr::class.java)
val argumentAdapters = binders.mapNotNull {
it.parentOfTypeOrNull<SqlInsertStmt>()?.let {
if (it.acceptsTableInterface() && it.table.needsAdapters()) return@mapNotNull it.table.adapterProperty()
}
typeResolver.argumentType(it).parentAdapter()
}
val resultColumnAdapters = namedQueries.flatMap {
it.resultColumnRequiredAdapters
}
return@lazy (argumentAdapters + resultColumnAdapters).distinct()
}
internal val triggers by lazy { triggers(this) }
override val order = null
override fun getFileType() = SqlDelightFileType
internal fun sqlStatements(): Collection<LabeledStatement> {
val sqlStmtList = PsiTreeUtil.getChildOfType(this, SqlDelightStmtList::class.java)!!
return sqlStmtList.stmtIdentifierList.zip(sqlStmtList.stmtList) { id, stmt ->
return@zip LabeledStatement(id as StmtIdentifierMixin, stmt)
}
}
fun iterateSqlFiles(block: (SqlDelightQueriesFile) -> Unit) {
val module = module ?: return
fun PsiDirectory.iterateSqlFiles() {
children.forEach {
if (it is PsiDirectory) it.iterateSqlFiles()
if (it is SqlDelightQueriesFile) block(it)
}
}
SqlDelightFileIndex.getInstance(module).sourceFolders(this).forEach { dir ->
dir.iterateSqlFiles()
}
}
override fun annotate(annotationHolder: SqlAnnotationHolder) {
if (packageName.isNullOrEmpty()) {
annotationHolder.createErrorAnnotation(this, "SqlDelight files must be placed in a package directory.")
}
}
override fun searchScope(): GlobalSearchScope {
val module = module
if (module != null && !SqlDelightFileIndex.getInstance(module).deriveSchemaFromMigrations) {
return GlobalSearchScope.getScopeRestrictedByFileTypes(super.searchScope(), SqlDelightFileType)
}
return super.searchScope()
}
data class LabeledStatement(val identifier: StmtIdentifierMixin, val statement: SqlStmt)
}
|
apache-2.0
|
f14823ef82aa5e02df455de146f83256
| 37.260116 | 112 | 0.727753 | 4.533562 | false | false | false | false |
edvin/tornadofx
|
src/main/java/tornadofx/Controls.kt
|
1
|
17225
|
@file:Suppress("UNCHECKED_CAST")
package tornadofx
import javafx.beans.property.ObjectProperty
import javafx.beans.property.Property
import javafx.beans.property.SimpleObjectProperty
import javafx.beans.value.ObservableValue
import javafx.collections.ObservableMap
import javafx.event.EventTarget
import javafx.geometry.Orientation
import javafx.scene.Node
import javafx.scene.control.*
import javafx.scene.image.Image
import javafx.scene.image.ImageView
import javafx.scene.layout.Pane
import javafx.scene.paint.Color
import javafx.scene.text.Text
import javafx.scene.text.TextFlow
import javafx.scene.web.HTMLEditor
import javafx.scene.web.WebView
import javafx.util.StringConverter
import java.time.LocalDate
fun EventTarget.webview(op: WebView.() -> Unit = {}) = WebView().attachTo(this, op)
enum class ColorPickerMode { Button, MenuButton, SplitMenuButton }
fun EventTarget.colorpicker(
color: Color? = null,
mode: ColorPickerMode = ColorPickerMode.Button,
op: ColorPicker.() -> Unit = {}
) = ColorPicker().attachTo(this, op) {
if (mode == ColorPickerMode.MenuButton) it.addClass(ColorPicker.STYLE_CLASS_BUTTON)
else if (mode == ColorPickerMode.SplitMenuButton) it.addClass(ColorPicker.STYLE_CLASS_SPLIT_BUTTON)
if (color != null) it.value = color
}
fun EventTarget.colorpicker(
colorProperty: ObjectProperty<Color>,
mode: ColorPickerMode = ColorPickerMode.Button,
op: ColorPicker.() -> Unit = {}
) = ColorPicker().apply { bind(colorProperty) }.attachTo(this, op) {
if (mode == ColorPickerMode.MenuButton) it.addClass(ColorPicker.STYLE_CLASS_BUTTON)
else if (mode == ColorPickerMode.SplitMenuButton) it.addClass(ColorPicker.STYLE_CLASS_SPLIT_BUTTON)
}
fun EventTarget.textflow(op: TextFlow.() -> Unit = {}) = TextFlow().attachTo(this, op)
fun EventTarget.text(op: Text.() -> Unit = {}) = Text().attachTo(this, op)
internal val EventTarget.properties: ObservableMap<Any, Any>
get() = when (this) {
is Node -> properties
is Tab -> properties
is MenuItem -> properties
else -> throw IllegalArgumentException("Don't know how to extract properties object from $this")
}
var EventTarget.tagProperty: Property<Any?>
get() = properties.getOrPut("tornadofx.value") {
SimpleObjectProperty<Any?>()
} as SimpleObjectProperty<Any?>
set(value) {
properties["tornadofx.value"] = value
}
var EventTarget.tag: Any?
get() = tagProperty.value
set(value) {
tagProperty.value = value
}
@Deprecated("Properties set on the fake node would be lost. Do not use this function.", ReplaceWith("Manually adding children"))
fun children(addTo: MutableList<Node>, op: Pane.() -> Unit) {
val fake = Pane().also(op)
addTo.addAll(fake.children)
}
fun EventTarget.text(initialValue: String? = null, op: Text.() -> Unit = {}) = Text().attachTo(this, op) {
if (initialValue != null) it.text = initialValue
}
fun EventTarget.text(property: Property<String>, op: Text.() -> Unit = {}) = text().apply {
bind(property)
op(this)
}
fun EventTarget.text(observable: ObservableValue<String>, op: Text.() -> Unit = {}) = text().apply {
bind(observable)
op(this)
}
fun EventTarget.textfield(value: String? = null, op: TextField.() -> Unit = {}) = TextField().attachTo(this, op) {
if (value != null) it.text = value
}
fun EventTarget.textfield(property: ObservableValue<String>, op: TextField.() -> Unit = {}) = textfield().apply {
bind(property)
op(this)
}
@JvmName("textfieldNumber")
fun EventTarget.textfield(property: ObservableValue<Number>, op: TextField.() -> Unit = {}) = textfield().apply {
bind(property)
op(this)
}
@JvmName("textfieldInt")
fun EventTarget.textfield(property: ObservableValue<Int>, op: TextField.() -> Unit = {}) = textfield().apply {
bind(property)
op(this)
}
fun EventTarget.passwordfield(value: String? = null, op: PasswordField.() -> Unit = {}) = PasswordField().attachTo(this, op) {
if (value != null) it.text = value
}
fun EventTarget.passwordfield(property: ObservableValue<String>, op: PasswordField.() -> Unit = {}) = passwordfield().apply {
bind(property)
op(this)
}
fun <T> EventTarget.textfield(property: Property<T>, converter: StringConverter<T>, op: TextField.() -> Unit = {}) = textfield().apply {
textProperty().bindBidirectional(property, converter)
ViewModel.register(textProperty(), property)
op(this)
}
fun EventTarget.datepicker(op: DatePicker.() -> Unit = {}) = DatePicker().attachTo(this, op)
fun EventTarget.datepicker(property: Property<LocalDate>, op: DatePicker.() -> Unit = {}) = datepicker().apply {
bind(property)
op(this)
}
fun EventTarget.textarea(value: String? = null, op: TextArea.() -> Unit = {}) = TextArea().attachTo(this, op) {
if (value != null) it.text = value
}
fun EventTarget.textarea(property: ObservableValue<String>, op: TextArea.() -> Unit = {}) = textarea().apply {
bind(property)
op(this)
}
fun <T> EventTarget.textarea(property: Property<T>, converter: StringConverter<T>, op: TextArea.() -> Unit = {}) = textarea().apply {
textProperty().bindBidirectional(property, converter)
ViewModel.register(textProperty(), property)
op(this)
}
fun EventTarget.buttonbar(buttonOrder: String? = null, op: (ButtonBar.() -> Unit)) = ButtonBar().attachTo(this, op) {
if (buttonOrder != null) it.buttonOrder = buttonOrder
}
fun EventTarget.htmleditor(html: String? = null, op: HTMLEditor.() -> Unit = {}) = HTMLEditor().attachTo(this, op) {
if (html != null) it.htmlText = html
}
fun EventTarget.checkbox(text: String? = null, property: Property<Boolean>? = null, op: CheckBox.() -> Unit = {}) = CheckBox(text).attachTo(this, op) {
if (property != null) it.bind(property)
}
fun EventTarget.progressindicator(op: ProgressIndicator.() -> Unit = {}) = ProgressIndicator().attachTo(this, op)
fun EventTarget.progressindicator(property: Property<Number>, op: ProgressIndicator.() -> Unit = {}) = progressindicator().apply {
bind(property)
op(this)
}
fun EventTarget.progressbar(initialValue: Double? = null, op: ProgressBar.() -> Unit = {}) = ProgressBar().attachTo(this, op) {
if (initialValue != null) it.progress = initialValue
}
fun EventTarget.progressbar(property: ObservableValue<Number>, op: ProgressBar.() -> Unit = {}) = progressbar().apply {
bind(property)
op(this)
}
fun EventTarget.slider(
min: Number? = null,
max: Number? = null,
value: Number? = null,
orientation: Orientation? = null,
op: Slider.() -> Unit = {}
) = Slider().attachTo(this, op) {
if (min != null) it.min = min.toDouble()
if (max != null) it.max = max.toDouble()
if (value != null) it.value = value.toDouble()
if (orientation != null) it.orientation = orientation
}
fun <T> EventTarget.slider(
range: ClosedRange<T>,
value: Number? = null,
orientation: Orientation? = null,
op: Slider.() -> Unit = {}
): Slider
where T : Comparable<T>,
T : Number {
return slider(range.start, range.endInclusive, value, orientation, op)
}
// Buttons
fun EventTarget.button(text: String = "", graphic: Node? = null, op: Button.() -> Unit = {}) = Button(text).attachTo(this, op) {
if (graphic != null) it.graphic = graphic
}
fun EventTarget.menubutton(text: String = "", graphic: Node? = null, op: MenuButton.() -> Unit = {}) = MenuButton(text).attachTo(this, op) {
if (graphic != null) it.graphic = graphic
}
fun EventTarget.splitmenubutton(text: String? = null, graphic: Node? = null, op: SplitMenuButton.() -> Unit = {}) = SplitMenuButton().attachTo(this, op) {
if (text != null) it.text = text
if (graphic != null) it.graphic = graphic
}
fun EventTarget.button(text: ObservableValue<String>, graphic: Node? = null, op: Button.() -> Unit = {}) = Button().attachTo(this, op) {
it.textProperty().bind(text)
if (graphic != null) it.graphic = graphic
}
fun ToolBar.button(text: String = "", graphic: Node? = null, op: Button.() -> Unit = {}) = Button(text).also {
if (graphic != null) it.graphic = graphic
items += it
op(it)
}
fun ToolBar.button(text: ObservableValue<String>, graphic: Node? = null, op: Button.() -> Unit = {}) = Button().also {
it.textProperty().bind(text)
if (graphic != null) it.graphic = graphic
items += it
op(it)
}
fun ButtonBar.button(text: String = "", type: ButtonBar.ButtonData? = null, graphic: Node? = null, op: Button.() -> Unit = {}) = Button(text).also {
if (type != null) ButtonBar.setButtonData(it, type)
if (graphic != null) it.graphic = graphic
buttons += it
op(it)
}
fun ButtonBar.button(text: ObservableValue<String>, type: ButtonBar.ButtonData? = null, graphic: Node? = null, op: Button.() -> Unit = {}) = Button().also {
it.textProperty().bind(text)
if (type != null) ButtonBar.setButtonData(it, type)
if (graphic != null) it.graphic = graphic
buttons += it
op(it)
}
fun Node.togglegroup(property: ObservableValue<Any>? = null, op: ToggleGroup.() -> Unit = {}) = ToggleGroup().also {tg ->
properties["tornadofx.togglegroup"] = tg
property?.let { tg.bind(it) }
op(tg)
}
/**
* Bind the selectedValueProperty of this toggle group to the given property. Passing in a writeable value
* will result in a bidirectional binding, while passing in a read only value will result in a unidirectional binding.
*
* If the toggles are configured with the value parameter (@see #togglebutton and #radiogroup), the corresponding
* button will be selected when the value is changed. Likewise, if the selected toggle is changed,
* the property value will be updated if it is writeable.
*/
fun <T> ToggleGroup.bind(property: ObservableValue<T>) = selectedValueProperty<T>().apply {
(property as? Property<T>)?.also { bindBidirectional(it) }
?: bind(property)
}
/**
* Generates a writable property that represents the selected value for this toggele group.
* If the toggles are configured with a value (@see #togglebutton and #radiogroup) the corresponding
* toggle will be selected when this value is changed. Likewise, if the toggle is changed by clicking
* it, the value for the toggle will be written to this property.
*
* To bind to this property, use the #ToggleGroup.bind() function.
*/
fun <T> ToggleGroup.selectedValueProperty(): ObjectProperty<T> = properties.getOrPut("tornadofx.selectedValueProperty") {
SimpleObjectProperty<T>().apply {
selectedToggleProperty().onChange {
value = it?.properties?.get("tornadofx.toggleGroupValue") as T?
}
onChange { selectedValue ->
selectToggle(toggles.find { it.properties["tornadofx.toggleGroupValue"] == selectedValue })
}
}
} as ObjectProperty<T>
/**
* Create a togglebutton inside the current or given toggle group. The optional value parameter will be matched against
* the extension property `selectedValueProperty()` on Toggle Group. If the #ToggleGroup.selectedValueProperty is used,
* it's value will be updated to reflect the value for this radio button when it's selected.
*
* Likewise, if the `selectedValueProperty` of the ToggleGroup is updated to a value that matches the value for this
* togglebutton, it will be automatically selected.
*/
fun EventTarget.togglebutton(
text: String? = null,
group: ToggleGroup? = getToggleGroup(),
selectFirst: Boolean = true,
value: Any? = null,
op: ToggleButton.() -> Unit = {}
) = ToggleButton().attachTo(this, op) {
it.text = if (value != null && text == null) value.toString() else text ?: ""
it.properties["tornadofx.toggleGroupValue"] = value ?: text
if (group != null) it.toggleGroup = group
if (it.toggleGroup?.selectedToggle == null && selectFirst) it.isSelected = true
}
fun EventTarget.togglebutton(
text: ObservableValue<String>? = null,
group: ToggleGroup? = getToggleGroup(),
selectFirst: Boolean = true,
value: Any? = null,
op: ToggleButton.() -> Unit = {}
) = ToggleButton().attachTo(this, op) {
it.textProperty().bind(text)
it.properties["tornadofx.toggleGroupValue"] = value ?: text
if (group != null) it.toggleGroup = group
if (it.toggleGroup?.selectedToggle == null && selectFirst) it.isSelected = true
}
fun EventTarget.togglebutton(
group: ToggleGroup? = getToggleGroup(),
selectFirst: Boolean = true,
value: Any? = null,
op: ToggleButton.() -> Unit = {}
) = ToggleButton().attachTo(this, op) {
it.properties["tornadofx.toggleGroupValue"] = value
if (group != null) it.toggleGroup = group
if (it.toggleGroup?.selectedToggle == null && selectFirst) it.isSelected = true
}
fun ToggleButton.whenSelected(op: () -> Unit) {
selectedProperty().onChange { if (it) op() }
}
/**
* Create a radiobutton inside the current or given toggle group. The optional value parameter will be matched against
* the extension property `selectedValueProperty()` on Toggle Group. If the #ToggleGroup.selectedValueProperty is used,
* it's value will be updated to reflect the value for this radio button when it's selected.
*
* Likewise, if the `selectedValueProperty` of the ToggleGroup is updated to a value that matches the value for this
* radiobutton, it will be automatically selected.
*/
fun EventTarget.radiobutton(
text: String? = null,
group: ToggleGroup? = getToggleGroup(),
value: Any? = null,
op: RadioButton.() -> Unit = {}
) = RadioButton().attachTo(this, op) {
it.text = if (value != null && text == null) value.toString() else text ?: ""
it.properties["tornadofx.toggleGroupValue"] = value ?: text
if (group != null) it.toggleGroup = group
}
fun EventTarget.label(text: String = "", graphic: Node? = null, op: Label.() -> Unit = {}) = Label(text).attachTo(this, op) {
if (graphic != null) it.graphic = graphic
}
inline fun <reified T> EventTarget.label(
observable: ObservableValue<T>,
graphicProperty: ObservableValue<Node>? = null,
converter: StringConverter<in T>? = null,
noinline op: Label.() -> Unit = {}
) = label().apply {
if (converter == null) {
if (T::class == String::class) {
@Suppress("UNCHECKED_CAST")
textProperty().bind(observable as ObservableValue<String>)
} else {
textProperty().bind(observable.stringBinding { it?.toString() })
}
} else {
textProperty().bind(observable.stringBinding { converter.toString(it) })
}
if (graphic != null) graphicProperty().bind(graphicProperty)
op(this)
}
fun EventTarget.hyperlink(text: String = "", graphic: Node? = null, op: Hyperlink.() -> Unit = {}) = Hyperlink(text, graphic).attachTo(this, op)
fun EventTarget.hyperlink(observable: ObservableValue<String>, graphic: Node? = null, op: Hyperlink.() -> Unit = {}) = hyperlink(graphic = graphic).apply {
bind(observable)
op(this)
}
fun EventTarget.menubar(op: MenuBar.() -> Unit = {}) = MenuBar().attachTo(this, op)
fun EventTarget.imageview(url: String? = null, lazyload: Boolean = true, op: ImageView.() -> Unit = {}) =
opcr(this, if (url == null) ImageView() else ImageView(Image(url, lazyload)), op)
fun EventTarget.imageview(
url: ObservableValue<String>,
lazyload: Boolean = true,
op: ImageView.() -> Unit = {}
) = ImageView().attachTo(this, op) { imageView ->
imageView.imageProperty().bind(objectBinding(url) { value?.let { Image(it, lazyload) } })
}
fun EventTarget.imageview(image: ObservableValue<Image?>, op: ImageView.() -> Unit = {}) = ImageView().attachTo(this, op) {
it.imageProperty().bind(image)
}
fun EventTarget.imageview(image: Image, op: ImageView.() -> Unit = {}) = ImageView(image).attachTo(this, op)
/**
* Listen to changes and update the value of the property if the given mutator results in a different value
*/
fun <T : Any?> Property<T>.mutateOnChange(mutator: (T?) -> T?) = onChange {
val changed = mutator(value)
if (changed != value) value = changed
}
/**
* Remove leading or trailing whitespace from a Text Input Control.
*/
fun TextInputControl.trimWhitespace() = focusedProperty().onChange { focused ->
if (!focused && text != null) text = text.trim()
}
/**
* Remove any whitespace from a Text Input Control.
*/
fun TextInputControl.stripWhitespace() = textProperty().mutateOnChange { it?.replace(Regex("\\s*"), "") }
/**
* Remove any non integer values from a Text Input Control.
*/
fun TextInputControl.stripNonInteger() = textProperty().mutateOnChange { it?.replace(Regex("[^0-9-]"), "") }
/**
* Remove any non integer values from a Text Input Control.
*/
fun TextInputControl.stripNonNumeric(vararg allowedChars: String = arrayOf(".", ",", "-")) =
textProperty().mutateOnChange { it?.replace(Regex("[^0-9${allowedChars.joinToString("")}]"), "") }
fun ChoiceBox<*>.action(op: () -> Unit) = setOnAction { op() }
fun ButtonBase.action(op: () -> Unit) = setOnAction { op() }
fun TextField.action(op: () -> Unit) = setOnAction { op() }
fun MenuItem.action(op: () -> Unit) = setOnAction { op() }
|
apache-2.0
|
2ee1a306da2d72b82499dee7a4d98db6
| 38.236902 | 156 | 0.671524 | 3.979898 | false | false | false | false |
RocketChat/Rocket.Chat.Android.Lily
|
app/src/main/java/chat/rocket/android/server/domain/RefreshSettingsInteractor.kt
|
2
|
2747
|
package chat.rocket.android.server.domain
import chat.rocket.android.server.infrastructure.RocketChatClientFactory
import chat.rocket.android.util.retryIO
import chat.rocket.core.internal.rest.settings
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import timber.log.Timber
import javax.inject.Inject
/**
* This class reloads the current logged server settings whenever needed.
*/
class RefreshSettingsInteractor @Inject constructor(
private val factory: RocketChatClientFactory,
private val repository: SettingsRepository
) {
private var settingsFilter = arrayOf(
UNIQUE_IDENTIFIER,
LDAP_ENABLE,
CAS_ENABLE,
CAS_LOGIN_URL,
ACCOUNT_REGISTRATION,
ACCOUNT_LOGIN_FORM,
ACCOUNT_PASSWORD_RESET,
ACCOUNT_CUSTOM_FIELDS,
ACCOUNT_GOOGLE,
ACCOUNT_FACEBOOK,
ACCOUNT_GITHUB,
ACCOUNT_LINKEDIN,
ACCOUNT_METEOR,
ACCOUNT_TWITTER,
ACCOUNT_GITLAB,
ACCOUNT_GITLAB_URL,
ACCOUNT_WORDPRESS,
ACCOUNT_WORDPRESS_URL,
JITSI_ENABLED,
JISTI_ENABLE_CHANNELS,
JITSI_SSL,
JITSI_DOMAIN,
JITSI_URL_ROOM_PREFIX,
SITE_URL,
SITE_NAME,
FAVICON_512,
FAVICON_196,
USE_REALNAME,
ALLOW_ROOM_NAME_SPECIAL_CHARS,
FAVORITE_ROOMS,
UPLOAD_STORAGE_TYPE,
UPLOAD_MAX_FILE_SIZE,
UPLOAD_WHITELIST_MIMETYPES,
HIDE_USER_JOIN,
HIDE_USER_LEAVE,
HIDE_TYPE_AU,
HIDE_MUTE_UNMUTE,
HIDE_TYPE_RU,
ALLOW_MESSAGE_DELETING,
ALLOW_MESSAGE_EDITING,
ALLOW_MESSAGE_PINNING,
ALLOW_MESSAGE_STARRING,
SHOW_DELETED_STATUS,
SHOW_EDITED_STATUS,
WIDE_TILE_310,
STORE_LAST_MESSAGE,
MESSAGE_READ_RECEIPT_ENABLED,
MESSAGE_READ_RECEIPT_STORE_USERS
)
suspend fun refresh(server: String) {
withContext(Dispatchers.IO) {
factory.get(server).let { client ->
val settings = retryIO(
description = "settings",
times = 5,
maxDelay = 5000,
initialDelay = 300
) {
client.settings(*settingsFilter)
}
repository.save(server, settings)
}
}
}
fun refreshAsync(server: String) {
GlobalScope.launch(Dispatchers.IO) {
try {
refresh(server)
} catch (ex: Exception) {
Timber.e(ex, "Error refreshing settings for: $server")
}
}
}
}
|
mit
|
e172d3e91ef027704dc98610fe4ee249
| 26.48 | 73 | 0.592647 | 4.444984 | false | false | false | false |
lare96/luna
|
plugins/api/item/LootTable.kt
|
1
|
1337
|
package api.item
import api.predef.*
import io.luna.game.model.item.Item
/**
* A model representing a loot table. Loot tables are collections of items that can select items to be picked based
* on their rarity.
*
* @author lare96
*/
class LootTable(private val items: List<LootTableItem>) : Iterable<LootTableItem> {
override fun iterator(): Iterator<LootTableItem> = items.iterator()
/**
* Rolls on one item from this loot table.
*/
fun pick(): Item? {
val all = pickAll()
return when (all.isEmpty()) {
true -> null
false -> all.random()
}
}
/**
* Rolls on all items from this loot table.
*/
fun pickAll(): List<Item> {
val lootItems = ArrayList<Item>(items.size)
for (loot in items) {
if (roll(loot)) {
lootItems += loot.getItem()
}
}
return lootItems
}
/**
* Determines if [loot] will be picked based on its rarity.
*/
private fun roll(loot: LootTableItem): Boolean {
val chance = loot.chance
return when {
chance.numerator <= 0 -> false
chance.numerator >= chance.denominator -> true
rand(0, chance.denominator) <= chance.numerator -> true
else -> false
}
}
}
|
mit
|
4104b266ee8fbf3bf798a1c37a369e8c
| 24.711538 | 115 | 0.563201 | 4.312903 | false | false | false | false |
RocketChat/Rocket.Chat.Android.Lily
|
app/src/main/java/chat/rocket/android/members/ui/MembersFragment.kt
|
2
|
5219
|
package chat.rocket.android.members.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import chat.rocket.android.R
import chat.rocket.android.analytics.AnalyticsManager
import chat.rocket.android.analytics.event.ScreenViewEvent
import chat.rocket.android.chatroom.ui.ChatRoomActivity
import chat.rocket.android.helper.EndlessRecyclerViewScrollListener
import chat.rocket.android.members.adapter.MembersAdapter
import chat.rocket.android.members.presentation.MembersPresenter
import chat.rocket.android.members.presentation.MembersView
import chat.rocket.android.members.uimodel.MemberUiModel
import chat.rocket.android.util.extensions.clearLightStatusBar
import chat.rocket.android.util.extensions.inflate
import chat.rocket.android.util.extensions.showToast
import chat.rocket.android.util.extensions.ui
import dagger.android.support.AndroidSupportInjection
import kotlinx.android.synthetic.main.app_bar_chat_room.*
import kotlinx.android.synthetic.main.fragment_members.*
import javax.inject.Inject
fun newInstance(chatRoomId: String): Fragment = MembersFragment().apply {
arguments = Bundle(1).apply {
putString(BUNDLE_CHAT_ROOM_ID, chatRoomId)
}
}
internal const val TAG_MEMBERS_FRAGMENT = "MembersFragment"
private const val BUNDLE_CHAT_ROOM_ID = "chat_room_id"
class MembersFragment : Fragment(), MembersView {
@Inject lateinit var presenter: MembersPresenter
@Inject lateinit var analyticsManager: AnalyticsManager
private val adapter: MembersAdapter =
MembersAdapter { memberUiModel -> presenter.toMemberDetails(memberUiModel, chatRoomId) }
private lateinit var chatRoomId: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AndroidSupportInjection.inject(this)
arguments?.run {
chatRoomId = getString(BUNDLE_CHAT_ROOM_ID, "")
}
?: requireNotNull(arguments) { "no arguments supplied when the fragment was instantiated" }
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? = container?.inflate(R.layout.fragment_members)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupToolbar()
setupListeners()
analyticsManager.logScreenView(ScreenViewEvent.Members)
}
override fun onResume() {
super.onResume()
adapter.clearData()
with(presenter) {
offset = 0
loadChatRoomsMembers(chatRoomId)
checkInviteUserPermission(chatRoomId)
}
}
override fun showMembers(dataSet: List<MemberUiModel>, total: Long) {
ui {
if (recycler_view.adapter == null) {
recycler_view.adapter = adapter
val linearLayoutManager = LinearLayoutManager(context)
recycler_view.layoutManager = linearLayoutManager
recycler_view.itemAnimator = DefaultItemAnimator()
if (dataSet.size >= 30) {
recycler_view.addOnScrollListener(object :
EndlessRecyclerViewScrollListener(linearLayoutManager) {
override fun onLoadMore(
page: Int,
totalItemsCount: Int,
recyclerView: RecyclerView
) {
presenter.loadChatRoomsMembers(chatRoomId)
}
})
}
}
setupToolbar(total)
adapter.appendData(dataSet)
}
}
override fun showLoading() {
ui { view_loading.isVisible = true }
}
override fun hideLoading() {
ui { view_loading.isVisible = false }
}
override fun showMessage(resId: Int) {
ui { showToast(resId) }
}
override fun showMessage(message: String) {
ui { showToast(message) }
}
override fun showInviteUsersButton() {
ui { button_invite_user.isVisible = true }
}
override fun hideInviteUserButton() {
ui { button_invite_user.isVisible = false }
}
override fun showGenericErrorMessage() = showMessage(getString(R.string.msg_generic_error))
private fun setupToolbar(totalMembers: Long? = null) {
with((activity as ChatRoomActivity)) {
if (totalMembers != null) {
setupToolbarTitle((getString(R.string.title_counted_members, totalMembers)))
} else {
setupToolbarTitle((getString(R.string.title_members)))
}
this.clearLightStatusBar()
toolbar.isVisible = true
}
}
private fun setupListeners() {
button_invite_user.setOnClickListener { presenter.toInviteUsers(chatRoomId) }
}
}
|
mit
|
55ec8e504e0c3553fd6aaf5d004e9bdf
| 34.510204 | 103 | 0.671776 | 5.057171 | false | false | false | false |
ffc-nectec/FFC
|
ffc/src/main/kotlin/ffc/app/ConnectivityChangeReceiver.kt
|
1
|
1300
|
/*
* Copyright (c) 2018 NECTEC
* National Electronics and Computer Technology Center, Thailand
*
* 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 ffc.app
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import ffc.android.connectivityManager
class ConnectivityChangeReceiver(
val onConnectivityChange: ((isConnect: Boolean) -> Unit)? = null
) : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == ConnectivityManager.CONNECTIVITY_ACTION)
onConnectivityChange?.invoke(context.connectivityManager.isConnected)
}
}
val ConnectivityManager.isConnected
get() = activeNetworkInfo?.isConnected == true
|
apache-2.0
|
bd1f647ef16aeb4da7b15e4bdce32f78
| 34.135135 | 81 | 0.758462 | 4.577465 | false | false | false | false |
wikimedia/apps-android-wikipedia
|
app/src/main/java/org/wikipedia/search/PrefixSearchResponse.kt
|
1
|
761
|
package org.wikipedia.search
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import org.wikipedia.dataclient.mwapi.MwQueryResponse
@Serializable
class PrefixSearchResponse : MwQueryResponse() {
@SerialName("searchinfo")
private val searchInfo: SearchInfo? = null
private val search: Search? = null
fun suggestion(): String? {
return searchInfo?.suggestion
}
@Serializable
internal class SearchInfo {
@SerialName("suggestionsnippet")
private val snippet: String? = null
val suggestion: String? = null
}
@Serializable
internal class Search {
@SerialName("ns")
private val namespace = 0
private val title: String? = null
}
}
|
apache-2.0
|
67b5bed85e324e3cd4059e38dd448ae9
| 24.366667 | 53 | 0.688568 | 4.878205 | false | false | false | false |
AndroidX/androidx
|
compose/ui/ui-graphics/src/commonMain/kotlin/androidx/compose/ui/graphics/Shadow.kt
|
3
|
2422
|
/*
* Copyright 2019 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.graphics
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.lerp
import androidx.compose.ui.util.lerp
/**
* A single shadow.
*/
@Immutable
class Shadow(
@Stable
val color: Color = Color(0xFF000000),
@Stable
val offset: Offset = Offset.Zero,
@Stable
val blurRadius: Float = 0.0f
) {
companion object {
/**
* Constant for no shadow.
*/
@Stable
val None = Shadow()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Shadow) return false
if (color != other.color) return false
if (offset != other.offset) return false
if (blurRadius != other.blurRadius) return false
return true
}
override fun hashCode(): Int {
var result = color.hashCode()
result = 31 * result + offset.hashCode()
result = 31 * result + blurRadius.hashCode()
return result
}
override fun toString(): String {
return "Shadow(color=$color, offset=$offset, blurRadius=$blurRadius)"
}
fun copy(
color: Color = this.color,
offset: Offset = this.offset,
blurRadius: Float = this.blurRadius
): Shadow {
return Shadow(
color = color,
offset = offset,
blurRadius = blurRadius
)
}
}
/**
* Linearly interpolate two [Shadow]s.
*/
@Stable
fun lerp(start: Shadow, stop: Shadow, fraction: Float): Shadow {
return Shadow(
lerp(start.color, stop.color, fraction),
lerp(start.offset, stop.offset, fraction),
lerp(start.blurRadius, stop.blurRadius, fraction)
)
}
|
apache-2.0
|
593403b04c977d5c6965acc22a7b2b67
| 25.922222 | 77 | 0.642444 | 4.241681 | false | false | false | false |
hannesa2/owncloud-android
|
owncloudData/src/androidTest/java/com/owncloud/android/data/capabilities/db/OCCapabilityDaoTest.kt
|
2
|
5468
|
/**
* ownCloud Android client application
*
* @author David González Verdugo
* @author Abel García de Prada
* Copyright (C) 2020 ownCloud GmbH.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* 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.owncloud.android.data.capabilities.db
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.test.filters.SmallTest
import androidx.test.platform.app.InstrumentationRegistry
import com.owncloud.android.data.OwncloudDatabase
import com.owncloud.android.data.capabilities.datasources.implementation.OCLocalCapabilitiesDataSource.Companion.toEntity
import com.owncloud.android.domain.capabilities.model.CapabilityBooleanType
import com.owncloud.android.testutil.OC_CAPABILITY
import com.owncloud.android.testutil.livedata.getLastEmittedValue
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Rule
import org.junit.Test
@SmallTest
class OCCapabilityDaoTest {
private lateinit var ocCapabilityDao: OCCapabilityDao
private val user1 = "user1@server"
private val user2 = "user2@server"
@Rule
@JvmField
val instantExecutorRule = InstantTaskExecutorRule()
@Before
fun setUp() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
OwncloudDatabase.switchToInMemory(context)
val db: OwncloudDatabase = OwncloudDatabase.getDatabase(context)
ocCapabilityDao = db.capabilityDao()
}
@Test
fun insertCapabilitiesListAndRead() {
val entityList: List<OCCapabilityEntity> = listOf(
OC_CAPABILITY.copy(accountName = user1).toEntity(),
OC_CAPABILITY.copy(accountName = user2).toEntity()
)
ocCapabilityDao.insert(entityList)
val capability = ocCapabilityDao.getCapabilitiesForAccount(user2)
val capabilityAsLiveData = ocCapabilityDao.getCapabilitiesForAccountAsLiveData(user2).getLastEmittedValue()
assertNotNull(capability)
assertNotNull(capabilityAsLiveData)
assertEquals(entityList[1], capability)
assertEquals(entityList[1], capabilityAsLiveData)
}
@Test
fun insertCapabilitiesAndRead() {
val entity1 = OC_CAPABILITY.copy(accountName = user1).toEntity()
val entity2 = OC_CAPABILITY.copy(accountName = user2).toEntity()
ocCapabilityDao.insert(entity1)
ocCapabilityDao.insert(entity2)
val capability = ocCapabilityDao.getCapabilitiesForAccount(user2)
val capabilityAsLiveData = ocCapabilityDao.getCapabilitiesForAccountAsLiveData(user2).getLastEmittedValue()
assertNotNull(capability)
assertNotNull(capabilityAsLiveData)
assertEquals(entity2, capability)
assertEquals(entity2, capabilityAsLiveData)
}
@Test
fun getNonExistingCapabilities() {
ocCapabilityDao.insert(OC_CAPABILITY.copy(accountName = user1).toEntity())
val capability = ocCapabilityDao.getCapabilitiesForAccountAsLiveData(user2).getLastEmittedValue()
assertNull(capability)
}
@Test
fun replaceCapabilityIfAlreadyExists_exists() {
val entity1 = OC_CAPABILITY.copy(filesVersioning = CapabilityBooleanType.FALSE).toEntity()
val entity2 = OC_CAPABILITY.copy(filesVersioning = CapabilityBooleanType.TRUE).toEntity()
ocCapabilityDao.insert(entity1)
ocCapabilityDao.replace(listOf(entity2))
val capability = ocCapabilityDao.getCapabilitiesForAccountAsLiveData(OC_CAPABILITY.accountName!!).getLastEmittedValue()
assertNotNull(capability)
assertEquals(entity2, capability)
}
@Test
fun replaceCapabilityIfAlreadyExists_doesNotExist() {
val entity1 = OC_CAPABILITY.copy(accountName = user1).toEntity()
val entity2 = OC_CAPABILITY.copy(accountName = user2).toEntity()
ocCapabilityDao.insert(entity1)
ocCapabilityDao.replace(listOf(entity2))
val capability1 = ocCapabilityDao.getCapabilitiesForAccountAsLiveData(user1).getLastEmittedValue()
assertNotNull(capability1)
assertEquals(entity1, capability1)
// capability2 didn't exist before, it should not replace the old one but got created
val capability2 = ocCapabilityDao.getCapabilitiesForAccountAsLiveData(user2).getLastEmittedValue()
assertNotNull(capability2)
assertEquals(entity2, capability2)
}
@Test
fun deleteCapability() {
val entity = OC_CAPABILITY.copy(accountName = user1).toEntity()
ocCapabilityDao.insert(entity)
val capability1 = ocCapabilityDao.getCapabilitiesForAccountAsLiveData(user1).getLastEmittedValue()
assertNotNull(capability1)
ocCapabilityDao.delete(user1)
val capability2 = ocCapabilityDao.getCapabilitiesForAccountAsLiveData(user1).getLastEmittedValue()
assertNull(capability2)
}
}
|
gpl-2.0
|
c7279bc24606ec2104ccc702416aea09
| 35.198675 | 127 | 0.744969 | 5.137218 | false | true | false | false |
bsmr-java/lwjgl3
|
modules/templates/src/main/kotlin/org/lwjgl/opengles/templates/KHR_texture_compression_astc_hdr.kt
|
1
|
4534
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opengles.templates
import org.lwjgl.generator.*
import org.lwjgl.opengles.*
val KHR_texture_compression_astc_ldr = "KHRTextureCompressionASTCLDR".nativeClassGLES("KHR_texture_compression_astc_ldr", postfix = KHR) {
documentation =
"""
Native bindings to the ${registryLink("KHR", "texture_compression_astc_hdr")} extension.
Adaptive Scalable Texture Compression (ASTC) is a new texture compression technology that offers unprecendented flexibility, while producing better or
comparable results than existing texture compressions at all bit rates. It includes support for 2D and slice-based 3D textures, with low and high
dynamic range, at bitrates from below 1 bit/pixel up to 8 bits/pixel in fine steps.
The goal of this extension is to support the full 2D profile of the ASTC texture compression specification, and allow construction of 3D textures from
multiple 2D slices.
ASTC-compressed textures are handled in OpenGL by adding new supported formats to the existing mechanisms for handling compressed textures.
<h3>What is ASTC</h3>
ASTC stands for Adaptive Scalable Texture Compression. The ASTC formats form a family of related compressed texture image formats. They are all derived
from a common set of definitions.
ASTC textures may be either 2D or 3D.
ASTC textures may be encoded using either high or low dynamic range. Low dynamic range images may optionally be specified using the sRGB color space.
A sub-profile ("HDR Profile") is defined, which supports only 2D images (and 3D images made up of multiple 2D slices) at low or high dynamic range.
Support for this profile is indicated by the presence of the extension string "GL_KHR_texture_compression_astc_hdr". If, in future, the full profile is
supported, "GL_KHR_texture_compression_astc_hdr" must still be published, in order to ensure backward compatibility.
A lower sub-profile ("LDR Profile") may be implemented, which supports only 2D images at low dynamic range. This is indicated by the presence of the
extension string "GL_KHR_texture_compression_astc_ldr". If either the HDR or full profile are implemented, then both name strings
"GL_KHR_texture_compression_astc_ldr" and "GL_KHR_texture_compression_astc_hdr" must be published.
ASTC textures may be encoded as 1, 2, 3 or 4 components, but they are all decoded into RGBA.
ASTC has a variable block size, and this is specified as part of the name of the token passed to CompressedImage2D and its related functions.
"""
IntConstant(
"""
Accepted by the {@code internalformat} parameter of CompressedTexImage2D, CompressedTexSubImage2D, CompressedTexImage3D, CompressedTexSubImage3D,
TexStorage2D, TextureStorage2D, TexStorage3D, and TextureStorage3D.
""",
"COMPRESSED_RGBA_ASTC_4x4_KHR"..0x93B0,
"COMPRESSED_RGBA_ASTC_5x4_KHR"..0x93B1,
"COMPRESSED_RGBA_ASTC_5x5_KHR"..0x93B2,
"COMPRESSED_RGBA_ASTC_6x5_KHR"..0x93B3,
"COMPRESSED_RGBA_ASTC_6x6_KHR"..0x93B4,
"COMPRESSED_RGBA_ASTC_8x5_KHR"..0x93B5,
"COMPRESSED_RGBA_ASTC_8x6_KHR"..0x93B6,
"COMPRESSED_RGBA_ASTC_8x8_KHR"..0x93B7,
"COMPRESSED_RGBA_ASTC_10x5_KHR"..0x93B8,
"COMPRESSED_RGBA_ASTC_10x6_KHR"..0x93B9,
"COMPRESSED_RGBA_ASTC_10x8_KHR"..0x93BA,
"COMPRESSED_RGBA_ASTC_10x10_KHR"..0x93BB,
"COMPRESSED_RGBA_ASTC_12x10_KHR"..0x93BC,
"COMPRESSED_RGBA_ASTC_12x12_KHR"..0x93BD,
"COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR"..0x93D0,
"COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR"..0x93D1,
"COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR"..0x93D2,
"COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR"..0x93D3,
"COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR"..0x93D4,
"COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR"..0x93D5,
"COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR"..0x93D6,
"COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR"..0x93D7,
"COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR"..0x93D8,
"COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR"..0x93D9,
"COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR"..0x93DA,
"COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR"..0x93DB,
"COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR"..0x93DC,
"COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR"..0x93DD
)
}
val KHR_texture_compression_astc_hdr = EXT_FLAG.nativeClassGLES("KHR_texture_compression_astc_hdr", postfix = KHR) {
documentation =
"""
When true, the ${registryLink("KHR", "texture_compression_astc_hdr")} extension is supported.
This extension corresponds to the ASTC HDR Profile, see ${KHR_texture_compression_astc_ldr.link} for details.
"""
}
|
bsd-3-clause
|
27247566774431904b1ef3653bfc123a
| 48.293478 | 153 | 0.763344 | 3.197461 | false | false | false | false |
SevenLines/Celebs-Image-Viewer
|
src/main/kotlin/theplace/parsers/elements/items.kt
|
1
|
6136
|
package theplace.parsers.elements
import com.mashape.unirest.http.Unirest
import org.apache.commons.io.FileUtils
import org.apache.commons.io.FilenameUtils
import theplace.imageloaders.ImageLoaderSelector
import theplace.imageloaders.LoadedImage
import theplace.parsers.BaseParser
import java.io.FileInputStream
import java.io.Serializable
import java.nio.file.Path
import java.nio.file.Paths
/**
* Created by mk on 03.04.16.
*/
open class Gallery(var title: String = "",
var url: String = "",
var id: Int = -1,
@Transient var parser: BaseParser? = null) : Serializable {
protected var _subGalleries: List<SubGallery>? = null
val subGalleries: List<SubGallery>
get() {
_subGalleries = if (_subGalleries == null) parser?.getSubGalleries(this) else _subGalleries
return _subGalleries as? List<SubGallery> ?: emptyList()
}
override fun toString(): String {
return "$title"
}
}
class SubGallery(var title: String = "",
var url: String = "",
var id: Int = -1,
var gallery: Gallery? = null,
@Transient var parser: BaseParser? = null) {
protected var _albums: List<GalleryAlbum>? = null
val albums: List<GalleryAlbum>
get() {
_albums = if (_albums == null) gallery?.parser?.getAlbums(this) else _albums
return _albums as? List<GalleryAlbum> ?: emptyList()
}
/**
* refresh albums binded to this gallery
*/
fun refreshAlbums() {
_albums = gallery?.parser?.getAlbums(this)
}
}
class GalleryAlbum(var url: String = "",
var title: String = "",
var id: Int = -1,
var thumb: GalleryImage? = null,
var subgallery: SubGallery? = null,
@Transient var parser: BaseParser? = null) {
override fun toString(): String {
return "GalleryAlbum: ${subgallery?.title} [url: $url]"
}
protected var _pages: List<GalleryAlbumPage>? = null
val pages: List<GalleryAlbumPage>
get() {
_pages = if (_pages == null) subgallery?.gallery?.parser?.getAlbumPages(this) else _pages
return _pages as? List<GalleryAlbumPage> ?: emptyList()
}
}
class GalleryAlbumPage(var url: String, var album: GalleryAlbum? = null, @Transient var parser: BaseParser? = null) {
protected var _images: List<GalleryImage>? = null
val images: List<GalleryImage>
get() {
_images = if (_images == null) album?.subgallery?.gallery?.parser?.getImages(this) else _images
return _images as? List<GalleryImage> ?: emptyList()
}
}
class GalleryImage(var title: String = "",
val url: String,
val url_thumb: String,
var page: GalleryAlbumPage? = null,
var album: GalleryAlbum? = null,
@Transient var parser: BaseParser? = null) {
companion object {
@JvmStatic var CACHE_DIR: String = "cache"
@JvmStatic val THUMBS_PREFIX: String = "thumbs"
}
init {
title = ImageLoaderSelector.getTitle(url)
}
protected fun _download(isThumb: Boolean = false): LoadedImage? {
var url = if (isThumb) this.url_thumb else this.url
var prefix = if (isThumb) THUMBS_PREFIX else ""
var path = exists(Paths.get(CACHE_DIR), prefix)
if (path != null) {
return LoadedImage(url = path.toString(), body = FileInputStream(path.toFile()))
} else {
var loadedImage: LoadedImage?
if (isThumb) {
loadedImage = LoadedImage(url, Unirest.get("$url").header("referer", "$url").asBinary().body)
} else {
loadedImage = ImageLoaderSelector.download(url)
}
if (loadedImage?.body != null) {
var newPath = getPath(CACHE_DIR, prefix, FilenameUtils.getExtension(loadedImage?.url))
FileUtils.copyInputStreamToFile(loadedImage?.body, newPath.toFile())
loadedImage?.body?.reset()
}
return loadedImage
}
}
protected fun _saveToPath(path: Path, isThumb: Boolean = false): Path {
var prefix = if (isThumb) THUMBS_PREFIX else ""
var loadedImage = if (isThumb) downloadThumb() else download()
var newPath = getPath(
path.toString(), prefix = prefix, extension = FilenameUtils.getExtension(loadedImage?.url)
)
FileUtils.copyInputStreamToFile(loadedImage?.body, newPath.toFile())
return newPath
}
fun exists(directory_path: Path, prefix: String = ""): Path? {
return listOf("", "jpg", "jpeg", "png", "tiff", "tif", "gif").map {
getPath(directory_path.toString(), prefix, it)
}.firstOrNull {
it.toFile().exists()
}
}
fun thumbExists(directory_path: Path): Path? {
return exists(directory_path, THUMBS_PREFIX)
}
fun safeName(title: String): String {
var result = title.replace("""\.+$|"""".toRegex(), "").trim()
return result
}
fun getPath(directory_path: String, prefix: String = "", extension: String = ""): Path {
var ext = FilenameUtils.getExtension(title)
if (ext.isNullOrEmpty())
ext = extension
return Paths.get(directory_path, prefix,
safeName(page?.album?.subgallery?.gallery?.title ?: ""),
safeName(page?.album?.subgallery?.gallery?.parser?.title ?: ""),
safeName(page?.album?.subgallery?.title ?: ""),
safeName(page?.album?.title ?: ""),
"${FilenameUtils.getBaseName(title)}.$ext")
}
fun downloadThumb(): LoadedImage? {
return _download(true)
}
fun download(): LoadedImage? {
return _download()
}
fun saveThumbToPath(path: Path): Path {
return _saveToPath(path, true)
}
fun saveToPath(path: Path): Path {
return _saveToPath(path)
}
}
|
mit
|
b702cbd46e8e1ae725d8003d1208ed61
| 34.270115 | 117 | 0.582627 | 4.518409 | false | false | false | false |
esofthead/mycollab
|
mycollab-services/src/main/java/com/mycollab/form/view/builder/type/DynaSection.kt
|
3
|
1574
|
/**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>.
*/
package com.mycollab.form.view.builder.type
import com.mycollab.form.view.LayoutType
import java.util.*
/**
* @author MyCollab Ltd.
* @since 1.0
*/
class DynaSection : Comparable<DynaSection> {
var header: Enum<*>? = null
var contextHelp: Enum<*>? = null
var orderIndex: Int = 0
var isDeletedSection = false
lateinit var layoutType: LayoutType
private val fields = ArrayList<AbstractDynaField>()
var parentForm: DynaForm? = null
val fieldCount: Int
get() = fields.size
fun fields(vararg dynaFields: AbstractDynaField): DynaSection {
dynaFields.forEach {
fields.add(it)
it.ownSection = this
}
return this
}
fun getField(index: Int): AbstractDynaField = fields[index]
override fun compareTo(other: DynaSection): Int = orderIndex - other.orderIndex
}
|
agpl-3.0
|
e467e8b208b396ff1246ed4617758c62
| 30.46 | 83 | 0.697394 | 4.150396 | false | false | false | false |
inorichi/tachiyomi-extensions
|
multisrc/src/main/java/eu/kanade/tachiyomi/multisrc/wpmangareader/WPMangaReaderUrlActivity.kt
|
1
|
1171
|
package eu.kanade.tachiyomi.multisrc.wpmangareader
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.os.Bundle
import android.util.Log
import eu.kanade.tachiyomi.multisrc.wpmangareader.WPMangaReader
import kotlin.system.exitProcess
class WPMangaReaderUrlActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val pathSegments = intent?.data?.pathSegments
if (pathSegments != null && pathSegments.size >= 1) {
val mainIntent = Intent().apply {
action = "eu.kanade.tachiyomi.SEARCH"
putExtra("query","${WPMangaReader.URL_SEARCH_PREFIX}${intent?.data?.toString()}")
putExtra("filter", packageName)
}
try {
startActivity(mainIntent)
} catch (e: ActivityNotFoundException) {
Log.e("WPMangaReaderUrl", e.toString())
}
} else {
Log.e("WPMangaReaderUrl", "could not parse uri from intent $intent")
}
finish()
exitProcess(0)
}
}
|
apache-2.0
|
523352531c7b34847c38290423415e19
| 31.527778 | 97 | 0.637916 | 4.982979 | false | false | false | false |
rhdunn/xquery-intellij-plugin
|
src/xqt-platform-intellij-ft/main/xqt/platform/intellij/ft/XPathFTTokenProvider.kt
|
1
|
14149
|
// Copyright (C) 2022 Reece H. Dunn. SPDX-License-Identifier: Apache-2.0
package xqt.platform.intellij.ft
import xqt.platform.ft.v3.lexer.tokens.XPath30FT10TokenProvider
import xqt.platform.intellij.lexer.token.*
import xqt.platform.intellij.xpath.XPath
import xqt.platform.intellij.xpath.XPathTokenProvider
/**
* The tokens present in the XPath with Full Text grammar.
*/
object XPathFTTokenProvider : XPath30FT10TokenProvider {
// region XPath10TokenProvider
override val AbbrevAttribute: ISymbolTokenType get() = XPathTokenProvider.AbbrevAttribute
override val AbbrevDescendantOrSelf: ISymbolTokenType get() = XPathTokenProvider.AbbrevDescendantOrSelf
override val AbbrevParent: ISymbolTokenType get() = XPathTokenProvider.AbbrevParent
override val AxisSeparator: ISymbolTokenType get() = XPathTokenProvider.AxisSeparator
override val Colon: ISymbolTokenType get() = XPathTokenProvider.Colon
override val Comma: ISymbolTokenType get() = XPathTokenProvider.Comma
override val ContextItem: ISymbolTokenType get() = XPathTokenProvider.ContextItem
override val Equals: ISymbolTokenType get() = XPathTokenProvider.Equals
override val GreaterThan: ISymbolTokenType get() = XPathTokenProvider.GreaterThan
override val GreaterThanOrEquals: ISymbolTokenType get() = XPathTokenProvider.GreaterThanOrEquals
override val LessThan: ISymbolTokenType get() = XPathTokenProvider.LessThan
override val LessThanOrEquals: ISymbolTokenType get() = XPathTokenProvider.LessThanOrEquals
override val Minus: ISymbolTokenType get() = XPathTokenProvider.Minus
override val NotEquals: ISymbolTokenType get() = XPathTokenProvider.NotEquals
override val ParenthesisClose: ISymbolTokenType get() = XPathTokenProvider.ParenthesisClose
override val ParenthesisOpen: ISymbolTokenType get() = XPathTokenProvider.ParenthesisOpen
override val PathOperator: ISymbolTokenType get() = XPathTokenProvider.PathOperator
override val Plus: ISymbolTokenType get() = XPathTokenProvider.Plus
override val SquareBracketClose: ISymbolTokenType get() = XPathTokenProvider.SquareBracketClose
override val SquareBracketOpen: ISymbolTokenType get() = XPathTokenProvider.SquareBracketOpen
override val Star: ISymbolTokenType get() = XPathTokenProvider.Star
override val Union: ISymbolTokenType get() = XPathTokenProvider.Union
override val VariableIndicator: ISymbolTokenType get() = XPathTokenProvider.VariableIndicator
override val Literal: ITerminalSymbolTokenType get() = XPathTokenProvider.Literal
override val Number: ITerminalSymbolTokenType get() = XPathTokenProvider.Number
override val NCName: INCNameTokenType get() = XPathTokenProvider.NCName
override val PrefixedName: ITerminalSymbolTokenType get() = XPathTokenProvider.PrefixedName
override val S: IWrappedTerminalSymbolTokenType get() = XPathTokenProvider.S
override val KAncestor: IKeywordTokenType get() = XPathTokenProvider.KAncestor
override val KAncestorOrSelf: IKeywordTokenType get() = XPathTokenProvider.KAncestorOrSelf
override val KAnd: IKeywordTokenType get() = XPathTokenProvider.KAnd
override val KAttribute: IKeywordTokenType get() = XPathTokenProvider.KAttribute
override val KChild: IKeywordTokenType get() = XPathTokenProvider.KChild
override val KComment: IKeywordTokenType get() = XPathTokenProvider.KComment
override val KDescendant: IKeywordTokenType get() = XPathTokenProvider.KDescendant
override val KDescendantOrSelf: IKeywordTokenType get() = XPathTokenProvider.KDescendantOrSelf
override val KDiv: IKeywordTokenType get() = XPathTokenProvider.KDiv
override val KFollowing: IKeywordTokenType get() = XPathTokenProvider.KFollowing
override val KFollowingSibling: IKeywordTokenType get() = XPathTokenProvider.KFollowingSibling
override val KMod: IKeywordTokenType get() = XPathTokenProvider.KMod
override val KNamespace: IKeywordTokenType get() = XPathTokenProvider.KNamespace
override val KNode: IKeywordTokenType get() = XPathTokenProvider.KNode
override val KOr: IKeywordTokenType get() = XPathTokenProvider.KOr
override val KParent: IKeywordTokenType get() = XPathTokenProvider.KParent
override val KPreceding: IKeywordTokenType get() = XPathTokenProvider.KPreceding
override val KPrecedingSibling: IKeywordTokenType get() = XPathTokenProvider.KPrecedingSibling
override val KProcessingInstruction: IKeywordTokenType get() = XPathTokenProvider.KProcessingInstruction
override val KSelf: IKeywordTokenType get() = XPathTokenProvider.KSelf
override val KText: IKeywordTokenType get() = XPathTokenProvider.KText
// endregion
// region XPath20TokenProvider
override val EscapeApos: ISymbolTokenType get() = XPathTokenProvider.EscapeApos
override val EscapeQuot: ISymbolTokenType get() = XPathTokenProvider.EscapeQuot
override val NodePrecedes: ISymbolTokenType get() = XPathTokenProvider.NodePrecedes
override val NodeFollows: ISymbolTokenType get() = XPathTokenProvider.NodeFollows
override val QuestionMark: ISymbolTokenType get() = XPathTokenProvider.QuestionMark
override val StringLiteralApos: ISymbolTokenType get() = XPathTokenProvider.StringLiteralApos
override val StringLiteralQuot: ISymbolTokenType get() = XPathTokenProvider.StringLiteralQuot
override val IntegerLiteral: ITerminalSymbolTokenType get() = XPathTokenProvider.IntegerLiteral
override val DecimalLiteral: ITerminalSymbolTokenType get() = XPathTokenProvider.DecimalLiteral
override val DoubleLiteral: ITerminalSymbolTokenType get() = XPathTokenProvider.DoubleLiteral
override val StringLiteralAposContents: ITerminalSymbolTokenType get() = XPathTokenProvider.StringLiteralAposContents
override val StringLiteralQuotContents: ITerminalSymbolTokenType get() = XPathTokenProvider.StringLiteralQuotContents
override val CommentOpen: ISymbolTokenType get() = XPathTokenProvider.CommentOpen
override val CommentContents: ITerminalSymbolTokenType get() = XPathTokenProvider.CommentContents
override val CommentClose: ISymbolTokenType get() = XPathTokenProvider.CommentClose
override val KAs: IKeywordTokenType get() = XPathTokenProvider.KAs
override val KCast: IKeywordTokenType get() = XPathTokenProvider.KCast
override val KCastable: IKeywordTokenType get() = XPathTokenProvider.KCastable
override val KDocumentNode: IKeywordTokenType get() = XPathTokenProvider.KDocumentNode
override val KElement: IKeywordTokenType get() = XPathTokenProvider.KElement
override val KElse: IKeywordTokenType get() = XPathTokenProvider.KElse
override val KEmptySequence: IKeywordTokenType get() = XPathTokenProvider.KEmptySequence
override val KEq: IKeywordTokenType get() = XPathTokenProvider.KEq
override val KEvery: IKeywordTokenType get() = XPathTokenProvider.KEvery
override val KExcept: IKeywordTokenType get() = XPathTokenProvider.KExcept
override val KFor: IKeywordTokenType get() = XPathTokenProvider.KFor
override val KGe: IKeywordTokenType get() = XPathTokenProvider.KGe
override val KGt: IKeywordTokenType get() = XPathTokenProvider.KGt
override val KIDiv: IKeywordTokenType get() = XPathTokenProvider.KIDiv
override val KIf: IKeywordTokenType get() = XPathTokenProvider.KIf
override val KIn: IKeywordTokenType get() = XPathTokenProvider.KIn
override val KInstance: IKeywordTokenType get() = XPathTokenProvider.KInstance
override val KIntersect: IKeywordTokenType get() = XPathTokenProvider.KIntersect
override val KIs: IKeywordTokenType get() = XPathTokenProvider.KIs
override val KItem: IKeywordTokenType get() = XPathTokenProvider.KItem
override val KLe: IKeywordTokenType get() = XPathTokenProvider.KLe
override val KLt: IKeywordTokenType get() = XPathTokenProvider.KLt
override val KNe: IKeywordTokenType get() = XPathTokenProvider.KNe
override val KOf: IKeywordTokenType get() = XPathTokenProvider.KOf
override val KReturn: IKeywordTokenType get() = XPathTokenProvider.KReturn
override val KSatisfies: IKeywordTokenType get() = XPathTokenProvider.KSatisfies
override val KSchemaAttribute: IKeywordTokenType get() = XPathTokenProvider.KSchemaAttribute
override val KSchemaElement: IKeywordTokenType get() = XPathTokenProvider.KSchemaElement
override val KSome: IKeywordTokenType get() = XPathTokenProvider.KSome
override val KThen: IKeywordTokenType get() = XPathTokenProvider.KThen
override val KTo: IKeywordTokenType get() = XPathTokenProvider.KTo
override val KTreat: IKeywordTokenType get() = XPathTokenProvider.KTreat
override val KUnion: IKeywordTokenType get() = XPathTokenProvider.KUnion
// endregion
// region XPath20FT10TokenProvider
override val CurlyBracketClose: ISymbolTokenType get() = XPathTokenProvider.CurlyBracketClose
override val CurlyBracketOpen: ISymbolTokenType get() = XPathTokenProvider.CurlyBracketOpen
override val PragmaClose: ISymbolTokenType = ISymbolTokenType("#)", "PRAGMA_END", XPath)
override val PragmaOpen: ISymbolTokenType = ISymbolTokenType("(#", "PRAGMA_BEGIN", XPath)
override val KAll: IKeywordTokenType = IKeywordTokenType("all", XPath)
override val KAny: IKeywordTokenType = IKeywordTokenType("any", XPath)
override val KAt: IKeywordTokenType = IKeywordTokenType("at", XPath)
override val KCase: IKeywordTokenType = IKeywordTokenType("case", XPath)
override val KContains: IKeywordTokenType = IKeywordTokenType("contains", XPath)
override val KContent: IKeywordTokenType = IKeywordTokenType("content", XPath)
override val KDefault: IKeywordTokenType = IKeywordTokenType("default", XPath)
override val KDiacritics: IKeywordTokenType = IKeywordTokenType("diacritics", XPath)
override val KDifferent: IKeywordTokenType = IKeywordTokenType("different", XPath)
override val KDistance: IKeywordTokenType = IKeywordTokenType("distance", XPath)
override val KEnd: IKeywordTokenType = IKeywordTokenType("end", XPath)
override val KEntire: IKeywordTokenType = IKeywordTokenType("entire", XPath)
override val KExactly: IKeywordTokenType = IKeywordTokenType("exactly", XPath)
override val KFrom: IKeywordTokenType = IKeywordTokenType("from", XPath)
override val KFtAnd: IKeywordTokenType = IKeywordTokenType("ftand", XPath)
override val KFtNot: IKeywordTokenType = IKeywordTokenType("ftnot", XPath)
override val KFtOr: IKeywordTokenType = IKeywordTokenType("ftor", XPath)
override val KInsensitive: IKeywordTokenType = IKeywordTokenType("insensitive", XPath)
override val KLanguage: IKeywordTokenType = IKeywordTokenType("language", XPath)
override val KLeast: IKeywordTokenType = IKeywordTokenType("least", XPath)
override val KLevels: IKeywordTokenType = IKeywordTokenType("levels", XPath)
override val KLowerCase: IKeywordTokenType = IKeywordTokenType("lowercase", XPath)
override val KMost: IKeywordTokenType = IKeywordTokenType("most", XPath)
override val KNo: IKeywordTokenType = IKeywordTokenType("no", XPath)
override val KNot: IKeywordTokenType = IKeywordTokenType("not", XPath)
override val KOccurs: IKeywordTokenType = IKeywordTokenType("occurs", XPath)
override val KOption: IKeywordTokenType = IKeywordTokenType("option", XPath)
override val KOrdered: IKeywordTokenType = IKeywordTokenType("ordered", XPath)
override val KParagraph: IKeywordTokenType = IKeywordTokenType("paragraph", XPath)
override val KParagraphs: IKeywordTokenType = IKeywordTokenType("paragraphs", XPath)
override val KPhrase: IKeywordTokenType = IKeywordTokenType("phrase", XPath)
override val KRelationship: IKeywordTokenType = IKeywordTokenType("relationship", XPath)
override val KSame: IKeywordTokenType = IKeywordTokenType("same", XPath)
override val KScore: IKeywordTokenType = IKeywordTokenType("score", XPath)
override val KSensitive: IKeywordTokenType = IKeywordTokenType("sensitive", XPath)
override val KSentence: IKeywordTokenType = IKeywordTokenType("sentence", XPath)
override val KSentences: IKeywordTokenType = IKeywordTokenType("sentences", XPath)
override val KStart: IKeywordTokenType = IKeywordTokenType("start", XPath)
override val KStemming: IKeywordTokenType = IKeywordTokenType("stemming", XPath)
override val KStop: IKeywordTokenType = IKeywordTokenType("stop", XPath)
override val KThesaurus: IKeywordTokenType = IKeywordTokenType("thesaurus", XPath)
override val KTimes: IKeywordTokenType = IKeywordTokenType("times", XPath)
override val KUpperCase: IKeywordTokenType = IKeywordTokenType("uppercase", XPath)
override val KUsing: IKeywordTokenType = IKeywordTokenType("using", XPath)
override val KWeight: IKeywordTokenType = IKeywordTokenType("weight", XPath)
override val KWildcards: IKeywordTokenType = IKeywordTokenType("wildcards", XPath)
override val KWindow: IKeywordTokenType = IKeywordTokenType("window", XPath)
override val KWithout: IKeywordTokenType = IKeywordTokenType("without", XPath)
override val KWord: IKeywordTokenType = IKeywordTokenType("word", XPath)
override val KWords: IKeywordTokenType = IKeywordTokenType("words", XPath)
override val PragmaContents: ITerminalSymbolTokenType = ITerminalSymbolTokenType("PragmaContents", "PRAGMA_CONTENTS", XPath)
// endregion
// region XPath30TokenProvider
override val AssignEquals: ISymbolTokenType get() = XPathTokenProvider.AssignEquals
override val Concatenation: ISymbolTokenType get() = XPathTokenProvider.Concatenation
override val FunctionRef: ISymbolTokenType get() = XPathTokenProvider.FunctionRef
override val MapOperator: ISymbolTokenType get() = XPathTokenProvider.MapOperator
override val BracedURILiteral: ITerminalSymbolTokenType get() = XPathTokenProvider.BracedURILiteral
override val KFunction: IKeywordTokenType get() = XPathTokenProvider.KFunction
override val KLet: IKeywordTokenType get() = XPathTokenProvider.KLet
override val KNamespaceNode: IKeywordTokenType get() = XPathTokenProvider.KNamespaceNode
// endregion
}
|
apache-2.0
|
da6a120664ed0c388dc36a6f52d7f3c1
| 69.745 | 128 | 0.798007 | 5.786912 | false | false | false | false |
Heiner1/AndroidAPS
|
app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadHistory.kt
|
1
|
1398
|
package info.nightscout.androidaps.queue.commands
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.Dana
import info.nightscout.androidaps.interfaces.Diaconn
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.queue.Callback
import javax.inject.Inject
class CommandLoadHistory(
injector: HasAndroidInjector,
private val type: Byte,
callback: Callback?
) : Command(injector, CommandType.LOAD_HISTORY, callback) {
@Inject lateinit var activePlugin: ActivePlugin
override fun execute() {
val pump = activePlugin.activePump
if (pump is Dana) {
val danaPump = pump as Dana
val r = danaPump.loadHistory(type)
aapsLogger.debug(LTag.PUMPQUEUE, "Result success: " + r.success + " enacted: " + r.enacted)
callback?.result(r)?.run()
}
if (pump is Diaconn) {
val diaconnG8Pump = pump as Diaconn
val r = diaconnG8Pump.loadHistory()
aapsLogger.debug(LTag.PUMPQUEUE, "Result success: " + r.success + " enacted: " + r.enacted)
callback?.result(r)?.run()
}
}
override fun status(): String = rh.gs(R.string.load_history, type.toInt())
override fun log(): String = "LOAD HISTORY $type"
}
|
agpl-3.0
|
e146f5198847c171ebc31a67f22fe454
| 33.975 | 103 | 0.68598 | 4.262195 | false | false | false | false |
Heiner1/AndroidAPS
|
core/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.kt
|
1
|
17942
|
package info.nightscout.androidaps.plugins.aps.loop
import android.text.Spanned
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.core.R
import info.nightscout.androidaps.data.IobTotal
import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.extensions.convertedToAbsolute
import info.nightscout.androidaps.extensions.convertedToPercent
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.IobCobCalculator
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.PumpDescription
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.DecimalFormatter
import info.nightscout.androidaps.utils.HtmlHelper.fromHtml
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.shared.sharedPreferences.SP
import org.json.JSONException
import org.json.JSONObject
import java.util.*
import javax.inject.Inject
import kotlin.math.abs
import kotlin.math.max
/**
* Created by mike on 09.06.2016.
*/
@Suppress("LeakingThis")
open class APSResult @Inject constructor(val injector: HasAndroidInjector) {
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var sp: SP
@Inject lateinit var activePlugin: ActivePlugin
@Inject lateinit var iobCobCalculator: IobCobCalculator
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var rh: ResourceHelper
@Inject lateinit var dateUtil: DateUtil
var date: Long = 0
var reason: String = ""
var rate = 0.0
var percent = 0
var usePercent = false
var duration = 0
var tempBasalRequested = false
var iob: IobTotal? = null
var json: JSONObject? = JSONObject()
var hasPredictions = false
var smb = 0.0 // super micro bolus in units
var deliverAt: Long = 0
var targetBG = 0.0
var carbsReq = 0
var carbsReqWithin = 0
var inputConstraints: Constraint<Double>? = null
var rateConstraint: Constraint<Double>? = null
var percentConstraint: Constraint<Int>? = null
var smbConstraint: Constraint<Double>? = null
init {
injector.androidInjector().inject(this)
}
fun rate(rate: Double): APSResult {
this.rate = rate
return this
}
fun duration(duration: Int): APSResult {
this.duration = duration
return this
}
fun percent(percent: Int): APSResult {
this.percent = percent
return this
}
fun tempBasalRequested(tempBasalRequested: Boolean): APSResult {
this.tempBasalRequested = tempBasalRequested
return this
}
fun usePercent(usePercent: Boolean): APSResult {
this.usePercent = usePercent
return this
}
fun json(json: JSONObject?): APSResult {
this.json = json
return this
}
val carbsRequiredText: String
get() = rh.gs(R.string.carbsreq, carbsReq, carbsReqWithin)
override fun toString(): String {
val pump = activePlugin.activePump
if (isChangeRequested) {
// rate
var ret: String = if (rate == 0.0 && duration == 0) "${rh.gs(R.string.canceltemp)} "
else if (rate == -1.0) "${rh.gs(R.string.let_temp_basal_run)}\n"
else if (usePercent) "${rh.gs(R.string.rate)}: ${DecimalFormatter.to2Decimal(percent.toDouble())}% (${DecimalFormatter.to2Decimal(percent * pump.baseBasalRate / 100.0)} U/h) " +
"${rh.gs(R.string.duration)}: ${DecimalFormatter.to2Decimal(duration.toDouble())} min "
else "${rh.gs(R.string.rate)}: ${DecimalFormatter.to2Decimal(rate)} U/h (${DecimalFormatter.to2Decimal(rate / pump.baseBasalRate * 100)}%) " +
"${rh.gs(R.string.duration)}: ${DecimalFormatter.to2Decimal(duration.toDouble())} min "
// smb
if (smb != 0.0) ret += "SMB: ${DecimalFormatter.toPumpSupportedBolus(smb, activePlugin.activePump, rh)} "
if (isCarbsRequired) {
ret += "$carbsRequiredText "
}
// reason
ret += rh.gs(R.string.reason) + ": " + reason
return ret
}
return if (isCarbsRequired) {
carbsRequiredText
} else rh.gs(R.string.nochangerequested)
}
fun toSpanned(): Spanned {
val pump = activePlugin.activePump
if (isChangeRequested) {
// rate
var ret: String = if (rate == 0.0 && duration == 0) rh.gs(R.string.canceltemp) + "<br>" else if (rate == -1.0) rh.gs(R.string.let_temp_basal_run) + "<br>" else if (usePercent) "<b>" + rh.gs(R.string.rate) + "</b>: " + DecimalFormatter.to2Decimal(percent.toDouble()) + "% " +
"(" + DecimalFormatter.to2Decimal(percent * pump.baseBasalRate / 100.0) + " U/h)<br>" +
"<b>" + rh.gs(R.string.duration) + "</b>: " + DecimalFormatter.to2Decimal(duration.toDouble()) + " min<br>" else "<b>" + rh.gs(R.string.rate) + "</b>: " + DecimalFormatter.to2Decimal(rate) + " U/h " +
"(" + DecimalFormatter.to2Decimal(rate / pump.baseBasalRate * 100.0) + "%) <br>" +
"<b>" + rh.gs(R.string.duration) + "</b>: " + DecimalFormatter.to2Decimal(duration.toDouble()) + " min<br>"
// smb
if (smb != 0.0) ret += "<b>" + "SMB" + "</b>: " + DecimalFormatter.toPumpSupportedBolus(smb, activePlugin.activePump, rh) + "<br>"
if (isCarbsRequired) {
ret += "$carbsRequiredText<br>"
}
// reason
ret += "<b>" + rh.gs(R.string.reason) + "</b>: " + reason.replace("<", "<").replace(">", ">")
return fromHtml(ret)
}
return if (isCarbsRequired) {
fromHtml(carbsRequiredText)
} else fromHtml(rh.gs(R.string.nochangerequested))
}
open fun newAndClone(injector: HasAndroidInjector): APSResult {
val newResult = APSResult(injector)
doClone(newResult)
return newResult
}
protected fun doClone(newResult: APSResult) {
newResult.date = date
newResult.reason = reason
newResult.rate = rate
newResult.duration = duration
newResult.tempBasalRequested = tempBasalRequested
newResult.iob = iob
newResult.json = JSONObject(json.toString())
newResult.hasPredictions = hasPredictions
newResult.smb = smb
newResult.deliverAt = deliverAt
newResult.rateConstraint = rateConstraint
newResult.smbConstraint = smbConstraint
newResult.percent = percent
newResult.usePercent = usePercent
newResult.carbsReq = carbsReq
newResult.carbsReqWithin = carbsReqWithin
newResult.targetBG = targetBG
}
open fun json(): JSONObject? {
val json = JSONObject()
if (isChangeRequested) {
json.put("rate", rate)
json.put("duration", duration)
json.put("reason", reason)
}
return json
}
val predictions: MutableList<GlucoseValue>
get() {
val array: MutableList<GlucoseValue> = ArrayList()
val startTime = date
json?.let { json ->
if (json.has("predBGs")) {
val predBGs = json.getJSONObject("predBGs")
if (predBGs.has("IOB")) {
val iob = predBGs.getJSONArray("IOB")
for (i in 1 until iob.length()) {
val gv = GlucoseValue(
raw = 0.0,
noise = 0.0,
value = iob.getInt(i).toDouble(),
timestamp = startTime + i * 5 * 60 * 1000L,
sourceSensor = GlucoseValue.SourceSensor.IOB_PREDICTION,
trendArrow = GlucoseValue.TrendArrow.NONE
)
array.add(gv)
}
}
if (predBGs.has("aCOB")) {
val iob = predBGs.getJSONArray("aCOB")
for (i in 1 until iob.length()) {
val gv = GlucoseValue(
raw = 0.0,
noise = 0.0,
value = iob.getInt(i).toDouble(),
timestamp = startTime + i * 5 * 60 * 1000L,
sourceSensor = GlucoseValue.SourceSensor.A_COB_PREDICTION,
trendArrow = GlucoseValue.TrendArrow.NONE
)
array.add(gv)
}
}
if (predBGs.has("COB")) {
val iob = predBGs.getJSONArray("COB")
for (i in 1 until iob.length()) {
val gv = GlucoseValue(
raw = 0.0,
noise = 0.0,
value = iob.getInt(i).toDouble(),
timestamp = startTime + i * 5 * 60 * 1000L,
sourceSensor = GlucoseValue.SourceSensor.COB_PREDICTION,
trendArrow = GlucoseValue.TrendArrow.NONE
)
array.add(gv)
}
}
if (predBGs.has("UAM")) {
val iob = predBGs.getJSONArray("UAM")
for (i in 1 until iob.length()) {
val gv = GlucoseValue(
raw = 0.0,
noise = 0.0,
value = iob.getInt(i).toDouble(),
timestamp = startTime + i * 5 * 60 * 1000L,
sourceSensor = GlucoseValue.SourceSensor.UAM_PREDICTION,
trendArrow = GlucoseValue.TrendArrow.NONE
)
array.add(gv)
}
}
if (predBGs.has("ZT")) {
val iob = predBGs.getJSONArray("ZT")
for (i in 1 until iob.length()) {
val gv = GlucoseValue(
raw = 0.0,
noise = 0.0,
value = iob.getInt(i).toDouble(),
timestamp = startTime + i * 5 * 60 * 1000L,
sourceSensor = GlucoseValue.SourceSensor.ZT_PREDICTION,
trendArrow = GlucoseValue.TrendArrow.NONE
)
array.add(gv)
}
}
}
}
return array
}
val latestPredictionsTime: Long
get() {
var latest: Long = 0
try {
val startTime = date
if (json != null && json!!.has("predBGs")) {
val predBGs = json!!.getJSONObject("predBGs")
if (predBGs.has("IOB")) {
val iob = predBGs.getJSONArray("IOB")
latest = max(latest, startTime + (iob.length() - 1) * 5 * 60 * 1000L)
}
if (predBGs.has("aCOB")) {
val iob = predBGs.getJSONArray("aCOB")
latest = max(latest, startTime + (iob.length() - 1) * 5 * 60 * 1000L)
}
if (predBGs.has("COB")) {
val iob = predBGs.getJSONArray("COB")
latest = max(latest, startTime + (iob.length() - 1) * 5 * 60 * 1000L)
}
if (predBGs.has("UAM")) {
val iob = predBGs.getJSONArray("UAM")
latest = max(latest, startTime + (iob.length() - 1) * 5 * 60 * 1000L)
}
if (predBGs.has("ZT")) {
val iob = predBGs.getJSONArray("ZT")
latest = max(latest, startTime + (iob.length() - 1) * 5 * 60 * 1000L)
}
}
} catch (e: JSONException) {
aapsLogger.error("Unhandled exception", e)
}
return latest
}
val isCarbsRequired: Boolean
get() = carbsReq > 0
val isChangeRequested: Boolean
get() {
val closedLoopEnabled = constraintChecker.isClosedLoopAllowed()
// closed loop mode: handle change at driver level
if (closedLoopEnabled.value()) {
aapsLogger.debug(LTag.APS, "DEFAULT: Closed mode")
return tempBasalRequested || bolusRequested()
}
// open loop mode: try to limit request
if (!tempBasalRequested && !bolusRequested()) {
aapsLogger.debug(LTag.APS, "FALSE: No request")
return false
}
val now = System.currentTimeMillis()
val activeTemp = iobCobCalculator.getTempBasalIncludingConvertedExtended(now)
val pump = activePlugin.activePump
val profile = profileFunction.getProfile()
if (profile == null) {
aapsLogger.error("FALSE: No Profile")
return false
}
return if (usePercent) {
if (activeTemp == null && percent == 100) {
aapsLogger.debug(LTag.APS, "FALSE: No temp running, asking cancel temp")
return false
}
if (activeTemp != null && abs(percent - activeTemp.convertedToPercent(now, profile)) < pump.pumpDescription.basalStep) {
aapsLogger.debug(LTag.APS, "FALSE: Temp equal")
return false
}
// always report zero temp
if (percent == 0) {
aapsLogger.debug(LTag.APS, "TRUE: Zero temp")
return true
}
// always report high temp
if (pump.pumpDescription.tempBasalStyle == PumpDescription.PERCENT) {
val pumpLimit = pump.pumpDescription.pumpType.tbrSettings?.maxDose ?: 0.0
if (percent.toDouble() == pumpLimit) {
aapsLogger.debug(LTag.APS, "TRUE: Pump limit")
return true
}
}
// report change bigger than 30%
var percentMinChangeChange = sp.getDouble(R.string.key_loop_openmode_min_change, 30.0)
percentMinChangeChange /= 100.0
val lowThreshold = 1 - percentMinChangeChange
val highThreshold = 1 + percentMinChangeChange
var change = percent / 100.0
if (activeTemp != null) change = percent / activeTemp.convertedToPercent(now, profile).toDouble()
if (change < lowThreshold || change > highThreshold) {
aapsLogger.debug(LTag.APS, "TRUE: Outside allowed range " + change * 100.0 + "%")
true
} else {
aapsLogger.debug(LTag.APS, "TRUE: Inside allowed range " + change * 100.0 + "%")
false
}
} else {
if (activeTemp == null && rate == pump.baseBasalRate) {
aapsLogger.debug(LTag.APS, "FALSE: No temp running, asking cancel temp")
return false
}
if (activeTemp != null && abs(rate - activeTemp.convertedToAbsolute(now, profile)) < pump.pumpDescription.basalStep) {
aapsLogger.debug(LTag.APS, "FALSE: Temp equal")
return false
}
// always report zero temp
if (rate == 0.0) {
aapsLogger.debug(LTag.APS, "TRUE: Zero temp")
return true
}
// always report high temp
if (pump.pumpDescription.tempBasalStyle == PumpDescription.ABSOLUTE) {
val pumpLimit = pump.pumpDescription.pumpType.tbrSettings?.maxDose ?: 0.0
if (rate == pumpLimit) {
aapsLogger.debug(LTag.APS, "TRUE: Pump limit")
return true
}
}
// report change bigger than 30%
var percentMinChangeChange = sp.getDouble(R.string.key_loop_openmode_min_change, 30.0)
percentMinChangeChange /= 100.0
val lowThreshold = 1 - percentMinChangeChange
val highThreshold = 1 + percentMinChangeChange
var change = rate / profile.getBasal()
if (activeTemp != null) change = rate / activeTemp.convertedToAbsolute(now, profile)
if (change < lowThreshold || change > highThreshold) {
aapsLogger.debug(LTag.APS, "TRUE: Outside allowed range " + change * 100.0 + "%")
true
} else {
aapsLogger.debug(LTag.APS, "TRUE: Inside allowed range " + change * 100.0 + "%")
false
}
}
}
fun bolusRequested(): Boolean = smb > 0.0
}
|
agpl-3.0
|
43b157f3cb5bfd9a0cbce01d465bee21
| 43.523573 | 286 | 0.519284 | 5.079841 | false | false | false | false |
rolandvitezhu/TodoCloud
|
app/src/main/java/com/rolandvitezhu/todocloud/ui/activity/main/adapter/ListAdapter.kt
|
1
|
2262
|
package com.rolandvitezhu.todocloud.ui.activity.main.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import com.rolandvitezhu.todocloud.databinding.ItemListBinding
import com.rolandvitezhu.todocloud.di.FragmentScope
import java.util.*
import javax.inject.Inject
@FragmentScope
class ListAdapter @Inject constructor() : BaseAdapter() {
private val lists: MutableList<com.rolandvitezhu.todocloud.data.List>
override fun getCount(): Int {
return lists.size
}
override fun getItem(position: Int): Any {
return lists[position]
}
override fun getItemId(position: Int): Long {
val (_id) = lists[position]
return _id!!
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var convertView = convertView
val itemListBinding: ItemListBinding
val layoutInflater = parent.context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE
) as LayoutInflater
if (convertView == null) {
itemListBinding = ItemListBinding.inflate(
layoutInflater,
parent,
false
)
convertView = itemListBinding.root
} else {
itemListBinding = convertView.tag as ItemListBinding
}
itemListBinding.list = lists[position]
itemListBinding.executePendingBindings()
convertView.tag = itemListBinding
return convertView
}
fun update(lists: List<com.rolandvitezhu.todocloud.data.List>?) {
this.lists.clear()
this.lists.addAll(lists!!)
}
fun clear() {
lists.clear()
notifyDataSetChanged()
}
fun toggleSelection(position: Int) {
lists[position].isSelected = isNotSelected(position)
notifyDataSetChanged()
}
fun clearSelection() {
for (list in lists) {
list.isSelected = false
}
notifyDataSetChanged()
}
private fun isNotSelected(position: Int): Boolean {
return !lists[position].isSelected
}
init {
lists = ArrayList()
}
}
|
mit
|
c63bd7d6e5ff5ba2f946fec0e9f97dd2
| 25.313953 | 86 | 0.64191 | 5.129252 | false | false | false | false |
Maccimo/intellij-community
|
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/versions/NormalizedPackageVersion.kt
|
1
|
8195
|
/*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions
import com.intellij.util.text.VersionComparatorUtil
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion
import com.jetbrains.packagesearch.intellij.plugin.util.versionTokenPriorityProvider
import kotlinx.serialization.Serializable
@Serializable
internal sealed class NormalizedPackageVersion<T : PackageVersion>(
val originalVersion: T
) : Comparable<NormalizedPackageVersion<*>> {
val versionName: String
get() = originalVersion.versionName
val displayName: String
get() = originalVersion.displayName
val isStable: Boolean
get() = originalVersion.isStable
val releasedAt: Long?
get() = originalVersion.releasedAt
@Serializable
data class Semantic(
private val original: PackageVersion.Named,
val semanticPart: String,
override val stabilityMarker: String?,
override val nonSemanticSuffix: String?
) : NormalizedPackageVersion<PackageVersion.Named>(original), DecoratedVersion {
val semanticPartWithStabilityMarker = semanticPart + (stabilityMarker ?: "")
override fun compareTo(other: NormalizedPackageVersion<*>): Int =
when (other) {
is Semantic -> compareByNameAndThenByTimestamp(other)
is TimestampLike, is Garbage, is Missing -> 1
}
private fun compareByNameAndThenByTimestamp(other: Semantic): Int {
// First, compare semantic parts and stability markers only
val nameComparisonResult = VersionComparatorUtil.compare(
semanticPartWithStabilityMarker,
other.semanticPartWithStabilityMarker,
::versionTokenPriorityProvider
)
if (nameComparisonResult != 0) return nameComparisonResult
// If they're identical, but only one has a non-semantic suffix, that's the larger one.
// If both or neither have a non-semantic suffix, we move to the next step
when {
nonSemanticSuffix.isNullOrBlank() && !other.nonSemanticSuffix.isNullOrBlank() -> return -1
!nonSemanticSuffix.isNullOrBlank() && other.nonSemanticSuffix.isNullOrBlank() -> return 1
}
// If both have a comparable non-semantic suffix, and they're different, that determines the result.
// Blank/null suffixes aren't comparable, so if they're both null/blank, we move to the next step
if (canBeUsedForComparison(nonSemanticSuffix) && canBeUsedForComparison(other.nonSemanticSuffix)) {
val comparisonResult = VersionComparatorUtil.compare(versionName, other.versionName, ::versionTokenPriorityProvider)
if (comparisonResult != 0) return comparisonResult
}
// Fallback: neither has a comparable non-semantic suffix, so timestamp is all we're left with
return original.compareByTimestamp(other.original)
}
private fun canBeUsedForComparison(nonSemanticSuffix: String?): Boolean {
if (nonSemanticSuffix.isNullOrBlank()) return false
val normalizedSuffix = nonSemanticSuffix.trim().lowercase()
val hasGitHashLength = normalizedSuffix.length in 7..10 || normalizedSuffix.length == 40
if (hasGitHashLength && normalizedSuffix.all { it.isDigit() || it in HEX_CHARS || !it.isLetter() }) return false
return true
}
companion object {
private val HEX_CHARS = 'a'..'f'
}
}
@Serializable
data class TimestampLike(
private val original: PackageVersion.Named,
val timestampPrefix: String,
override val stabilityMarker: String?,
override val nonSemanticSuffix: String?
) : NormalizedPackageVersion<PackageVersion.Named>(original), DecoratedVersion {
private val timestampPrefixWithStabilityMarker = timestampPrefix + (stabilityMarker ?: "")
override fun compareTo(other: NormalizedPackageVersion<*>): Int =
when (other) {
is TimestampLike -> compareByNameAndThenByTimestamp(other)
is Semantic -> -1
is Garbage, is Missing -> 1
}
private fun compareByNameAndThenByTimestamp(other: TimestampLike): Int {
val nameComparisonResult = VersionComparatorUtil.compare(
timestampPrefixWithStabilityMarker,
other.timestampPrefixWithStabilityMarker,
::versionTokenPriorityProvider
)
return if (nameComparisonResult == 0) {
original.compareByTimestamp(other.original)
} else {
nameComparisonResult
}
}
}
@Serializable
data class Garbage(
private val original: PackageVersion.Named
) : NormalizedPackageVersion<PackageVersion.Named>(original) {
override fun compareTo(other: NormalizedPackageVersion<*>): Int =
when (other) {
is Missing -> 1
is Garbage -> compareByNameAndThenByTimestamp(other)
is Semantic, is TimestampLike -> -1
}
private fun compareByNameAndThenByTimestamp(other: Garbage): Int {
val nameComparisonResult = VersionComparatorUtil.compare(original.versionName, other.original.versionName)
return if (nameComparisonResult == 0) {
original.compareByTimestamp(other.original)
} else {
nameComparisonResult
}
}
}
@Serializable
object Missing : NormalizedPackageVersion<PackageVersion.Missing>(PackageVersion.Missing) {
override fun compareTo(other: NormalizedPackageVersion<*>): Int =
when (other) {
is Missing -> 0
else -> -1
}
}
// If only one of them has a releasedAt, it wins. If neither does, they're equal.
// If both have a releasedAt, we use those to discriminate.
protected fun PackageVersion.Named.compareByTimestamp(other: PackageVersion.Named) =
when {
releasedAt == null && other.releasedAt == null -> 0
releasedAt != null && other.releasedAt == null -> 1
releasedAt == null && other.releasedAt != null -> -1
else -> releasedAt!!.compareTo(other.releasedAt!!)
}
fun nonSemanticSuffixOrNull(): String? =
when (this) {
is Semantic -> nonSemanticSuffix
is TimestampLike -> nonSemanticSuffix
is Garbage, is Missing -> null
}
interface DecoratedVersion {
val stabilityMarker: String?
val nonSemanticSuffix: String?
}
companion object {
suspend fun parseFrom(version: PackageVersion.Named, normalizer: PackageVersionNormalizer): NormalizedPackageVersion<PackageVersion.Named> =
normalizer.parse(version)
suspend fun <T : PackageVersion> parseFrom(version: T, normalizer: PackageVersionNormalizer): NormalizedPackageVersion<*> =
when (version) {
is PackageVersion.Missing -> Missing
is PackageVersion.Named -> parseFrom(version, normalizer)
else -> error("Unknown version type: ${version.javaClass.simpleName}")
}
}
}
|
apache-2.0
|
7b493a5b4d456f13611e5c5907f221cf
| 40.388889 | 148 | 0.641123 | 5.836895 | false | false | false | false |
Maccimo/intellij-community
|
plugins/markdown/test/src/org/intellij/plugins/markdown/model/UnresolvedHeaderReferenceInspectionTest.kt
|
1
|
1276
|
package org.intellij.plugins.markdown.model
import com.intellij.testFramework.fixtures.BasePlatformTestCase
import org.intellij.plugins.markdown.MarkdownTestingUtil
import org.intellij.plugins.markdown.model.psi.headers.UnresolvedHeaderReferenceInspection
class UnresolvedHeaderReferenceInspectionTest: BasePlatformTestCase() {
fun `test header in single file is unresolved`() = doTest()
fun `test header in single file is resolved`() = doTest()
fun `test headers in project are resolved`() = doTest()
fun `test headers in project are resolved without file extensions`() = doTest()
fun `test headers in project are unresolved`() = doTest()
override fun setUp() {
super.setUp()
myFixture.copyDirectoryToProject("", "")
}
private fun doTest() {
val name = getTestName(true)
myFixture.enableInspections(UnresolvedHeaderReferenceInspection())
myFixture.configureByFile("$name.md")
myFixture.testHighlighting(true, false, true)
}
override fun getTestName(lowercaseFirstLetter: Boolean): String {
val name = super.getTestName(lowercaseFirstLetter)
return name.trimStart().replace(' ', '_')
}
override fun getTestDataPath(): String {
return "${MarkdownTestingUtil.TEST_DATA_PATH}/model/headers/inspection/"
}
}
|
apache-2.0
|
33b1bc01d3d40c6a762e239274ace4cb
| 32.578947 | 90 | 0.751567 | 4.888889 | false | true | false | false |
JStege1206/AdventOfCode
|
aoc-2016/src/main/kotlin/nl/jstege/adventofcode/aoc2016/days/Day03.kt
|
1
|
1027
|
package nl.jstege.adventofcode.aoc2016.days
import nl.jstege.adventofcode.aoccommon.days.Day
import nl.jstege.adventofcode.aoccommon.utils.extensions.transpose
/**
*
* @author Jelle Stege
*/
class Day03 : Day(title = "Squares With Three Sides") {
private companion object Configuration {
private const val WHITESPACE_PATTERN_STRING = """\s+"""
private val WHITESPACE_REGEX = WHITESPACE_PATTERN_STRING.toRegex()
}
override fun first(input: Sequence<String>): Any = input
.map { it.trim().split(WHITESPACE_REGEX).map(String::toInt) }
.filter { (x, y, z) -> isValid(x, y, z) }
.toList()
.size
override fun second(input: Sequence<String>): Any = input
.map { it.trim().split(WHITESPACE_REGEX).map(String::toInt) }
.toList()
.transpose()
.flatten()
.chunked(3)
.filter { (x, y, z) -> isValid(x, y, z) }
.size
private fun isValid(x: Int, y: Int, z: Int) = (x + y > z) && (x + z > y) && (y + z > x)
}
|
mit
|
c4a953a2b3bac477c32440cf6a3ae8a4
| 30.121212 | 91 | 0.599805 | 3.541379 | false | false | false | false |
jmsloat/dailyprogrammer
|
165_Forest_Hard/src/Inhabitant.kt
|
1
|
569
|
package com.sloat.dailyprogrammer
public abstract class Inhabitant() {
abstract val type : String
abstract val repr : Char
}
public class Lumberjack : Inhabitant() {
public override val type: String =
"Lumberjack"
override val repr = 'L'
}
public class Tree : Inhabitant() {
override val type = "Tree"
override val repr = 't'
}
public class EmptySpace : Inhabitant() {
override val type = "Nothing"
override val repr = '.'
}
public class Bear : Inhabitant() {
override val type = "Bear"
override val repr = 'B'
}
|
mit
|
6ff3360d354d476b20568ddc525ea944
| 20.111111 | 40 | 0.652021 | 3.793333 | false | false | false | false |
RadiationX/ForPDA
|
app/src/main/java/forpdateam/ru/forpda/presentation/search/SearchTemplate.kt
|
1
|
4702
|
package forpdateam.ru.forpda.presentation.search
import forpdateam.ru.forpda.entity.remote.search.SearchResult
import forpdateam.ru.forpda.model.AuthHolder
import forpdateam.ru.forpda.model.data.remote.api.ApiUtils
import forpdateam.ru.forpda.model.preferences.TopicPreferencesHolder
import forpdateam.ru.forpda.model.repository.temp.TempHelper
import forpdateam.ru.forpda.ui.TemplateManager
import java.util.regex.Matcher
import java.util.regex.Pattern
class SearchTemplate(
private val templateManager: TemplateManager,
private val authHolder: AuthHolder,
private val topicPreferencesHolder: TopicPreferencesHolder
) {
private val firstLetter = Pattern.compile("([a-zA-Zа-яА-Я])")
fun mapEntity(page: SearchResult): SearchResult = page.apply { html = mapString(page) }
private fun mapString(page: SearchResult): String {
val template = templateManager.getTemplate(TemplateManager.TEMPLATE_SEARCH)
val authData = authHolder.get()
template.apply {
templateManager.fillStaticStrings(template)
val prevDisabled = page.pagination.current <= 1
val nextDisabled = page.pagination.current == page.pagination.all
setVariableOpt("style_type", templateManager.getThemeType())
setVariableOpt("all_pages_int", page.pagination.all)
setVariableOpt("posts_on_page_int", page.pagination.perPage)
setVariableOpt("current_page_int", page.pagination.current)
setVariableOpt("authorized_bool", java.lang.Boolean.toString(authData.isAuth()))
setVariableOpt("member_id_int", authData.userId)
setVariableOpt("body_type", "search")
setVariableOpt("navigation_disable", TempHelper.getDisableStr(prevDisabled && nextDisabled))
setVariableOpt("first_disable", TempHelper.getDisableStr(prevDisabled))
setVariableOpt("prev_disable", TempHelper.getDisableStr(prevDisabled))
setVariableOpt("next_disable", TempHelper.getDisableStr(nextDisabled))
setVariableOpt("last_disable", TempHelper.getDisableStr(nextDisabled))
val isEnableAvatars = topicPreferencesHolder.getShowAvatars()
setVariableOpt("enable_avatars_bool", java.lang.Boolean.toString(isEnableAvatars))
setVariableOpt("enable_avatars", if (isEnableAvatars) "show_avatar" else "hide_avatar")
setVariableOpt("avatar_type", if (topicPreferencesHolder.getCircleAvatars()) "circle_avatar" else "square_avatar")
var letterMatcher: Matcher? = null
for (post in page.items) {
setVariableOpt("topic_id", post.topicId)
setVariableOpt("post_title", post.title)
setVariableOpt("user_online", if (post.isOnline) "online" else "")
setVariableOpt("post_id", post.id)
setVariableOpt("user_id", post.userId)
//Post header
setVariableOpt("avatar", post.avatar)
setVariableOpt("none_avatar", if (post.avatar.isNullOrEmpty()) "none_avatar" else "")
letterMatcher = letterMatcher?.reset(post.nick) ?: firstLetter.matcher(post.nick)
val letter: String = letterMatcher?.run {
if (find()) group(1) else null
} ?: post.nick?.substring(0, 1).orEmpty()
setVariableOpt("nick_letter", letter)
setVariableOpt("nick", ApiUtils.htmlEncode(post.nick))
//t.setVariableOpt("curator", false ? "curator" : "");
setVariableOpt("group_color", post.groupColor)
setVariableOpt("group", post.group)
setVariableOpt("reputation", post.reputation)
setVariableOpt("date", post.date)
//t.setVariableOpt("number", post.getNumber());
//Post body
setVariableOpt("body", post.body)
//Post footer
/*if (post.canReport() && authorized)
t.addBlockOpt("report_block");
if (page.canQuote() && authorized && post.getUserId() != memberId)
t.addBlockOpt("reply_block");
if (authorized && post.getUserId() != memberId)
t.addBlockOpt("vote_block");
if (post.canDelete() && authorized)
t.addBlockOpt("delete_block");
if (post.canEdit() && authorized)
t.addBlockOpt("edit_block");*/
addBlockOpt("post")
}
}
val result = template.generateOutput()
template.reset()
return result
}
}
|
gpl-3.0
|
4bae0fa6fb648960d74ccd34d868aedf
| 43.330189 | 126 | 0.627927 | 4.929696 | false | false | false | false |
profan/mal
|
kotlin/src/mal/step4_if_fn_do.kt
|
1
|
3471
|
package mal
fun read(input: String?): MalType = read_str(input)
fun eval(ast: MalType, env: Env): MalType =
if (ast is MalList) {
val first = ast.first()
if (first is MalSymbol) {
when (first.value) {
"def!" -> eval_def_BANG(ast, env)
"let*" -> eval_let_STAR(ast, env)
"fn*" -> eval_fn_STAR(ast, env)
"do" -> eval_do(ast, env)
"if" -> eval_if(ast, env)
else -> eval_function_call(ast, env)
}
} else eval_function_call(ast, env)
} else eval_ast(ast, env)
private fun eval_def_BANG(ast: ISeq, env: Env): MalType =
env.set(ast.nth(1) as MalSymbol, eval(ast.nth(2), env))
private fun eval_let_STAR(ast: ISeq, env: Env): MalType {
val child = Env(env)
val bindings = ast.nth(1) as? ISeq ?: throw MalException("expected sequence as the first parameter to let*")
val it = bindings.seq().iterator()
while (it.hasNext()) {
val key = it.next()
if (!it.hasNext()) throw MalException("odd number of binding elements in let*")
val value = eval(it.next(), child)
child.set(key as MalSymbol, value)
}
return eval(ast.nth(2), child)
}
private fun eval_fn_STAR(ast: ISeq, env: Env): MalType {
val binds = ast.nth(1) as? ISeq ?: throw MalException("fn* requires a binding list as first parameter")
val symbols = binds.seq().filterIsInstance<MalSymbol>()
val body = ast.nth(2)
return MalFunction({ s: ISeq ->
eval(body, Env(env, symbols, s.seq()))
})
}
private fun eval_do(ast: ISeq, env: Env): MalType =
(eval_ast(MalList(ast.rest()), env) as ISeq).seq().last()
private fun eval_if(ast: ISeq, env: Env): MalType {
val check = eval(ast.nth(1), env)
return if (check != NIL && check != FALSE) {
eval(ast.nth(2), env)
} else if (ast.seq().asSequence().count() > 3) {
eval(ast.nth(3), env)
} else NIL
}
private fun eval_function_call(ast: ISeq, env: Env): MalType {
val evaluated = eval_ast(ast, env) as ISeq
val first = evaluated.first() as? MalFunction ?: throw MalException("cannot execute non-function")
return first.apply(evaluated.rest())
}
fun eval_ast(ast: MalType, env: Env): MalType =
if (ast is MalSymbol) {
env.get(ast)
} else if (ast is MalList) {
ast.elements.fold(MalList(), { a, b -> a.conj_BANG(eval(b, env)); a })
} else if (ast is MalVector) {
ast.elements.fold(MalVector(), { a, b -> a.conj_BANG(eval(b, env)); a })
} else if (ast is MalHashMap) {
ast.elements.entries.fold(MalHashMap(), { a, b -> a.assoc_BANG(b.key, eval(b.value, env)); a })
} else ast
fun print(result: MalType) = pr_str(result, print_readably = true)
fun rep(input: String, env: Env): String =
print(eval(read(input), env))
fun main(args: Array<String>) {
val repl_env = Env()
ns.forEach({ it -> repl_env.set(it.key, it.value) })
rep("(def! not (fn* (a) (if a false true)))", repl_env)
while (true) {
val input = readline("user> ")
try {
println(rep(input, repl_env))
} catch (e: EofException) {
break
} catch (e: MalContinue) {
} catch (e: MalException) {
println("Error: " + e.message)
} catch (t: Throwable) {
println("Uncaught " + t + ": " + t.message)
t.printStackTrace()
}
}
}
|
mpl-2.0
|
5ee4e18cdc9b3f2b0123149d179a75a6
| 32.057143 | 112 | 0.567272 | 3.347155 | false | false | false | false |
AberrantFox/hotbot
|
src/main/kotlin/me/aberrantfox/hotbot/commandframework/commands/administration/SecurityCommands.kt
|
1
|
1677
|
package me.aberrantfox.hotbot.commandframework.commands.administration
import me.aberrantfox.hotbot.commandframework.parsing.ArgumentType
import me.aberrantfox.hotbot.dsls.command.CommandSet
import me.aberrantfox.hotbot.dsls.command.commands
import me.aberrantfox.hotbot.listeners.antispam.NewPlayers
enum class SecurityLevel(val matchCount: Int, val waitPeriod: Int, val maxAmount: Int) {
Normal(6, 10, 5), Elevated(6, 5, 5), High(4, 5, 4), Max(3, 3, 3)
}
fun names() = SecurityLevel.values().map { it.name }
object SecurityLevelState {
var alertLevel: SecurityLevel = SecurityLevel.Normal
}
@CommandSet
fun securityCommands() = commands {
command("setSecuritylevel") {
expect(ArgumentType.Word)
execute {
val targetLevel = (it.args[0] as String).capitalize()
try {
val parsed = SecurityLevel.valueOf(targetLevel)
SecurityLevelState.alertLevel = parsed
it.respond("Level set to ${parsed.name}")
} catch (e: IllegalArgumentException) {
it.respond("SecurityLevel: $targetLevel is unknown, known levels are: ${names()}")
}
}
}
command("securitylevel") {
execute {
it.respond("Current security level: ${SecurityLevelState.alertLevel}")
}
}
command("viewnewplayers") {
execute {
it.respond("Current tracked new players: ${NewPlayers.names(it.jda)}")
}
}
command("resetsecuritylevel") {
execute {
SecurityLevelState.alertLevel = SecurityLevel.Normal
it.respond("Security level set to normal.")
}
}
}
|
mit
|
b0744ccf5b9bab94ca1976c8107c5495
| 30.055556 | 98 | 0.641622 | 4.367188 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/idea/tests/testData/refactoring/pullUp/k2k/propertyDependenceUnsatisfied.kt
|
13
|
353
|
open class A
class <caret>B: A {
// INFO: {"checked": "true"}
val n: Int
// INFO: {"checked": "true"}
val x: Int = 3
// INFO: {"checked": "false"}
val y: Int = 4
// INFO: {"checked": "true"}
val a: Int = 1
// INFO: {"checked": "true"}
val b: Int = x + y
constructor(p: Int) {
n = a + b - p
}
}
|
apache-2.0
|
fac351fa521e1d242b448d0eb9b867ad
| 16.7 | 33 | 0.444759 | 2.991525 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/refactoring/fqName/fqNameUtil.kt
|
6
|
1342
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.refactoring.fqName
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.base.psi.kotlinFqName
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.ImportPath
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.types.AbbreviatedType
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.idea.base.utils.fqname.isImported as _isImported
val KotlinType.fqName: FqName?
get() = when (this) {
is AbbreviatedType -> abbreviation.fqName
else -> constructor.declarationDescriptor?.fqNameOrNull()
}
@Deprecated(
"Replace with 'org.jetbrains.kotlin.idea.base.psi.kotlinFqName'",
replaceWith = ReplaceWith("kotlinFqName", "org.jetbrains.kotlin.idea.base.psi.kotlinFqName"),
)
fun PsiElement.getKotlinFqName(): FqName? = this.kotlinFqName
@Deprecated(
"For binary compatibility",
replaceWith = ReplaceWith("this.isImported(importPath, skipAliasedImports)", "org.jetbrains.kotlin.idea.base.utils.fqname.isImported"),
)
fun FqName.isImported(importPath: ImportPath, skipAliasedImports: Boolean = true): Boolean =
_isImported(importPath, skipAliasedImports)
|
apache-2.0
|
8e59a2f03d60858eeeb8d510798c9e85
| 43.766667 | 139 | 0.788376 | 4.180685 | false | false | false | false |
GunoH/intellij-community
|
platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/service/project/manage/ExternalProjectsDataStorageTest.kt
|
7
|
3507
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.externalSystem.service.project.manage
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.Key
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.externalSystem.model.internal.InternalExternalProjectInfo
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.util.io.FileUtil
import com.intellij.testFramework.UsefulTestCase
import com.intellij.testFramework.fixtures.IdeaProjectTestFixture
import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory
import kotlinx.coroutines.runBlocking
import org.assertj.core.api.BDDAssertions.then
import org.junit.Test
import kotlin.reflect.jvm.jvmName
class ExternalProjectsDataStorageTest: UsefulTestCase() {
lateinit var myFixture: IdeaProjectTestFixture
override fun setUp() {
super.setUp()
myFixture = IdeaTestFixtureFactory.getFixtureFactory().createFixtureBuilder(name).fixture
myFixture.setUp()
}
override fun tearDown() {
try {
myFixture.tearDown()
}
catch (e: Throwable) {
addSuppressedException(e)
}
finally {
super.tearDown()
}
}
@Test
fun `test external project data is saved and loaded`() = runBlocking<Unit> {
val dataStorage = ExternalProjectsDataStorage(myFixture.project)
val testSystemId = ProjectSystemId("Test")
val externalName = "external_name"
val externalProjectInfo = createExternalProjectInfo(
testSystemId, externalName, FileUtil.toSystemIndependentName(createTempDir(suffix = externalName).canonicalPath))
dataStorage.update(externalProjectInfo)
dataStorage.save()
dataStorage.load()
val list = dataStorage.list(testSystemId)
then(list).hasSize(1)
then(list.iterator().next().externalProjectStructure?.data?.externalName).isEqualTo(externalName)
}
@Test
fun `test external project data updated before storage initialization is not lost`() = runBlocking<Unit> {
val dataStorage = ExternalProjectsDataStorage(myFixture.project)
val testSystemId = ProjectSystemId("Test")
val externalName1 = "external_name1"
dataStorage.update(createExternalProjectInfo(
testSystemId, externalName1, FileUtil.toSystemIndependentName(createTempDir(suffix = externalName1).canonicalPath)))
dataStorage.load()
val externalName2 = "external_name2"
dataStorage.update(createExternalProjectInfo(
testSystemId, externalName2, FileUtil.toSystemIndependentName(createTempDir(suffix = externalName2).canonicalPath)))
val list = dataStorage.list(testSystemId)
then(list).hasSize(2)
val thenList = then(list)
thenList.anyMatch { it.externalProjectStructure?.data?.externalName == externalName1 }
thenList.anyMatch { it.externalProjectStructure?.data?.externalName == externalName2 }
}
private fun createExternalProjectInfo(testId: ProjectSystemId,
externalName: String,
externalProjectPath: String): InternalExternalProjectInfo {
val projectData = ProjectData(testId, externalName, externalProjectPath, externalProjectPath)
val node = DataNode<ProjectData>(Key(ProjectData::class.jvmName, 0), projectData, null)
return InternalExternalProjectInfo(testId, externalProjectPath, node)
}
}
|
apache-2.0
|
fe6d9dcaedf0a19cf153bc34e71ac72e
| 40.270588 | 122 | 0.765612 | 5.104803 | false | true | false | false |
AsamK/TextSecure
|
app/src/main/java/org/thoughtcrime/securesms/components/settings/models/AsyncSwitch.kt
|
2
|
2080
|
package org.thoughtcrime.securesms.components.settings.models
import android.view.View
import android.widget.ViewSwitcher
import com.google.android.material.switchmaterial.SwitchMaterial
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.settings.DSLSettingsText
import org.thoughtcrime.securesms.components.settings.PreferenceModel
import org.thoughtcrime.securesms.components.settings.PreferenceViewHolder
import org.thoughtcrime.securesms.util.adapter.mapping.LayoutFactory
import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter
/**
* Switch that will perform a long-running async operation (normally network) that requires a
* progress spinner to replace the switch after a press.
*/
object AsyncSwitch {
fun register(adapter: MappingAdapter) {
adapter.registerFactory(Model::class.java, LayoutFactory(AsyncSwitch::ViewHolder, R.layout.dsl_async_switch_preference_item))
}
class Model(
override val title: DSLSettingsText,
override val isEnabled: Boolean,
val isChecked: Boolean,
val isProcessing: Boolean,
val onClick: () -> Unit
) : PreferenceModel<Model>() {
override fun areContentsTheSame(newItem: Model): Boolean {
return super.areContentsTheSame(newItem) && isChecked == newItem.isChecked && isProcessing == newItem.isProcessing
}
}
class ViewHolder(itemView: View) : PreferenceViewHolder<Model>(itemView) {
private val switchWidget: SwitchMaterial = itemView.findViewById(R.id.switch_widget)
private val switcher: ViewSwitcher = itemView.findViewById(R.id.switcher)
override fun bind(model: Model) {
super.bind(model)
switchWidget.isEnabled = model.isEnabled
switchWidget.isChecked = model.isChecked
itemView.isEnabled = !model.isProcessing && model.isEnabled
switcher.displayedChild = if (model.isProcessing) 1 else 0
itemView.setOnClickListener {
if (!model.isProcessing) {
itemView.isEnabled = false
switcher.displayedChild = 1
model.onClick()
}
}
}
}
}
|
gpl-3.0
|
de7cf6277cde0ee13c1a9d654407b003
| 36.818182 | 129 | 0.753365 | 4.759725 | false | false | false | false |
ktorio/ktor
|
ktor-server/ktor-server-plugins/ktor-server-sessions/jvm/src/io/ktor/server/sessions/DirectoryStorage.kt
|
1
|
2763
|
/*
* Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.sessions
import java.io.*
/**
* Creates a storage that serializes a session's data to a file under the [rootDir] directory.
*
* @see [Sessions]
*/
public fun directorySessionStorage(rootDir: File, cached: Boolean = true): SessionStorage = when (cached) {
true -> CacheStorage(DirectoryStorage(rootDir), 60000)
false -> DirectoryStorage(rootDir)
}
internal class DirectoryStorage(private val dir: File) : SessionStorage, Closeable {
init {
dir.mkdirsOrFail()
}
override fun close() {
}
override suspend fun write(id: String, value: String) {
requireId(id)
val file = fileOf(id)
file.parentFile?.mkdirsOrFail()
file.writeText(value)
}
override suspend fun read(id: String): String {
requireId(id)
try {
val file = fileOf(id)
file.parentFile?.mkdirsOrFail()
return file.readText().takeIf { it.isNotEmpty() }
?: throw IllegalStateException("Failed to read stored session from $file")
} catch (notFound: FileNotFoundException) {
throw NoSuchElementException("No session data found for id $id")
}
}
override suspend fun invalidate(id: String) {
requireId(id)
try {
val file = fileOf(id)
file.delete()
file.parentFile?.deleteParentsWhileEmpty(dir)
} catch (notFound: FileNotFoundException) {
throw NoSuchElementException("No session data found for id $id")
}
}
private fun fileOf(id: String) = File(dir, split(id).joinToString(File.separator, postfix = ".dat"))
private fun split(id: String) = id.windowedSequence(size = 2, step = 2, partialWindows = true)
private fun requireId(id: String) {
if (id.isEmpty()) {
throw IllegalArgumentException("Session id is empty")
}
if (id.indexOfAny(listOf("..", "/", "\\", "!", "?", ">", "<", "\u0000")) != -1) {
throw IllegalArgumentException("Bad session id $id")
}
}
}
private fun File.mkdirsOrFail() {
if (!this.mkdirs() && !this.exists()) {
throw IOException("Couldn't create directory $this")
}
if (!this.isDirectory) {
throw IOException("Path is not a directory: $this")
}
}
private tailrec fun File.deleteParentsWhileEmpty(mostTop: File) {
if (this != mostTop && isDirectory && exists() && list().isNullOrEmpty()) {
if (!delete() && exists()) {
throw IOException("Failed to delete dir $this")
}
parentFile.deleteParentsWhileEmpty(mostTop)
}
}
|
apache-2.0
|
d8bef462062355d9487b80fa07823a32
| 30.044944 | 119 | 0.613102 | 4.263889 | false | false | false | false |
google/accompanist
|
systemuicontroller/src/sharedTest/kotlin/com/google/accompanist/systemuicontroller/DialogRememberSystemUiControllerTest.kt
|
1
|
17478
|
/*
* 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.accompanist.systemuicontroller
import android.os.Build
import android.view.View
import android.view.Window
import androidx.activity.ComponentActivity
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogWindowProvider
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.FlakyTest
import androidx.test.filters.SdkSuppress
import com.google.accompanist.internal.test.IgnoreOnRobolectric
import com.google.accompanist.internal.test.waitUntil
import com.google.accompanist.internal.test.withActivity
import com.google.accompanist.systemuicontroller.test.R
import com.google.common.truth.Truth.assertThat
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.experimental.categories.Category
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class DialogRememberSystemUiControllerTest {
@get:Rule
val rule = createAndroidComposeRule<ComponentActivity>()
private lateinit var window: Window
private lateinit var contentView: View
@Before
fun setup() {
rule.activityRule.scenario.onActivity {
it.setTheme(R.style.DialogSystemUiControllerTheme)
}
}
@Test
fun statusBarColor() {
rule.setContent {
Dialog(onDismissRequest = {}) {
window = (LocalView.current.parent as DialogWindowProvider).window
// Create an systemUiController and set the status bar color
val systemUiController = rememberSystemUiController()
SideEffect {
systemUiController.setStatusBarColor(Color.Blue, darkIcons = false)
}
}
}
// Assert that the color was set
assertThat(Color(window.statusBarColor)).isEqualTo(Color.Blue)
}
@Test
fun navigationBarColor() {
rule.setContent {
Dialog(onDismissRequest = {}) {
window = (LocalView.current.parent as DialogWindowProvider).window
// Now create an systemUiController and set the navigation bar color
val systemUiController = rememberSystemUiController()
SideEffect {
systemUiController.setNavigationBarColor(Color.Green, darkIcons = false)
}
}
}
assertThat(Color(window.navigationBarColor)).isEqualTo(Color.Green)
}
@Test
fun systemBarColor() {
rule.setContent {
Dialog(onDismissRequest = {}) {
window = (LocalView.current.parent as DialogWindowProvider).window
// Now create an systemUiController and set the system bar colors
val systemUiController = rememberSystemUiController()
SideEffect {
systemUiController.setSystemBarsColor(Color.Red, darkIcons = false)
}
}
}
// Assert that the colors were set
assertThat(Color(window.statusBarColor)).isEqualTo(Color.Red)
assertThat(Color(window.navigationBarColor)).isEqualTo(Color.Red)
}
@Test
@Category(IgnoreOnRobolectric::class) // Robolectric implements the new behavior from 23+
@SdkSuppress(maxSdkVersion = 22)
fun statusBarIcons_scrim() {
// Now create an systemUiController and set the navigation bar with dark icons
rule.setContent {
Dialog(onDismissRequest = {}) {
window = (LocalView.current.parent as DialogWindowProvider).window
contentView = LocalView.current
val systemUiController = rememberSystemUiController()
SideEffect {
systemUiController.setStatusBarColor(Color.White, darkIcons = true) {
// Here we can provide custom logic to 'darken' the color to maintain contrast.
// We return red just to assert below.
Color.Red
}
}
}
}
// Assert that the colors were set to our 'darkened' color
assertThat(Color(window.statusBarColor)).isEqualTo(Color.Red)
// Assert that the system couldn't apply the native light icons
rule.activityRule.scenario.onActivity {
val windowInsetsController = WindowCompat.getInsetsController(window, contentView)
assertThat(windowInsetsController.isAppearanceLightStatusBars).isFalse()
}
}
@Test
@Category(IgnoreOnRobolectric::class)
@SdkSuppress(minSdkVersion = 23)
fun statusBarIcons_native() {
// Now create an systemUiController and set the status bar with dark icons
rule.setContent {
Dialog(onDismissRequest = {}) {
window = (LocalView.current.parent as DialogWindowProvider).window
contentView = LocalView.current
val systemUiController = rememberSystemUiController()
SideEffect {
systemUiController.setStatusBarColor(Color.White, darkIcons = true) {
// Here we can provide custom logic to 'darken' the color to maintain contrast.
// We return red just to assert below.
Color.Red
}
}
}
}
// Assert that the colors were darkened color is not used
assertThat(Color(window.statusBarColor)).isEqualTo(Color.White)
// Assert that the system applied the native light icons
rule.activityRule.scenario.onActivity {
val windowInsetsController = WindowCompat.getInsetsController(window, contentView)
assertThat(windowInsetsController.isAppearanceLightStatusBars).isTrue()
}
}
@Test
@Category(IgnoreOnRobolectric::class) // Robolectric implements the new behavior from 25+
@SdkSuppress(maxSdkVersion = 25)
fun navigationBarIcons_scrim() {
// Now create an systemUiController and set the navigation bar with dark icons
rule.setContent {
Dialog(onDismissRequest = {}) {
window = (LocalView.current.parent as DialogWindowProvider).window
contentView = LocalView.current
val systemUiController = rememberSystemUiController()
SideEffect {
systemUiController.setNavigationBarColor(Color.White, darkIcons = true) {
// Here we can provide custom logic to 'darken' the color to maintain contrast.
// We return red just to assert below.
Color.Red
}
}
}
}
// Assert that the colors were set to our 'darkened' color
assertThat(Color(window.navigationBarColor)).isEqualTo(Color.Red)
// Assert that the system couldn't apply the native light icons
rule.activityRule.scenario.onActivity {
val windowInsetsController = WindowCompat.getInsetsController(window, contentView)
assertThat(windowInsetsController.isAppearanceLightNavigationBars).isFalse()
}
}
@Test
@Category(IgnoreOnRobolectric::class)
@SdkSuppress(minSdkVersion = 26)
fun navigationBar_native() {
// Now create an systemUiController and set the navigation bar with dark icons
rule.setContent {
Dialog(onDismissRequest = {}) {
window = (LocalView.current.parent as DialogWindowProvider).window
contentView = LocalView.current
val systemUiController = rememberSystemUiController()
SideEffect {
systemUiController.setNavigationBarColor(Color.White, darkIcons = true) {
// Here we can provide custom logic to 'darken' the color to maintain contrast.
// We return red just to assert below.
Color.Red
}
}
}
}
// Assert that the colors were darkened color is not used
assertThat(Color(window.navigationBarColor)).isEqualTo(Color.White)
// Assert that the system applied the native light icons
rule.activityRule.scenario.onActivity {
val windowInsetsController = WindowCompat.getInsetsController(window, contentView)
assertThat(windowInsetsController.isAppearanceLightNavigationBars).isTrue()
}
}
@Test
@SdkSuppress(minSdkVersion = 29)
fun navigationBar_contrastEnforced() {
lateinit var systemUiController: SystemUiController
rule.setContent {
Dialog(onDismissRequest = {}) {
window = (LocalView.current.parent as DialogWindowProvider).window
systemUiController = rememberSystemUiController()
}
}
if (Build.VERSION.SDK_INT >= 29) {
// On API 29+, the system can modify the bar colors to maintain contrast.
// We disable that here to make it simple to assert expected values
rule.activityRule.scenario.onActivity {
window.apply {
isNavigationBarContrastEnforced = false
isStatusBarContrastEnforced = false
}
}
}
rule.activityRule.scenario.onActivity {
// Assert that the contrast is not enforced initially
assertThat(systemUiController.isNavigationBarContrastEnforced).isFalse()
// and set the navigation bar with dark icons and enforce contrast
systemUiController.setNavigationBarColor(
Color.Transparent,
darkIcons = true,
navigationBarContrastEnforced = true
) {
// Here we can provide custom logic to 'darken' the color to maintain contrast.
// We return red just to assert below.
Color.Red
}
// Assert that the colors were darkened color is not used
assertThat(Color(window.navigationBarColor)).isEqualTo(Color.Transparent)
// Assert that the system applied the contrast enforced property
assertThat(window.isNavigationBarContrastEnforced).isTrue()
// Assert that the controller reflects that the contrast is enforced
assertThat(systemUiController.isNavigationBarContrastEnforced).isTrue()
}
}
@Test
@SdkSuppress(minSdkVersion = 30) // TODO: https://issuetracker.google.com/issues/189366125
fun systemBarsBehavior_showBarsByTouch() {
lateinit var systemUiController: SystemUiController
rule.setContent {
Dialog(onDismissRequest = {}) {
window = (LocalView.current.parent as DialogWindowProvider).window
contentView = LocalView.current
systemUiController = rememberSystemUiController()
}
}
rule.activityRule.scenario.onActivity {
systemUiController.systemBarsBehavior =
WindowInsetsControllerCompat.BEHAVIOR_SHOW_BARS_BY_TOUCH
}
assertThat(WindowCompat.getInsetsController(window, contentView).systemBarsBehavior)
.isEqualTo(WindowInsetsControllerCompat.BEHAVIOR_SHOW_BARS_BY_TOUCH)
}
@Test
@SdkSuppress(minSdkVersion = 30) // TODO: https://issuetracker.google.com/issues/189366125
fun systemBarsBehavior_showBarsBySwipe() {
lateinit var systemUiController: SystemUiController
rule.setContent {
Dialog(onDismissRequest = {}) {
window = (LocalView.current.parent as DialogWindowProvider).window
contentView = LocalView.current
systemUiController = rememberSystemUiController()
}
}
rule.activityRule.scenario.onActivity {
systemUiController.systemBarsBehavior =
WindowInsetsControllerCompat.BEHAVIOR_SHOW_BARS_BY_SWIPE
}
assertThat(WindowCompat.getInsetsController(window, contentView).systemBarsBehavior)
.isEqualTo(WindowInsetsControllerCompat.BEHAVIOR_SHOW_BARS_BY_SWIPE)
}
@Test
@SdkSuppress(minSdkVersion = 30) // TODO: https://issuetracker.google.com/issues/189366125
fun systemBarsBehavior_showTransientBarsBySwipe() {
lateinit var systemUiController: SystemUiController
rule.setContent {
Dialog(onDismissRequest = {}) {
window = (LocalView.current.parent as DialogWindowProvider).window
contentView = LocalView.current
systemUiController = rememberSystemUiController()
}
}
rule.activityRule.scenario.onActivity {
systemUiController.systemBarsBehavior =
WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
}
assertThat(WindowCompat.getInsetsController(window, contentView).systemBarsBehavior)
.isEqualTo(WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE)
}
@Test
@FlakyTest(detail = "https://github.com/google/accompanist/issues/491")
@SdkSuppress(minSdkVersion = 23) // rootWindowInsets which work
@Category(IgnoreOnRobolectric::class)
fun statusBarsVisibility() {
lateinit var systemUiController: SystemUiController
rule.setContent {
Dialog(onDismissRequest = {}) {
contentView = LocalView.current
systemUiController = rememberSystemUiController()
}
}
// First show the bars
rule.activityRule.scenario.onActivity {
systemUiController.isStatusBarVisible = true
}
waitUntil { isRootWindowTypeVisible(WindowInsetsCompat.Type.statusBars()) }
// Now hide the bars
rule.activityRule.scenario.onActivity {
systemUiController.isStatusBarVisible = false
}
waitUntil { !isRootWindowTypeVisible(WindowInsetsCompat.Type.statusBars()) }
}
@Test
@FlakyTest(detail = "https://github.com/google/accompanist/issues/491")
@SdkSuppress(minSdkVersion = 23) // rootWindowInsets which work
@Category(IgnoreOnRobolectric::class)
fun navigationBarsVisibility() {
lateinit var systemUiController: SystemUiController
rule.setContent {
Dialog(onDismissRequest = {}) {
contentView = LocalView.current
systemUiController = rememberSystemUiController()
}
}
// First show the bars
rule.activityRule.scenario.onActivity {
systemUiController.isNavigationBarVisible = true
}
waitUntil { isRootWindowTypeVisible(WindowInsetsCompat.Type.navigationBars()) }
// Now hide the bars
rule.activityRule.scenario.onActivity {
systemUiController.isNavigationBarVisible = false
}
waitUntil { !isRootWindowTypeVisible(WindowInsetsCompat.Type.navigationBars()) }
}
@Test
@Category(IgnoreOnRobolectric::class)
@FlakyTest(detail = "https://github.com/google/accompanist/issues/491")
@SdkSuppress(minSdkVersion = 23) // rootWindowInsets which work
fun systemBarsVisibility() {
lateinit var systemUiController: SystemUiController
rule.setContent {
Dialog(onDismissRequest = {}) {
contentView = LocalView.current
systemUiController = rememberSystemUiController()
}
}
// First show the bars
rule.activityRule.scenario.onActivity {
systemUiController.isSystemBarsVisible = true
}
waitUntil { isRootWindowTypeVisible(WindowInsetsCompat.Type.navigationBars()) }
waitUntil { isRootWindowTypeVisible(WindowInsetsCompat.Type.statusBars()) }
// Now hide the bars
rule.activityRule.scenario.onActivity {
systemUiController.isSystemBarsVisible = false
}
waitUntil { !isRootWindowTypeVisible(WindowInsetsCompat.Type.navigationBars()) }
waitUntil { !isRootWindowTypeVisible(WindowInsetsCompat.Type.statusBars()) }
}
private fun isRootWindowTypeVisible(type: Int): Boolean {
return rule.activityRule.scenario.withActivity {
ViewCompat.getRootWindowInsets(contentView)!!.isVisible(type)
}
}
}
|
apache-2.0
|
dc1d00aae5ae8f202412020b76455ebf
| 37.84 | 103 | 0.649388 | 5.880888 | false | true | false | false |
marklemay/IntelliJATS
|
src/main/kotlin/com/atslangplugin/annotators/AtsAnnotatorProjectSettings.kt
|
1
|
666
|
package com.atslangplugin.annotators
//TODO: rename to astproject settings?
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.StoragePathMacros
@State(name = "ATS.Settings", storages = arrayOf(Storage(StoragePathMacros.WORKSPACE_FILE)))
class AtsAnnotatorProjectSettings : PersistentStateComponent<AtsAnnotatorSettings> {
var settings: AtsAnnotatorSettings? = AtsAnnotatorSettings()
override fun getState() = settings
override fun loadState(state: AtsAnnotatorSettings?) {
settings = state
}
}
|
gpl-3.0
|
e98c6e7b83938aa14f58f120cb23fef5
| 36.055556 | 92 | 0.804805 | 4.791367 | false | false | false | false |
inorichi/mangafeed
|
app/src/main/java/eu/kanade/tachiyomi/util/lang/StringExtensions.kt
|
2
|
1812
|
package eu.kanade.tachiyomi.util.lang
import net.greypanther.natsort.CaseInsensitiveSimpleNaturalComparator
import java.nio.charset.StandardCharsets
import kotlin.math.floor
/**
* Replaces the given string to have at most [count] characters using [replacement] at its end.
* If [replacement] is longer than [count] an exception will be thrown when `length > count`.
*/
fun String.chop(count: Int, replacement: String = "…"): String {
return if (length > count) {
take(count - replacement.length) + replacement
} else {
this
}
}
/**
* Replaces the given string to have at most [count] characters using [replacement] near the center.
* If [replacement] is longer than [count] an exception will be thrown when `length > count`.
*/
fun String.truncateCenter(count: Int, replacement: String = "..."): String {
if (length <= count) {
return this
}
val pieceLength: Int = floor((count - replacement.length).div(2.0)).toInt()
return "${take(pieceLength)}$replacement${takeLast(pieceLength)}"
}
/**
* Case-insensitive natural comparator for strings.
*/
fun String.compareToCaseInsensitiveNaturalOrder(other: String): Int {
val comparator = CaseInsensitiveSimpleNaturalComparator.getInstance<String>()
return comparator.compare(this, other)
}
/**
* Returns the size of the string as the number of bytes.
*/
fun String.byteSize(): Int {
return toByteArray(StandardCharsets.UTF_8).size
}
/**
* Returns a string containing the first [n] bytes from this string, or the entire string if this
* string is shorter.
*/
fun String.takeBytes(n: Int): String {
val bytes = toByteArray(StandardCharsets.UTF_8)
return if (bytes.size <= n) {
this
} else {
bytes.decodeToString(endIndex = n).replace("\uFFFD", "")
}
}
|
apache-2.0
|
5d51c67721382ea108cb2447b149e7b8
| 29.677966 | 100 | 0.69558 | 4.03118 | false | false | false | false |
jonathanlermitage/tikione-c2e
|
src/main/kotlin/fr/tikione/c2e/core/cfg/Cfg.kt
|
1
|
404
|
package fr.tikione.c2e.core.cfg
class Cfg {
var doList = false
var doIncludePictures = false
var doIndex = false
var doDarkMode = false
var doHtml = false
var doAllMags = false
var doAllMissing = false
var doHome = false
var doDysfont = false
var doColumn = false
var resize: String? = null
var customCss: String? = null
var directory: String = "."
}
|
mit
|
d5dbde3d4acb4f5bba77a3498cadca97
| 22.764706 | 33 | 0.65099 | 3.63964 | false | false | false | false |
google/android-fhir
|
engine/src/main/java/com/google/android/fhir/search/filter/QuantityParamFilterCriterion.kt
|
1
|
1687
|
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.fhir.search.filter
import ca.uhn.fhir.rest.gclient.QuantityClientParam
import ca.uhn.fhir.rest.param.ParamPrefixEnum
import com.google.android.fhir.search.Operation
import com.google.android.fhir.search.SearchDslMarker
import com.google.android.fhir.search.getConditionParamPair
import java.math.BigDecimal
/**
* Represents a criterion for filtering [QuantityClientParam]. e.g.
* filter(Observation.VALUE_QUANTITY,{value = BigDecimal("5.403")} )
*/
@SearchDslMarker
data class QuantityParamFilterCriterion(
val parameter: QuantityClientParam,
var prefix: ParamPrefixEnum? = null,
var value: BigDecimal? = null,
var system: String? = null,
var unit: String? = null
) : FilterCriterion {
override fun getConditionalParams() = listOf(getConditionParamPair(prefix, value!!, system, unit))
}
internal data class QuantityParamFilterCriteria(
val parameter: QuantityClientParam,
override val filters: List<QuantityParamFilterCriterion>,
override val operation: Operation,
) : FilterCriteria(filters, operation, parameter, "QuantityIndexEntity")
|
apache-2.0
|
c123ca34a4262946cbe319fefd437195
| 35.673913 | 100 | 0.772377 | 4.035885 | false | false | false | false |
Tickaroo/tikxml
|
annotationprocessortesting-kt/src/main/java/com/tickaroo/tikxml/annotationprocessing/attribute/Item.kt
|
1
|
3682
|
/*
* Copyright (C) 2015 Hannes Dorfmann
* Copyright (C) 2015 Tickaroo, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.tickaroo.tikxml.annotationprocessing.attribute
import com.tickaroo.tikxml.annotation.Attribute
import com.tickaroo.tikxml.annotation.Xml
import com.tickaroo.tikxml.annotationprocessing.DateConverter
import java.util.Date
/**
* @author Hannes Dorfmann
*/
@Xml
class Item {
@Attribute
@JvmField
var aString: String? = null
@Attribute
@JvmField
var anInt: Int = 0
@Attribute
@JvmField
var aBoolean: Boolean = false
@Attribute
@JvmField
var aDouble: Double = 0.toDouble()
@Attribute
@JvmField
var aLong: Long = 0
@Attribute(converter = DateConverter::class)
@JvmField
var aDate: Date? = null
@Attribute
@JvmField
var intWrapper: Int? = null
@Attribute
@JvmField
var booleanWrapper: Boolean? = null
@Attribute
@JvmField
var doubleWrapper: Double? = null
@Attribute
@JvmField
var longWrapper: Long? = null
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Item) return false
val item = other as Item?
if (anInt != item!!.anInt) return false
if (aBoolean != item.aBoolean) return false
if (java.lang.Double.compare(item.aDouble, aDouble) != 0) return false
if (aLong != item.aLong) return false
if (if (aString != null) aString != item.aString else item.aString != null) return false
if (if (aDate != null) aDate != item.aDate else item.aDate != null) return false
if (if (intWrapper != null) intWrapper != item.intWrapper else item.intWrapper != null) {
return false
}
if (if (booleanWrapper != null)
booleanWrapper != item.booleanWrapper
else
item.booleanWrapper != null) {
return false
}
if (if (doubleWrapper != null)
doubleWrapper != item.doubleWrapper
else
item.doubleWrapper != null) {
return false
}
return if (longWrapper != null) longWrapper == item.longWrapper else item.longWrapper == null
}
override fun hashCode(): Int {
var result: Int = if (aString != null) aString!!.hashCode() else 0
val temp: Long = java.lang.Double.doubleToLongBits(aDouble)
result = 31 * result + anInt
result = 31 * result + if (aBoolean) 1 else 0
result = 31 * result + (temp xor temp.ushr(32)).toInt()
result = 31 * result + (aLong xor aLong.ushr(32)).toInt()
result = 31 * result + if (aDate != null) aDate!!.hashCode() else 0
result = 31 * result + if (intWrapper != null) intWrapper!!.hashCode() else 0
result = 31 * result + if (booleanWrapper != null) booleanWrapper!!.hashCode() else 0
result = 31 * result + if (doubleWrapper != null) doubleWrapper!!.hashCode() else 0
result = 31 * result + if (longWrapper != null) longWrapper!!.hashCode() else 0
return result
}
}
|
apache-2.0
|
aa83bc7c99b1c10f314b8f443b98af86
| 31.017391 | 101 | 0.626562 | 4.372922 | false | false | false | false |
dahlstrom-g/intellij-community
|
plugins/kotlin/jvm-debugger/test/testData/stepping/custom/smartStepIntoConstructor.kt
|
9
|
1770
|
package smartStepIntoConstructor
fun main(args: Array<String>) {
// SMART_STEP_INTO_BY_INDEX: 1
// RESUME: 1
//Breakpoint!
B()
// SMART_STEP_INTO_BY_INDEX: 1
// RESUME: 1
//Breakpoint!
C(1)
// SMART_STEP_INTO_BY_INDEX: 1
// RESUME: 1
//Breakpoint!
D()
// SMART_STEP_INTO_BY_INDEX: 1
// RESUME: 1
//Breakpoint!
E(1)
// SMART_STEP_INTO_BY_INDEX: 1
// RESUME: 1
//Breakpoint!
F()
// SMART_STEP_INTO_BY_INDEX: 1
// RESUME: 1
//Breakpoint!
G(1)
// SMART_STEP_INTO_BY_INDEX: 1
// RESUME: 1
//Breakpoint!
J()
// SMART_STEP_INTO_BY_INDEX: 1
// RESUME: 1
//Breakpoint!
K(1)
// SMART_STEP_INTO_BY_INDEX: 1
// RESUME: 1
//Breakpoint!
L()
// SMART_STEP_INTO_BY_INDEX: 1
// RESUME: 1
//Breakpoint!
M()
// SMART_STEP_INTO_BY_INDEX: 1
// RESUME: 1
//Breakpoint!
N(1)
// SMART_STEP_INTO_BY_INDEX: 1
// RESUME: 1
//Breakpoint!
O(1)
// SMART_STEP_INTO_BY_INDEX: 1
// RESUME: 1
//Breakpoint!
O(1, "1")
}
class B()
class C(val a: Int)
class D {
constructor()
}
class E {
constructor(i: Int)
}
class F {
constructor() {
val a = 1
}
}
class G {
constructor(i: Int) {
val a = 1
}
}
class J {
init {
val a = 1
}
}
class K(val i: Int) {
init {
val a = 1
}
}
class L {
constructor() {
val a = 1
}
init {
val a = 1
}
}
class M {
constructor(): this(1) {
val a = 1
}
constructor(i: Int) {
}
}
class N {
constructor(i: Int): this() {
val a = 1
}
constructor() {
}
}
class O<T>(i: T) {
constructor(i: Int, j: T): this(j) {
}
}
|
apache-2.0
|
d29b98f711b125c8c796b381f644efc1
| 14.4 | 40 | 0.483051 | 3 | false | false | false | false |
zeapo/Android-Password-Store
|
app/src/main/java/com/zeapo/pwdstore/git/GitActivity.kt
|
1
|
29018
|
package com.zeapo.pwdstore.git
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Spinner
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatTextView
import androidx.preference.PreferenceManager
import com.google.android.material.button.MaterialButton
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.textfield.TextInputEditText
import com.zeapo.pwdstore.R
import com.zeapo.pwdstore.UserPreference
import com.zeapo.pwdstore.git.config.SshApiSessionFactory
import com.zeapo.pwdstore.utils.PasswordRepository
import org.apache.commons.io.FileUtils
import org.eclipse.jgit.lib.Constants
import java.io.File
import java.io.IOException
import java.util.regex.Pattern
open class GitActivity : AppCompatActivity() {
private lateinit var context: Context
private lateinit var settings: SharedPreferences
private lateinit var protocol: String
private lateinit var connectionMode: String
private lateinit var hostname: String
private var identityBuilder: SshApiSessionFactory.IdentityBuilder? = null
private var identity: SshApiSessionFactory.ApiIdentity? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
context = requireNotNull(this)
settings = PreferenceManager.getDefaultSharedPreferences(this)
protocol = settings.getString("git_remote_protocol", null) ?: "ssh://"
connectionMode = settings.getString("git_remote_auth", null) ?: "ssh-key"
hostname = settings.getString("git_remote_location", null) ?: ""
val operationCode = intent.extras!!.getInt("Operation")
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
when (operationCode) {
REQUEST_CLONE, EDIT_SERVER -> {
setContentView(R.layout.activity_git_clone)
setTitle(R.string.title_activity_git_clone)
val protcolSpinner = findViewById<Spinner>(R.id.clone_protocol)
val connectionModeSpinner = findViewById<Spinner>(R.id.connection_mode)
// init the spinner for connection modes
val connectionModeAdapter = ArrayAdapter.createFromResource(this,
R.array.connection_modes, android.R.layout.simple_spinner_item)
connectionModeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
connectionModeSpinner.adapter = connectionModeAdapter
connectionModeSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(adapterView: AdapterView<*>, view: View, i: Int, l: Long) {
val selection = (findViewById<View>(R.id.connection_mode) as Spinner).selectedItem.toString()
connectionMode = selection
settings.edit().putString("git_remote_auth", selection).apply()
}
override fun onNothingSelected(adapterView: AdapterView<*>) {
}
}
// init the spinner for protocols
val protocolAdapter = ArrayAdapter.createFromResource(this,
R.array.clone_protocols, android.R.layout.simple_spinner_item)
protocolAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
protcolSpinner.adapter = protocolAdapter
protcolSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(adapterView: AdapterView<*>, view: View, i: Int, l: Long) {
protocol = (findViewById<View>(R.id.clone_protocol) as Spinner).selectedItem.toString()
if (protocol == "ssh://") {
// select ssh-key auth mode as default and enable the spinner in case it was disabled
connectionModeSpinner.setSelection(0)
connectionModeSpinner.isEnabled = true
// however, if we have some saved that, that's more important!
when {
connectionMode.equals("ssh-key", ignoreCase = true) -> connectionModeSpinner.setSelection(0)
connectionMode.equals("OpenKeychain", ignoreCase = true) -> connectionModeSpinner.setSelection(2)
else -> connectionModeSpinner.setSelection(1)
}
} else {
// select user/pwd auth-mode and disable the spinner
connectionModeSpinner.setSelection(1)
connectionModeSpinner.isEnabled = false
}
updateURI()
}
override fun onNothingSelected(adapterView: AdapterView<*>) {
}
}
if (protocol == "ssh://") {
protcolSpinner.setSelection(0)
} else {
protcolSpinner.setSelection(1)
}
// init the server information
val serverUrl = findViewById<TextInputEditText>(R.id.server_url)
val serverPort = findViewById<TextInputEditText>(R.id.server_port)
val serverPath = findViewById<TextInputEditText>(R.id.server_path)
val serverUser = findViewById<TextInputEditText>(R.id.server_user)
val serverUri = findViewById<TextInputEditText>(R.id.clone_uri)
serverUrl.setText(settings.getString("git_remote_server", ""))
serverPort.setText(settings.getString("git_remote_port", ""))
serverUser.setText(settings.getString("git_remote_username", ""))
serverPath.setText(settings.getString("git_remote_location", ""))
serverUrl.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {}
override fun onTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {
if (serverUrl.isFocused)
updateURI()
}
override fun afterTextChanged(editable: Editable) {}
})
serverPort.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {}
override fun onTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {
if (serverPort.isFocused)
updateURI()
}
override fun afterTextChanged(editable: Editable) {}
})
serverUser.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {}
override fun onTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {
if (serverUser.isFocused)
updateURI()
}
override fun afterTextChanged(editable: Editable) {}
})
serverPath.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {}
override fun onTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {
if (serverPath.isFocused)
updateURI()
}
override fun afterTextChanged(editable: Editable) {}
})
serverUri.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {}
override fun onTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {
if (serverUri.isFocused)
splitURI()
}
override fun afterTextChanged(editable: Editable) {}
})
if (operationCode == EDIT_SERVER) {
findViewById<View>(R.id.clone_button).visibility = View.INVISIBLE
findViewById<View>(R.id.save_button).visibility = View.VISIBLE
} else {
findViewById<View>(R.id.clone_button).visibility = View.VISIBLE
findViewById<View>(R.id.save_button).visibility = View.INVISIBLE
}
updateURI()
}
EDIT_GIT_CONFIG -> {
setContentView(R.layout.activity_git_config)
setTitle(R.string.title_activity_git_config)
showGitConfig()
}
REQUEST_PULL -> syncRepository(REQUEST_PULL)
REQUEST_PUSH -> syncRepository(REQUEST_PUSH)
REQUEST_SYNC -> syncRepository(REQUEST_SYNC)
}
}
/**
* Fills in the server_uri field with the information coming from other fields
*/
private fun updateURI() {
val uri = findViewById<TextInputEditText>(R.id.clone_uri)
val serverUrl = findViewById<TextInputEditText>(R.id.server_url)
val serverPort = findViewById<TextInputEditText>(R.id.server_port)
val serverPath = findViewById<TextInputEditText>(R.id.server_path)
val serverUser = findViewById<TextInputEditText>(R.id.server_user)
if (uri != null) {
when (protocol) {
"ssh://" -> {
var hostname = (serverUser.text.toString()
+ "@" +
serverUrl.text.toString().trim { it <= ' ' }
+ ":")
if (serverPort.text.toString() == "22") {
hostname += serverPath.text.toString()
findViewById<View>(R.id.warn_url).visibility = View.GONE
} else {
val warnUrl = findViewById<AppCompatTextView>(R.id.warn_url)
if (!serverPath.text.toString().matches("/.*".toRegex()) && serverPort.text.toString().isNotEmpty()) {
warnUrl.setText(R.string.warn_malformed_url_port)
warnUrl.visibility = View.VISIBLE
} else {
warnUrl.visibility = View.GONE
}
hostname += serverPort.text.toString() + serverPath.text.toString()
}
if (hostname != "@:") uri.setText(hostname)
}
"https://" -> {
val hostname = StringBuilder()
hostname.append(serverUrl.text.toString().trim { it <= ' ' })
if (serverPort.text.toString() == "443") {
hostname.append(serverPath.text.toString())
findViewById<View>(R.id.warn_url).visibility = View.GONE
} else {
hostname.append("/")
hostname.append(serverPort.text.toString())
.append(serverPath.text.toString())
}
if (hostname.toString() != "@/") uri.setText(hostname)
}
else -> {
}
}
}
}
/**
* Splits the information in server_uri into the other fields
*/
private fun splitURI() {
val serverUri = findViewById<TextInputEditText>(R.id.clone_uri)
val serverUrl = findViewById<TextInputEditText>(R.id.server_url)
val serverPort = findViewById<TextInputEditText>(R.id.server_port)
val serverPath = findViewById<TextInputEditText>(R.id.server_path)
val serverUser = findViewById<TextInputEditText>(R.id.server_user)
val uri = serverUri.text.toString()
val pattern = Pattern.compile("(.+)@([\\w\\d.]+):([\\d]+)*(.*)")
val matcher = pattern.matcher(uri)
if (matcher.find()) {
val count = matcher.groupCount()
if (count > 1) {
serverUser.setText(matcher.group(1))
serverUrl.setText(matcher.group(2))
}
if (count == 4) {
serverPort.setText(matcher.group(3))
serverPath.setText(matcher.group(4))
val warnUrl = findViewById<AppCompatTextView>(R.id.warn_url)
if (!serverPath.text.toString().matches("/.*".toRegex()) && serverPort.text.toString().isNotEmpty()) {
warnUrl.setText(R.string.warn_malformed_url_port)
warnUrl.visibility = View.VISIBLE
} else {
warnUrl.visibility = View.GONE
}
}
}
}
public override fun onResume() {
super.onResume()
updateURI()
}
override fun onDestroy() {
// Do not leak the service connection
if (identityBuilder != null) {
identityBuilder!!.close()
identityBuilder = null
}
super.onDestroy()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.git_clone, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.user_pref -> try {
val intent = Intent(this, UserPreference::class.java)
startActivity(intent)
return true
} catch (e: Exception) {
println("Exception caught :(")
e.printStackTrace()
}
android.R.id.home -> {
finish()
return true
}
}
return super.onOptionsItemSelected(item)
}
/**
* Saves the configuration found in the form
*/
private fun saveConfiguration(): Boolean {
// remember the settings
val editor = settings.edit()
editor.putString("git_remote_server", (findViewById<View>(R.id.server_url) as TextInputEditText).text.toString())
editor.putString("git_remote_location", (findViewById<View>(R.id.server_path) as TextInputEditText).text.toString())
editor.putString("git_remote_username", (findViewById<View>(R.id.server_user) as TextInputEditText).text.toString())
editor.putString("git_remote_protocol", protocol)
editor.putString("git_remote_auth", connectionMode)
editor.putString("git_remote_port", (findViewById<View>(R.id.server_port) as TextInputEditText).text.toString())
editor.putString("git_remote_uri", (findViewById<View>(R.id.clone_uri) as TextInputEditText).text.toString())
// 'save' hostname variable for use by addRemote() either here or later
// in syncRepository()
hostname = (findViewById<View>(R.id.clone_uri) as TextInputEditText).text.toString()
val port = (findViewById<View>(R.id.server_port) as TextInputEditText).text.toString()
// don't ask the user, take off the protocol that he puts in
hostname = hostname.replaceFirst("^.+://".toRegex(), "")
(findViewById<View>(R.id.clone_uri) as TextInputEditText).setText(hostname)
if (protocol != "ssh://") {
hostname = protocol + hostname
} else {
// if the port is explicitly given, jgit requires the ssh://
if (port.isNotEmpty() && port != "22")
hostname = protocol + hostname
// did he forget the username?
if (!hostname.matches("^.+@.+".toRegex())) {
MaterialAlertDialogBuilder(this)
.setMessage(context.getString(R.string.forget_username_dialog_text))
.setPositiveButton(context.getString(R.string.dialog_oops), null)
.show()
return false
}
}
if (PasswordRepository.isInitialized && settings.getBoolean("repository_initialized", false)) {
// don't just use the clone_uri text, need to use hostname which has
// had the proper protocol prepended
PasswordRepository.addRemote("origin", hostname, true)
}
editor.apply()
return true
}
/**
* Save the repository information to the shared preferences settings
*/
@Suppress("UNUSED_PARAMETER")
fun saveConfiguration(view: View) {
if (!saveConfiguration())
return
finish()
}
private fun showGitConfig() {
// init the server information
val username = findViewById<TextInputEditText>(R.id.git_user_name)
val email = findViewById<TextInputEditText>(R.id.git_user_email)
val abort = findViewById<MaterialButton>(R.id.git_abort_rebase)
username.setText(settings.getString("git_config_user_name", ""))
email.setText(settings.getString("git_config_user_email", ""))
// git status
val repo = PasswordRepository.getRepository(PasswordRepository.getRepositoryDirectory(context))
if (repo != null) {
val commitHash = findViewById<AppCompatTextView>(R.id.git_commit_hash)
try {
val objectId = repo.resolve(Constants.HEAD)
val ref = repo.getRef("refs/heads/master")
val head = if (ref.objectId.equals(objectId)) ref.name else "DETACHED"
commitHash.text = String.format("%s (%s)", objectId.abbreviate(8).name(), head)
// enable the abort button only if we're rebasing
val isRebasing = repo.repositoryState.isRebasing
abort.isEnabled = isRebasing
abort.alpha = if (isRebasing) 1.0f else 0.5f
} catch (e: Exception) {
// ignore
}
}
}
private fun saveGitConfigs(): Boolean {
// remember the settings
val editor = settings.edit()
val email = (findViewById<View>(R.id.git_user_email) as TextInputEditText).text!!.toString()
editor.putString("git_config_user_email", email)
editor.putString("git_config_user_name", (findViewById<View>(R.id.git_user_name) as TextInputEditText).text.toString())
if (!email.matches(emailPattern.toRegex())) {
MaterialAlertDialogBuilder(this)
.setMessage(context.getString(R.string.invalid_email_dialog_text))
.setPositiveButton(context.getString(R.string.dialog_oops), null)
.show()
return false
}
editor.apply()
return true
}
@Suppress("UNUSED_PARAMETER")
fun applyGitConfigs(view: View) {
if (!saveGitConfigs())
return
PasswordRepository.setUserName(settings.getString("git_config_user_name", null) ?: "")
PasswordRepository.setUserEmail(settings.getString("git_config_user_email", null) ?: "")
finish()
}
@Suppress("UNUSED_PARAMETER")
fun abortRebase(view: View) {
launchGitOperation(BREAK_OUT_OF_DETACHED)
}
@Suppress("UNUSED_PARAMETER")
fun resetToRemote(view: View) {
launchGitOperation(REQUEST_RESET)
}
/**
* Clones the repository, the directory exists, deletes it
*/
@Suppress("UNUSED_PARAMETER")
fun cloneRepository(view: View) {
if (PasswordRepository.getRepository(null) == null) {
PasswordRepository.initialize(this)
}
val localDir = requireNotNull(PasswordRepository.getRepositoryDirectory(context))
if (!saveConfiguration())
return
// Warn if non-empty folder unless it's a just-initialized store that has just a .git folder
if (localDir.exists() && localDir.listFiles()!!.isNotEmpty()
&& !(localDir.listFiles()!!.size == 1 && localDir.listFiles()!![0].name == ".git")) {
MaterialAlertDialogBuilder(this)
.setTitle(R.string.dialog_delete_title)
.setMessage(resources.getString(R.string.dialog_delete_msg) + " " + localDir.toString())
.setCancelable(false)
.setPositiveButton(R.string.dialog_delete
) { dialog, _ ->
try {
FileUtils.deleteDirectory(localDir)
launchGitOperation(REQUEST_CLONE)
} catch (e: IOException) {
//TODO Handle the exception correctly if we are unable to delete the directory...
e.printStackTrace()
MaterialAlertDialogBuilder(this).setMessage(e.message).show()
}
dialog.cancel()
}
.setNegativeButton(R.string.dialog_do_not_delete
) { dialog, _ -> dialog.cancel() }
.show()
} else {
try {
// Silently delete & replace the lone .git folder if it exists
if (localDir.exists() && localDir.listFiles()!!.size == 1 && localDir.listFiles()!![0].name == ".git") {
try {
FileUtils.deleteDirectory(localDir)
} catch (e: IOException) {
e.printStackTrace()
MaterialAlertDialogBuilder(this).setMessage(e.message).show()
}
}
} catch (e: Exception) {
//This is what happens when jgit fails :(
//TODO Handle the diffent cases of exceptions
e.printStackTrace()
MaterialAlertDialogBuilder(this).setMessage(e.message).show()
}
launchGitOperation(REQUEST_CLONE)
}
}
/**
* Syncs the local repository with the remote one (either pull or push)
*
* @param operation the operation to execute can be REQUEST_PULL or REQUEST_PUSH
*/
private fun syncRepository(operation: Int) {
if (settings.getString("git_remote_username", "")!!.isEmpty() ||
settings.getString("git_remote_server", "")!!.isEmpty() ||
settings.getString("git_remote_location", "")!!.isEmpty())
MaterialAlertDialogBuilder(this)
.setMessage(context.getString(R.string.set_information_dialog_text))
.setPositiveButton(context.getString(R.string.dialog_positive)) { _, _ ->
val intent = Intent(context, UserPreference::class.java)
startActivityForResult(intent, REQUEST_PULL)
}
.setNegativeButton(context.getString(R.string.dialog_negative)) { _, _ ->
// do nothing :(
setResult(AppCompatActivity.RESULT_OK)
finish()
}
.show()
else {
// check that the remote origin is here, else add it
PasswordRepository.addRemote("origin", hostname, false)
launchGitOperation(operation)
}
}
/**
* Attempt to launch the requested GIT operation. Depending on the configured auth, it may not
* be possible to launch the operation immediately. In that case, this function may launch an
* intermediate activity instead, which will gather necessary information and post it back via
* onActivityResult, which will then re-call this function. This may happen multiple times,
* until either an error is encountered or the operation is successfully launched.
*
* @param operation The type of GIT operation to launch
*/
private fun launchGitOperation(operation: Int) {
val op: GitOperation
val localDir = requireNotNull(PasswordRepository.getRepositoryDirectory(context))
try {
// Before launching the operation with OpenKeychain auth, we need to issue several requests
// to the OpenKeychain API. IdentityBuild will take care of launching the relevant intents,
// we just need to keep calling it until it returns a completed ApiIdentity.
if (connectionMode.equals("OpenKeychain", ignoreCase = true) && identity == null) {
// Lazy initialization of the IdentityBuilder
if (identityBuilder == null) {
identityBuilder = SshApiSessionFactory.IdentityBuilder(this)
}
// Try to get an ApiIdentity and bail if one is not ready yet. The builder will ensure
// that onActivityResult is called with operation again, which will re-invoke us here
identity = identityBuilder!!.tryBuild(operation)
if (identity == null)
return
}
when (operation) {
REQUEST_CLONE, GitOperation.GET_SSH_KEY_FROM_CLONE -> op = CloneOperation(localDir, this).setCommand(hostname)
REQUEST_PULL -> op = PullOperation(localDir, this).setCommand()
REQUEST_PUSH -> op = PushOperation(localDir, this).setCommand()
REQUEST_SYNC -> op = SyncOperation(localDir, this).setCommands()
BREAK_OUT_OF_DETACHED -> op = BreakOutOfDetached(localDir, this).setCommands()
REQUEST_RESET -> op = ResetToRemoteOperation(localDir, this).setCommands()
SshApiSessionFactory.POST_SIGNATURE -> return
else -> {
Log.e(TAG, "Operation not recognized : $operation")
setResult(AppCompatActivity.RESULT_CANCELED)
finish()
return
}
}
op.executeAfterAuthentication(connectionMode,
settings.getString("git_remote_username", "git")!!,
File("$filesDir/.ssh_key"),
identity)
} catch (e: Exception) {
e.printStackTrace()
MaterialAlertDialogBuilder(this).setMessage(e.message).show()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int,
data: Intent?) {
// In addition to the pre-operation-launch series of intents for OpenKeychain auth
// that will pass through here and back to launchGitOperation, there is one
// synchronous operation that happens /after/ the operation has been launched in the
// background thread - the actual signing of the SSH challenge. We pass through the
// completed signature to the ApiIdentity, which will be blocked in the other thread
// waiting for it.
if (requestCode == SshApiSessionFactory.POST_SIGNATURE && identity != null)
identity!!.postSignature(data)
if (resultCode == AppCompatActivity.RESULT_CANCELED) {
setResult(AppCompatActivity.RESULT_CANCELED)
finish()
} else if (resultCode == AppCompatActivity.RESULT_OK) {
// If an operation has been re-queued via this mechanism, let the
// IdentityBuilder attempt to extract some updated state from the intent before
// trying to re-launch the operation.
if (identityBuilder != null) {
identityBuilder!!.consume(data)
}
launchGitOperation(requestCode)
}
super.onActivityResult(requestCode, resultCode, data)
}
companion object {
const val REQUEST_PULL = 101
const val REQUEST_PUSH = 102
const val REQUEST_CLONE = 103
const val REQUEST_INIT = 104
const val EDIT_SERVER = 105
const val REQUEST_SYNC = 106
@Suppress("Unused")
const val REQUEST_CREATE = 107
const val EDIT_GIT_CONFIG = 108
const val BREAK_OUT_OF_DETACHED = 109
const val REQUEST_RESET = 110
private const val TAG = "GitAct"
private const val emailPattern = "^[^@]+@[^@]+$"
}
}
|
gpl-3.0
|
da96d8c17edd9d06c03cfb300c0c26c7
| 42.966667 | 129 | 0.574609 | 5.296222 | false | false | false | false |
PaulWoitaschek/MaterialAudiobookPlayer
|
app/src/main/java/de/ph1b/audiobook/features/settings/dialogs/PlaybackSpeedDialogController.kt
|
1
|
2905
|
package de.ph1b.audiobook.features.settings.dialogs
import android.annotation.SuppressLint
import android.app.Dialog
import android.os.Bundle
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import de.ph1b.audiobook.R
import de.ph1b.audiobook.data.Book
import de.ph1b.audiobook.data.repo.BookRepository
import de.ph1b.audiobook.injection.PrefKeys
import de.ph1b.audiobook.injection.appComponent
import de.ph1b.audiobook.misc.DialogController
import de.ph1b.audiobook.misc.DialogLayoutContainer
import de.ph1b.audiobook.misc.inflate
import de.ph1b.audiobook.misc.progressChangedStream
import de.ph1b.audiobook.persistence.pref.Pref
import de.ph1b.audiobook.playback.PlayerController
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.dialog_amount_chooser.*
import java.text.DecimalFormat
import java.util.UUID
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Named
/**
* Dialog for setting the playback speed of the current book.
*/
class PlaybackSpeedDialogController : DialogController() {
@Inject
lateinit var repo: BookRepository
@field:[Inject Named(PrefKeys.CURRENT_BOOK)]
lateinit var currentBookIdPref: Pref<UUID>
@Inject
lateinit var playerController: PlayerController
@SuppressLint("InflateParams")
override fun onCreateDialog(savedViewState: Bundle?): Dialog {
appComponent.inject(this)
// init views
val container =
DialogLayoutContainer(activity!!.layoutInflater.inflate(R.layout.dialog_amount_chooser))
val seekBar = container.seekBar
val textView = container.textView
// setting current speed
val book = repo.bookById(currentBookIdPref.value)
?: throw AssertionError("Cannot instantiate ${javaClass.name} without a current book")
val speed = book.content.playbackSpeed
seekBar.max = ((MAX - MIN) * FACTOR).toInt()
seekBar.progress = ((speed - MIN) * FACTOR).toInt()
// observable of seek bar, mapped to speed
seekBar.progressChangedStream(initialNotification = true)
.map { Book.SPEED_MIN + it.toFloat() / FACTOR }
.doOnNext {
// update speed text
val text = "${activity!!.getString(R.string.playback_speed)}: ${speedFormatter.format(it)}"
textView.text = text
}
.debounce(50, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
.subscribe { playerController.setSpeed(it) } // update speed after debounce
.disposeOnDestroyDialog()
return MaterialDialog(activity!!).apply {
title(R.string.playback_speed)
customView(view = container.containerView, scrollable = true)
}
}
companion object {
private const val MAX = Book.SPEED_MAX
private const val MIN = Book.SPEED_MIN
private const val FACTOR = 100F
private val speedFormatter = DecimalFormat("0.0 x")
}
}
|
lgpl-3.0
|
352f4a9e88fc59fe6abb2cd91652a7ba
| 35.3125 | 99 | 0.757659 | 4.259531 | false | false | false | false |
vladmm/intellij-community
|
plugins/settings-repository/src/settings/readOnlySourcesEditor.kt
|
5
|
6198
|
/*
* 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.settingsRepository
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.options.ConfigurableUi
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.ui.DialogBuilder
import com.intellij.openapi.ui.TextBrowseFolderListener
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.ui.DocumentAdapter
import com.intellij.util.Function
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.ui.FormBuilder
import com.intellij.util.ui.table.TableModelEditor
import gnu.trove.THashSet
import org.jetbrains.settingsRepository.git.asProgressMonitor
import org.jetbrains.settingsRepository.git.cloneBare
import java.io.File
import javax.swing.JTextField
import javax.swing.event.DocumentEvent
private val COLUMNS = arrayOf(object : TableModelEditor.EditableColumnInfo<ReadonlySource, Boolean>() {
override fun getColumnClass() = Boolean::class.java
override fun valueOf(item: ReadonlySource) = item.active
override fun setValue(item: ReadonlySource, value: Boolean) {
item.active = value
}
},
object : TableModelEditor.EditableColumnInfo<ReadonlySource, String>() {
override fun valueOf(item: ReadonlySource) = item.url
override fun setValue(item: ReadonlySource, value: String) {
item.url = value
}
})
internal fun createReadOnlySourcesEditor(): ConfigurableUi<IcsSettings> {
val itemEditor = object : TableModelEditor.DialogItemEditor<ReadonlySource>() {
override fun clone(item: ReadonlySource, forInPlaceEditing: Boolean) = ReadonlySource(item.url, item.active)
override fun getItemClass() = ReadonlySource::class.java
override fun edit(item: ReadonlySource, mutator: Function<ReadonlySource, ReadonlySource>, isAdd: Boolean) {
val dialogBuilder = DialogBuilder()
val urlField = TextFieldWithBrowseButton(JTextField(20))
urlField.addBrowseFolderListener(TextBrowseFolderListener(FileChooserDescriptorFactory.createSingleFolderDescriptor()))
urlField.textField.document.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(event: DocumentEvent) {
val url = StringUtil.nullize(urlField.text)
val enabled: Boolean
try {
enabled = url != null && url.length > 1 && icsManager.repositoryService.checkUrl(url, null)
}
catch (e: Exception) {
enabled = false
}
dialogBuilder.setOkActionEnabled(enabled)
}
})
dialogBuilder.title("Add read-only source").resizable(false).centerPanel(FormBuilder.createFormBuilder().addLabeledComponent("URL:", urlField).panel).setPreferredFocusComponent(urlField)
if (dialogBuilder.showAndGet()) {
mutator.`fun`(item).url = urlField.text
}
}
override fun applyEdited(oldItem: ReadonlySource, newItem: ReadonlySource) {
newItem.url = oldItem.url
}
override fun isUseDialogToAdd() = true
}
val editor = TableModelEditor(COLUMNS, itemEditor, "No sources configured")
editor.reset(icsManager.settings.readOnlySources)
return object : ConfigurableUi<IcsSettings> {
override fun isModified(settings: IcsSettings) = editor.isModified
override fun apply(settings: IcsSettings) {
val oldList = settings.readOnlySources
val toDelete = THashSet<String>(oldList.size)
for (oldSource in oldList) {
ContainerUtil.addIfNotNull(toDelete, oldSource.path)
}
val toCheckout = THashSet<ReadonlySource>()
val newList = editor.apply()
for (newSource in newList) {
val path = newSource.path
if (path != null && !toDelete.remove(path)) {
toCheckout.add(newSource)
}
}
if (toDelete.isEmpty && toCheckout.isEmpty) {
return
}
ProgressManager.getInstance().run(object : Task.Modal(null, icsMessage("task.sync.title"), true) {
override fun run(indicator: ProgressIndicator) {
indicator.isIndeterminate = true
val root = icsManager.readOnlySourcesManager.rootDir
if (toDelete.isNotEmpty()) {
indicator.text = "Deleting old repositories"
for (path in toDelete) {
indicator.checkCanceled()
try {
indicator.text2 = path
FileUtil.delete(File(root, path))
}
catch (e: Exception) {
LOG.error(e)
}
}
}
if (toCheckout.isNotEmpty()) {
for (source in toCheckout) {
indicator.checkCanceled()
try {
indicator.text = "Cloning ${StringUtil.trimMiddle(source.url!!, 255)}"
val dir = File(root, source.path!!)
if (dir.exists()) {
FileUtil.delete(dir)
}
cloneBare(source.url!!, dir, icsManager.credentialsStore, indicator.asProgressMonitor()).close()
}
catch (e: Exception) {
LOG.error(e)
}
}
}
icsManager.readOnlySourcesManager.setSources(newList)
}
})
}
override fun reset(settings: IcsSettings) {
editor.reset(settings.readOnlySources)
}
override fun getComponent() = editor.createComponent()
}
}
|
apache-2.0
|
71a77e39509b8250c0c731b7085d4c9f
| 35.674556 | 192 | 0.68264 | 4.853563 | false | false | false | false |
PlanBase/PdfLayoutMgr2
|
src/main/java/com/planbase/pdf/lm2/contents/Table.kt
|
1
|
5915
|
// Copyright 2017 PlanBase Inc.
//
// This file is part of PdfLayoutMgr2
//
// PdfLayoutMgr is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// PdfLayoutMgr is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with PdfLayoutMgr. If not, see <https://www.gnu.org/licenses/agpl-3.0.en.html>.
//
// If you wish to use this code with proprietary software,
// contact PlanBase Inc. <https://planbase.com> to purchase a commercial license.
package com.planbase.pdf.lm2.contents
import com.planbase.pdf.lm2.attributes.CellStyle
import com.planbase.pdf.lm2.attributes.DimAndPageNums
import com.planbase.pdf.lm2.attributes.TextStyle
import com.planbase.pdf.lm2.lineWrapping.LineWrappable
import com.planbase.pdf.lm2.lineWrapping.LineWrapped
import com.planbase.pdf.lm2.lineWrapping.LineWrapper
import com.planbase.pdf.lm2.pages.RenderTarget
import com.planbase.pdf.lm2.utils.Coord
import com.planbase.pdf.lm2.utils.Dim
import com.planbase.pdf.lm2.utils.mutableListToStr
import kotlin.math.max
/*
Algorithm for choosing column sizes dynamically:
- For each cell, figure out min and max width.
- For each column figure out min and max width.
- If all columns fit with max-width, then do that, shrinking total table width as needed: END.
- If columns do not fit with min-width, then expand total table width to fit every column min-width and use that: END.
- If any column overflows, then figure out some ratio of min to max width for the cells in that column, an average width.
colAvgWidth = (sumMinWidths + sumMaxWidths) / (numRows * 2)
Then figure proportion of average column widths
colProportion1 = colAvgWidth / sumColAvgWidths
colWidth1 = tableMaxWidth * colProportion1
- Each column must have at least min-width size. So check all colWidth1's and adjust any that are less than that size.
- Proportion the remaining columns and find colProportion2 and colWidth2
- Repeat until all columns have at least min-width.
*/
/**
* Use this to create Tables. This strives to remind the programmer of HTML tables but because you
* can resize and scroll a browser window, and not a piece of paper, this is fundamentally different.
* Still familiarity with HTML may make this class easier to use.
*/
class Table
@JvmOverloads
constructor(var cellWidths: MutableList<Double> = mutableListOf(),
var cellStyle: CellStyle = CellStyle.TOP_LEFT_BORDERLESS,
var textStyle: TextStyle? = null,
private val rows: MutableList<TableRow> = mutableListOf()) : LineWrappable {
var minRowHeight = 0.0
fun minRowHeight(h: Double): Table {
minRowHeight = h
return this
}
private var openRow = false
override fun lineWrapper() =
LineWrapper.preWrappedLineWrapper(WrappedTable(this.rows.map { TableRow.WrappedTableRow(it) }))
fun wrap(): WrappedTable {
if (openRow) {
throw IllegalStateException("Must end TableRow before wrapping table!")
}
return WrappedTable(this.rows.map { TableRow.WrappedTableRow(it) })
}
/** Sets default widths for all table rows. */
fun addCellWidths(x: Iterable<Double>): Table {
cellWidths.addAll(x)
return this
}
fun addCellWidths(vararg ws: Double): Table {
for (w in ws) {
cellWidths.add(w)
}
return this
}
// fun addCellWidth(x: Double): TableBuilder {
// cellWidths.add(x)
// return this
// }
fun cellStyle(x: CellStyle): Table {
cellStyle = x
return this
}
fun textStyle(x: TextStyle): Table {
textStyle = x
return this
}
fun addRow(trb: TableRow): Table {
rows.add(trb)
return this
}
fun startRow(): TableRow {
if (openRow) {
throw IllegalStateException("Must end current TableRow before starting a new one!")
}
openRow = true
return TableRow(this, { openRow = false })
}
override fun toString(): String =
"Table(${mutableListToStr(0, cellWidths)})" +
rows.fold(StringBuilder(""),
{sB, row -> sB.append("\n.startRow()")
.append(row)
.append("\n.endRow()")})
.toString()
data class WrappedTable(private val rows:List<TableRow.WrappedTableRow>) : LineWrapped {
override val dim: Dim = Dim.sum(rows.map { row -> row.dim })
override val ascent: Double = dim.height
/*
* Renders item and all child-items with given width and returns the x-y pair of the
* lower-right-hand corner of the last line (e.g. of text).
*/
override fun render(lp: RenderTarget, topLeft: Coord, reallyRender: Boolean,
justifyWidth:Double): DimAndPageNums {
var y = topLeft.y
var maxWidth = 0.0
var pageNums:IntRange = DimAndPageNums.INVALID_PAGE_RANGE
for (row in rows) {
val dimAndPageNums: DimAndPageNums = row.render(lp, topLeft.withY(y), reallyRender)
maxWidth = max(maxWidth, dimAndPageNums.dim.width)
y -= dimAndPageNums.dim.height
pageNums = dimAndPageNums.maxExtents(pageNums)
}
return DimAndPageNums(Dim(maxWidth, topLeft.y - y), pageNums)
}
override fun toString(): String = "WrappedTable($rows)"
}
}
|
agpl-3.0
|
30560cc054741a58200e12a299915c14
| 35.512346 | 122 | 0.665934 | 4.301818 | false | false | false | false |
google/intellij-community
|
python/src/com/jetbrains/python/run/TargetedPythonPaths.kt
|
2
|
9973
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("TargetedPythonPaths")
package com.jetbrains.python.run
import com.intellij.execution.target.TargetEnvironment
import com.intellij.execution.target.TargetEnvironmentRequest
import com.intellij.execution.target.local.LocalTargetEnvironmentRequest
import com.intellij.execution.target.value.TargetEnvironmentFunction
import com.intellij.execution.target.value.constant
import com.intellij.execution.target.value.getTargetEnvironmentValueForLocalPath
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.SdkAdditionalData
import com.intellij.openapi.roots.CompilerModuleExtension
import com.intellij.openapi.roots.LibraryOrderEntry
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.JarFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.remote.RemoteSdkProperties
import com.intellij.util.PlatformUtils
import com.jetbrains.python.PythonHelpersLocator
import com.jetbrains.python.facet.LibraryContributingFacet
import com.jetbrains.python.library.PythonLibraryType
import com.jetbrains.python.remote.PyRemotePathMapper
import com.jetbrains.python.run.target.getTargetPathForPythonConsoleExecution
import com.jetbrains.python.sdk.PythonEnvUtil
import com.jetbrains.python.sdk.PythonSdkAdditionalData
import com.jetbrains.python.sdk.PythonSdkUtil
import com.jetbrains.python.sdk.flavors.JythonSdkFlavor
import com.jetbrains.python.sdk.flavors.PythonSdkFlavor
import java.io.File
import java.nio.file.Path
import java.util.function.Function
fun initPythonPath(envs: MutableMap<String, Function<TargetEnvironment, String>>,
passParentEnvs: Boolean,
pythonPathList: MutableCollection<Function<TargetEnvironment, String>>,
targetEnvironmentRequest: TargetEnvironmentRequest) {
// TODO [Targets API] Passing parent envs logic should be moved somewhere else
if (passParentEnvs && targetEnvironmentRequest is LocalTargetEnvironmentRequest && !envs.containsKey(PythonEnvUtil.PYTHONPATH)) {
appendSystemPythonPath(pythonPathList)
}
appendToPythonPath(envs, pythonPathList, targetEnvironmentRequest.targetPlatform)
}
private fun appendSystemPythonPath(pythonPath: MutableCollection<Function<TargetEnvironment, String>>) {
val syspath = System.getenv(PythonEnvUtil.PYTHONPATH)
if (syspath != null) {
pythonPath.addAll(syspath.split(File.pathSeparator).dropLastWhile(String::isEmpty).map(::constant))
}
}
fun collectPythonPath(project: Project,
module: Module?,
sdkHome: String?,
pathMapper: PyRemotePathMapper?,
shouldAddContentRoots: Boolean,
shouldAddSourceRoots: Boolean,
isDebug: Boolean): Collection<Function<TargetEnvironment, String>> {
val sdk = PythonSdkUtil.findSdkByPath(sdkHome)
return collectPythonPath(
LocalPathToTargetPathConverterSdkAware(project, sdk, pathMapper),
module,
sdkHome,
shouldAddContentRoots,
shouldAddSourceRoots,
isDebug
)
}
private fun collectPythonPath(pathConverter: LocalPathToTargetPathConverter,
module: Module?,
sdkHome: String?,
shouldAddContentRoots: Boolean,
shouldAddSourceRoots: Boolean,
isDebug: Boolean): Collection<Function<TargetEnvironment, String>> {
val pythonPath: MutableSet<Function<TargetEnvironment, String>> = LinkedHashSet(
collectPythonPath(pathConverter,
module,
shouldAddContentRoots,
shouldAddSourceRoots)
)
if (isDebug && PythonSdkFlavor.getFlavor(sdkHome) is JythonSdkFlavor) {
//that fixes Jython problem changing sys.argv on execfile, see PY-8164
for (helpersResource in listOf("pycharm", "pydev")) {
val helperPath = PythonHelpersLocator.getHelperPath(helpersResource)
val targetHelperPath = getTargetEnvironmentValueForLocalPath(Path.of(helperPath))
pythonPath.add(targetHelperPath)
}
}
return pythonPath
}
private fun collectPythonPath(pathConverter: LocalPathToTargetPathConverter,
module: Module?,
addContentRoots: Boolean,
addSourceRoots: Boolean): Collection<Function<TargetEnvironment, String>> {
val pythonPathList: MutableCollection<Function<TargetEnvironment, String>> = LinkedHashSet()
if (module != null) {
val dependencies: MutableSet<Module> = HashSet()
ModuleUtilCore.getDependencies(module, dependencies)
if (addContentRoots) {
addRoots(pathConverter, pythonPathList, ModuleRootManager.getInstance(module).contentRoots)
for (dependency in dependencies) {
addRoots(pathConverter, pythonPathList, ModuleRootManager.getInstance(dependency).contentRoots)
}
}
if (addSourceRoots) {
addRoots(pathConverter, pythonPathList, ModuleRootManager.getInstance(module).sourceRoots)
for (dependency in dependencies) {
addRoots(pathConverter, pythonPathList, ModuleRootManager.getInstance(dependency).sourceRoots)
}
}
addLibrariesFromModule(module, pythonPathList)
addRootsFromModule(module, pythonPathList)
for (dependency in dependencies) {
addLibrariesFromModule(dependency, pythonPathList)
addRootsFromModule(dependency, pythonPathList)
}
}
return pythonPathList
}
/**
* List of [target->targetPath] functions. TargetPaths are to be added to ``PYTHONPATH`` because user did so
*/
fun getAddedPaths(sdkAdditionalData: SdkAdditionalData): List<Function<TargetEnvironment, String>> {
val pathList: MutableList<Function<TargetEnvironment, String>> = ArrayList()
if (sdkAdditionalData is PythonSdkAdditionalData) {
val addedPaths = if (sdkAdditionalData is RemoteSdkProperties) {
sdkAdditionalData.addedPathFiles.map { sdkAdditionalData.pathMappings.convertToRemote(it.path) }
}
else {
sdkAdditionalData.addedPathFiles.map { it.path }
}
for (file in addedPaths) {
pathList.add(constant(file))
}
}
return pathList
}
private fun addToPythonPath(pathConverter: LocalPathToTargetPathConverter,
file: VirtualFile,
pathList: MutableCollection<Function<TargetEnvironment, String>>) {
if (file.fileSystem is JarFileSystem) {
val realFile = JarFileSystem.getInstance().getVirtualFileForJar(file)
if (realFile != null) {
addIfNeeded(pathConverter, realFile, pathList)
}
}
else {
addIfNeeded(pathConverter, file, pathList)
}
}
private fun addIfNeeded(pathConverter: LocalPathToTargetPathConverter,
file: VirtualFile,
pathList: MutableCollection<Function<TargetEnvironment, String>>) {
val filePath = Path.of(FileUtil.toSystemDependentName(file.path))
pathList.add(pathConverter.getTargetPath(filePath))
}
/**
* Adds all libs from [module] to [pythonPathList] as [target,targetPath] func
*/
private fun addLibrariesFromModule(module: Module,
pythonPathList: MutableCollection<TargetEnvironmentFunction<String>>) {
val entries = ModuleRootManager.getInstance(module).orderEntries
for (entry in entries) {
if (entry is LibraryOrderEntry) {
val name = entry.libraryName
if (name != null && name.endsWith(LibraryContributingFacet.PYTHON_FACET_LIBRARY_NAME_SUFFIX)) {
// skip libraries from Python facet
continue
}
for (root in entry.getRootFiles(OrderRootType.CLASSES).map { it.toNioPath() }) {
val library = entry.library
if (!PlatformUtils.isPyCharm()) {
pythonPathList += getTargetEnvironmentValueForLocalPath(root)
}
else if (library is LibraryEx) {
val kind = library.kind
if (kind === PythonLibraryType.getInstance().kind) {
pythonPathList += getTargetEnvironmentValueForLocalPath(root)
}
}
}
}
}
}
private fun addRootsFromModule(module: Module, pythonPathList: MutableCollection<Function<TargetEnvironment, String>>) {
// for Jython
val extension = CompilerModuleExtension.getInstance(module)
if (extension != null) {
val path = extension.compilerOutputPath
if (path != null) {
pythonPathList.add(constant(path.path))
}
val pathForTests = extension.compilerOutputPathForTests
if (pathForTests != null) {
pythonPathList.add(constant(pathForTests.path))
}
}
}
private fun addRoots(pathConverter: LocalPathToTargetPathConverter,
pythonPathList: MutableCollection<Function<TargetEnvironment, String>>,
roots: Array<VirtualFile>) {
for (root in roots) {
addToPythonPath(pathConverter, root, pythonPathList)
}
}
private fun interface LocalPathToTargetPathConverter {
fun getTargetPath(localPath: Path): Function<TargetEnvironment, String>
}
private class LocalPathToTargetPathConverterSdkAware(private val project: Project,
private val sdk: Sdk?,
private val pathMapper: PyRemotePathMapper?)
: LocalPathToTargetPathConverter {
override fun getTargetPath(localPath: Path): Function<TargetEnvironment, String> {
return getTargetPathForPythonConsoleExecution(project, sdk, pathMapper, localPath)
}
}
|
apache-2.0
|
7f041241aaceb41e2edd1f38f8e53a5e
| 41.806867 | 140 | 0.721047 | 5.216004 | false | false | false | false |
google/intellij-community
|
platform/vcs-log/impl/src/com/intellij/vcs/log/history/FileHistoryFilterer.kt
|
1
|
18174
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.log.history
import com.intellij.diagnostic.telemetry.TraceManager
import com.intellij.diagnostic.telemetry.useWithScope
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.UnorderedPair
import com.intellij.openapi.vcs.AbstractVcs
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.history.VcsCachingHistory
import com.intellij.openapi.vcs.history.VcsFileRevision
import com.intellij.openapi.vcs.history.VcsFileRevisionEx
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.containers.MultiMap
import com.intellij.vcs.log.*
import com.intellij.vcs.log.data.CompressedRefs
import com.intellij.vcs.log.data.DataPack
import com.intellij.vcs.log.data.VcsLogData
import com.intellij.vcs.log.data.VcsLogProgress
import com.intellij.vcs.log.data.index.IndexDataGetter
import com.intellij.vcs.log.graph.GraphCommitImpl
import com.intellij.vcs.log.graph.PermanentGraph
import com.intellij.vcs.log.graph.VisibleGraph
import com.intellij.vcs.log.graph.impl.facade.PermanentGraphImpl
import com.intellij.vcs.log.history.FileHistoryPaths.fileHistory
import com.intellij.vcs.log.history.FileHistoryPaths.withFileHistory
import com.intellij.vcs.log.ui.frame.CommitPresentationUtil
import com.intellij.vcs.log.util.VcsLogUtil
import com.intellij.vcs.log.util.findBranch
import com.intellij.vcs.log.visible.*
import com.intellij.vcs.log.visible.filters.VcsLogFilterObject
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.Future
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
import java.util.concurrent.atomic.AtomicReference
class FileHistoryFilterer(private val logData: VcsLogData, private val logId: String) : VcsLogFilterer, Disposable {
private val project = logData.project
private val logProviders = logData.logProviders
private val storage = logData.storage
private val index = logData.index
private val vcsLogFilterer = VcsLogFiltererImpl(logProviders, storage, logData.topCommitsCache, logData.commitDetailsGetter, index)
private var fileHistoryTask: FileHistoryTask? = null
override fun filter(dataPack: DataPack,
oldVisiblePack: VisiblePack,
sortType: PermanentGraph.SortType,
filters: VcsLogFilterCollection,
commitCount: CommitCountStage): Pair<VisiblePack, CommitCountStage> {
val filePath = getFilePath(filters)
val root = filePath?.let { VcsLogUtil.getActualRoot(project, filePath) }
val hash = getHash(filters)
if (root != null && !filePath.isDirectory) {
val result = MyWorker(root, filePath, hash).filter(dataPack, oldVisiblePack, sortType, filters, commitCount)
if (result != null) return result
}
return vcsLogFilterer.filter(dataPack, oldVisiblePack, sortType, filters, commitCount)
}
override fun canFilterEmptyPack(filters: VcsLogFilterCollection): Boolean = true
private fun cancelLastTask(wait: Boolean) {
fileHistoryTask?.cancel(wait)
fileHistoryTask = null
}
private fun createFileHistoryTask(vcs: AbstractVcs, root: VirtualFile, filePath: FilePath, hash: Hash?, isInitial: Boolean): FileHistoryTask {
val oldHistoryTask = fileHistoryTask
if (oldHistoryTask != null && !oldHistoryTask.isCancelled && !isInitial &&
oldHistoryTask.filePath == filePath && oldHistoryTask.hash == hash) return oldHistoryTask
cancelLastTask(false)
val factory = project.service<VcsLogObjectsFactory>()
val newHistoryTask = object : FileHistoryTask(vcs, filePath, hash, createProgressIndicator()) {
override fun createCommitMetadataWithPath(revision: VcsFileRevision): CommitMetadataWithPath {
val revisionEx = revision as VcsFileRevisionEx
val commitHash = factory.createHash(revisionEx.revisionNumber.asString())
val metadata = factory.createCommitMetadata(commitHash, emptyList(), revisionEx.revisionDate.time, root,
CommitPresentationUtil.getSubject(revisionEx.commitMessage!!),
revisionEx.author!!, revisionEx.authorEmail!!,
revisionEx.commitMessage!!,
revisionEx.committerName!!, revisionEx.committerEmail!!, revisionEx.authorDate!!.time)
return CommitMetadataWithPath(storage.getCommitIndex(commitHash, root), metadata,
MaybeDeletedFilePath(revisionEx.path, revisionEx.isDeleted))
}
}
fileHistoryTask = newHistoryTask
return newHistoryTask
}
private fun createProgressIndicator(): ProgressIndicator {
return logData.progress.createProgressIndicator(VcsLogProgress.ProgressKey("file history task for $logId"))
}
override fun dispose() {
cancelLastTask(true)
}
private inner class MyWorker constructor(private val root: VirtualFile,
private val filePath: FilePath,
private val hash: Hash?) {
fun filter(dataPack: DataPack,
oldVisiblePack: VisiblePack,
sortType: PermanentGraph.SortType,
filters: VcsLogFilterCollection,
commitCount: CommitCountStage): Pair<VisiblePack, CommitCountStage>? {
TraceManager.getTracer("vcs").spanBuilder("computing history").useWithScope { scope ->
val isInitial = commitCount == CommitCountStage.INITIAL
val indexDataGetter = index.dataGetter
scope.setAttribute("filePath", filePath.toString())
if (indexDataGetter != null && index.isIndexed(root) && dataPack.isFull) {
cancelLastTask(false)
val visiblePack = filterWithIndex(indexDataGetter, dataPack, oldVisiblePack, sortType, filters, isInitial)
scope.setAttribute("type", "index")
if (checkNotEmpty(dataPack, visiblePack, true)) {
return Pair(visiblePack, commitCount)
}
}
ProjectLevelVcsManager.getInstance(project).getVcsFor(root)?.let { vcs ->
if (vcs.vcsHistoryProvider != null) {
try {
val visiblePack = filterWithProvider(vcs, dataPack, sortType, filters, isInitial)
scope.setAttribute("type", "history provider")
checkNotEmpty(dataPack, visiblePack, false)
return@filter Pair(visiblePack, commitCount)
}
catch (e: VcsException) {
LOG.error(e)
}
}
}
LOG.warn("Could not find vcs or history provider for file $filePath")
return null
}
}
private fun checkNotEmpty(dataPack: DataPack, visiblePack: VisiblePack, withIndex: Boolean): Boolean {
if (!dataPack.isFull) {
LOG.debug("Data pack is not full while computing file history for $filePath\n" +
"Found ${visiblePack.visibleGraph.visibleCommitCount} commits")
return true
}
else if (visiblePack.visibleGraph.visibleCommitCount == 0) {
LOG.warn("Empty file history from ${if (withIndex) "index" else "provider"} for $filePath")
return false
}
return true
}
@Throws(VcsException::class)
private fun filterWithProvider(vcs: AbstractVcs,
dataPack: DataPack,
sortType: PermanentGraph.SortType,
filters: VcsLogFilterCollection,
isInitial: Boolean): VisiblePack {
val (revisions, isDone) = createFileHistoryTask(vcs, root, filePath, hash, isInitial).waitForRevisions()
if (revisions.isEmpty()) return VisiblePack.EMPTY
if (dataPack.isFull) {
val pathsMap = revisions.associate { Pair(it.commit, it.path) }
val visibleGraph = createVisibleGraph(dataPack, sortType, null, pathsMap.keys)
return VisiblePack(dataPack, visibleGraph, !isDone, filters)
.withFileHistory(FileHistory(pathsMap))
.apply {
putUserData(FileHistorySpeedSearch.COMMIT_METADATA, revisions.associate { Pair(it.commit, it.metadata) })
}
}
val commits = revisions.map { GraphCommitImpl.createCommit(it.commit, emptyList(), it.metadata.timestamp) }
val refs = getFilteredRefs(dataPack)
val fakeDataPack = DataPack.build(commits, refs, mapOf(root to logProviders[root]), storage, false)
val visibleGraph = createVisibleGraph(fakeDataPack, sortType, null,
null/*no need to filter here, since we do not have any extra commits in this pack*/)
return VisiblePack(fakeDataPack, visibleGraph, !isDone, filters)
.withFileHistory(FileHistory(revisions.associate { Pair(it.commit, it.path) }))
.apply {
putUserData(NO_PARENTS_INFO, true)
putUserData(FileHistorySpeedSearch.COMMIT_METADATA, revisions.associate { Pair(it.commit, it.metadata) })
}
}
private fun getFilteredRefs(dataPack: DataPack): Map<VirtualFile, CompressedRefs> {
val compressedRefs = dataPack.refsModel.allRefsByRoot[root] ?: CompressedRefs(emptySet(), storage)
return mapOf(Pair(root, compressedRefs))
}
private fun filterWithIndex(indexDataGetter: IndexDataGetter,
dataPack: DataPack,
oldVisiblePack: VisiblePack,
sortType: PermanentGraph.SortType,
filters: VcsLogFilterCollection,
isInitial: Boolean): VisiblePack {
val oldFileHistory = oldVisiblePack.fileHistory
if (isInitial) {
return filterWithIndex(indexDataGetter, dataPack, filters, sortType,
oldFileHistory.commitToRename,
FileHistory(emptyMap(), processedAdditionsDeletions = oldFileHistory.processedAdditionsDeletions))
}
val renames = collectRenamesFromProvider(oldFileHistory)
return filterWithIndex(indexDataGetter, dataPack, filters, sortType, renames.union(oldFileHistory.commitToRename), oldFileHistory)
}
private fun filterWithIndex(indexDataGetter: IndexDataGetter,
dataPack: DataPack,
filters: VcsLogFilterCollection,
sortType: PermanentGraph.SortType,
oldRenames: MultiMap<UnorderedPair<Int>, Rename>,
oldFileHistory: FileHistory): VisiblePack {
val matchingHeads = vcsLogFilterer.getMatchingHeads(dataPack.refsModel, setOf(root), filters)
val data = indexDataGetter.createFileHistoryData(filePath).build(oldRenames)
val permanentGraph = dataPack.permanentGraph
if (permanentGraph !is PermanentGraphImpl) {
val visibleGraph = createVisibleGraph(dataPack, sortType, matchingHeads, data.getCommits())
val fileHistory = FileHistory(data.buildPathsMap())
return VisiblePack(dataPack, visibleGraph, false, filters).withFileHistory(fileHistory)
}
if (matchingHeads.matchesNothing() || data.isEmpty) {
return VisiblePack.EMPTY
}
val commit = (hash ?: getHead(dataPack))?.let { storage.getCommitIndex(it, root) }
val historyBuilder = FileHistoryBuilder(commit, filePath, data, oldFileHistory,
removeTrivialMerges = FileHistoryBuilder.isRemoveTrivialMerges,
refine = FileHistoryBuilder.isRefine)
val visibleGraph = permanentGraph.createVisibleGraph(sortType, matchingHeads, data.getCommits(), historyBuilder)
val fileHistory = historyBuilder.fileHistory
return VisiblePack(dataPack, visibleGraph, fileHistory.unmatchedAdditionsDeletions.isNotEmpty(), filters).withFileHistory(fileHistory)
}
private fun collectRenamesFromProvider(fileHistory: FileHistory): MultiMap<UnorderedPair<Int>, Rename> {
if (fileHistory.unmatchedAdditionsDeletions.isEmpty()) return MultiMap.empty()
TraceManager.getTracer("vcs").spanBuilder("collecting renames").useWithScope {
val handler = logProviders[root]?.fileHistoryHandler ?: return MultiMap.empty()
val renames = fileHistory.unmatchedAdditionsDeletions.mapNotNull {
val parentHash = storage.getCommitId(it.parent)!!.hash
val childHash = storage.getCommitId(it.child)!!.hash
if (it.isAddition) handler.getRename(root, it.filePath, parentHash, childHash)
else handler.getRename(root, it.filePath, childHash, parentHash)
}.map { r ->
Rename(r.filePath1, r.filePath2, storage.getCommitIndex(r.hash1, root), storage.getCommitIndex(r.hash2, root))
}
it.setAttribute("renamesSize", renames.size.toLong())
it.setAttribute("numberOfAdditionDeletions",fileHistory.unmatchedAdditionsDeletions.size.toLong())
val result = MultiMap<UnorderedPair<Int>, Rename>()
renames.forEach { result.putValue(it.commits, it) }
return result
}
}
private fun getHead(pack: DataPack): Hash? {
return pack.refsModel.findBranch(VcsLogUtil.HEAD, root)?.commitHash
}
}
private fun getHash(filters: VcsLogFilterCollection): Hash? {
val fileHistoryFilter = getStructureFilter(filters) as? VcsLogFileHistoryFilter
if (fileHistoryFilter != null) {
return fileHistoryFilter.hash
}
val revisionFilter = filters.get(VcsLogFilterCollection.REVISION_FILTER)
return revisionFilter?.heads?.singleOrNull()?.hash
}
companion object {
private val LOG = logger<FileHistoryFilterer>()
@JvmField
val NO_PARENTS_INFO = Key.create<Boolean>("NO_PARENTS_INFO")
private fun getStructureFilter(filters: VcsLogFilterCollection) = filters.detailsFilters.singleOrNull() as? VcsLogStructureFilter
fun getFilePath(filters: VcsLogFilterCollection): FilePath? {
val filter = getStructureFilter(filters) ?: return null
return filter.files.singleOrNull()
}
@JvmStatic
fun createFilters(path: FilePath,
revision: Hash?,
root: VirtualFile,
showAllBranches: Boolean): VcsLogFilterCollection {
val fileFilter = VcsLogFileHistoryFilter(path, revision)
val revisionFilter = when {
showAllBranches -> null
revision != null -> VcsLogFilterObject.fromCommit(CommitId(revision, root))
else -> VcsLogFilterObject.fromBranch(VcsLogUtil.HEAD)
}
return VcsLogFilterObject.collection(fileFilter, revisionFilter)
}
private fun createVisibleGraph(dataPack: DataPack,
sortType: PermanentGraph.SortType,
matchingHeads: Set<Int>?,
matchingCommits: Set<Int>?): VisibleGraph<Int> {
if (matchingHeads.matchesNothing() || matchingCommits.matchesNothing()) {
return EmptyVisibleGraph.getInstance()
}
return dataPack.permanentGraph.createVisibleGraph(sortType, matchingHeads, matchingCommits)
}
}
}
private fun <K : Any?, V : Any?> MultiMap<K, V>.union(map: MultiMap<K, V>): MultiMap<K, V> {
if (isEmpty) {
return map
}
if (map.isEmpty) {
return this
}
val result = MultiMap<K, V>()
result.putAllValues(this)
result.putAllValues(map)
return result
}
private data class CommitMetadataWithPath(val commit: Int, val metadata: VcsCommitMetadata, val path: MaybeDeletedFilePath)
private abstract class FileHistoryTask(val vcs: AbstractVcs, val filePath: FilePath, val hash: Hash?, val indicator: ProgressIndicator) {
private val revisionNumber = if (hash != null) VcsLogUtil.convertToRevisionNumber(hash) else null
private val future: Future<*>
private val _revisions = ConcurrentLinkedQueue<CommitMetadataWithPath>()
private val exception = AtomicReference<VcsException>()
@Volatile
private var lastSize = 0
val isCancelled get() = indicator.isCanceled
init {
future = AppExecutorUtil.getAppExecutorService().submit {
ProgressManager.getInstance().runProcess(Runnable {
try {
VcsCachingHistory.collect(vcs, filePath, revisionNumber) { revision ->
_revisions.add(createCommitMetadataWithPath(revision))
}
}
catch (e: VcsException) {
exception.set(e)
}
}, indicator)
}
}
protected abstract fun createCommitMetadataWithPath(revision: VcsFileRevision): CommitMetadataWithPath
@Throws(VcsException::class)
fun waitForRevisions(): Pair<List<CommitMetadataWithPath>, Boolean> {
throwOnError()
while (_revisions.size == lastSize) {
try {
future.get(100, TimeUnit.MILLISECONDS)
ProgressManager.checkCanceled()
throwOnError()
return Pair(getRevisionsSnapshot(), true)
}
catch (_: TimeoutException) {
}
}
return Pair(getRevisionsSnapshot(), false)
}
private fun getRevisionsSnapshot(): List<CommitMetadataWithPath> {
val list = _revisions.toList()
lastSize = list.size
return list
}
@Throws(VcsException::class)
private fun throwOnError() {
if (exception.get() != null) throw VcsException(exception.get())
}
fun cancel(wait: Boolean) {
indicator.cancel()
if (wait) {
try {
future.get(20, TimeUnit.MILLISECONDS)
}
catch (_: Throwable) {
}
}
}
}
|
apache-2.0
|
b7505aff0463724c7920ba913186c5be
| 43.11165 | 158 | 0.682734 | 5.420221 | false | false | false | false |
JetBrains/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddAnnotationTargetFix.kt
|
1
|
10703
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.*
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import org.jetbrains.kotlin.asJava.LightClassUtil
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget
import org.jetbrains.kotlin.descriptors.annotations.KotlinTarget
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors.WRONG_ANNOTATION_TARGET
import org.jetbrains.kotlin.diagnostics.Errors.WRONG_ANNOTATION_TARGET_WITH_USE_SITE_TARGET
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgressIfEdt
import org.jetbrains.kotlin.idea.util.runOnExpectAndAllActuals
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.AnnotationChecker
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.BindingTraceContext
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.constants.EnumValue
import org.jetbrains.kotlin.resolve.constants.TypedArrayValue
import org.jetbrains.kotlin.resolve.descriptorUtil.firstArgument
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class AddAnnotationTargetFix(annotationEntry: KtAnnotationEntry) : KotlinQuickFixAction<KtAnnotationEntry>(annotationEntry) {
override fun getText() = KotlinBundle.message("fix.add.annotation.target")
override fun getFamilyName() = text
override fun startInWriteAction(): Boolean = false
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val annotationEntry = element ?: return
val (annotationClass, annotationClassDescriptor) = annotationEntry.toAnnotationClass() ?: return
val requiredAnnotationTargets = annotationEntry.getRequiredAnnotationTargets(annotationClass, annotationClassDescriptor, project)
if (requiredAnnotationTargets.isEmpty()) return
annotationClass.runOnExpectAndAllActuals(useOnSelf = true) {
val ktClass = it.safeAs<KtClass>() ?: return@runOnExpectAndAllActuals
runWriteAction {
val psiFactory = KtPsiFactory(project)
ktClass.addAnnotationTargets(requiredAnnotationTargets, psiFactory)
}
}
}
companion object : KotlinSingleIntentionActionFactory() {
private fun KtAnnotationEntry.toAnnotationClass(): Pair<KtClass, ClassDescriptor>? {
val context = analyze(BodyResolveMode.PARTIAL)
val annotationDescriptor = context[BindingContext.ANNOTATION, this] ?: return null
val annotationTypeDescriptor = annotationDescriptor.type.constructor.declarationDescriptor as? ClassDescriptor ?: return null
val annotationClass = (DescriptorToSourceUtils.descriptorToDeclaration(annotationTypeDescriptor) as? KtClass)?.takeIf {
it.isAnnotation() && it.isWritable
} ?: return null
return annotationClass to annotationTypeDescriptor
}
override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtAnnotationEntry>? {
if (diagnostic.factory != WRONG_ANNOTATION_TARGET && diagnostic.factory != WRONG_ANNOTATION_TARGET_WITH_USE_SITE_TARGET) {
return null
}
val entry = diagnostic.psiElement as? KtAnnotationEntry ?: return null
val (annotationClass, annotationClassDescriptor) = entry.toAnnotationClass() ?: return null
if (entry.getRequiredAnnotationTargets(annotationClass, annotationClassDescriptor, entry.project).isEmpty()) return null
return AddAnnotationTargetFix(entry)
}
}
}
private fun KtAnnotationEntry.getRequiredAnnotationTargets(
annotationClass: KtClass,
annotationClassDescriptor: ClassDescriptor,
project: Project
): List<KotlinTarget> {
val ignoredTargets = if (annotationClassDescriptor.hasRequiresOptInAnnotation()) {
listOf(AnnotationTarget.EXPRESSION, AnnotationTarget.FILE, AnnotationTarget.TYPE, AnnotationTarget.TYPE_PARAMETER)
.map { it.name }
.toSet()
} else emptySet()
val existingTargets = annotationClassDescriptor.annotations
.firstOrNull { it.fqName == StandardNames.FqNames.target }
?.firstArgument()
.safeAs<TypedArrayValue>()
?.value
?.mapNotNull { it.safeAs<EnumValue>()?.enumEntryName?.asString() }
?.toSet()
.orEmpty()
val validTargets = AnnotationTarget.values()
.map { it.name }
.minus(ignoredTargets)
.minus(existingTargets)
.toSet()
if (validTargets.isEmpty()) return emptyList()
val requiredTargets = getActualTargetList()
if (requiredTargets.isEmpty()) return emptyList()
val searchScope = GlobalSearchScope.allScope(project)
return project.runSynchronouslyWithProgressIfEdt(KotlinBundle.message("progress.looking.up.add.annotation.usage"), true) {
val otherReferenceRequiredTargets = ReferencesSearch.search(annotationClass, searchScope).mapNotNull { reference ->
if (reference.element is KtNameReferenceExpression) {
// Kotlin annotation
reference.element.getNonStrictParentOfType<KtAnnotationEntry>()?.takeIf { it != this }?.getActualTargetList()
} else {
// Java annotation
(reference.element.parent as? PsiAnnotation)?.getActualTargetList()
}
}.flatten().toSet()
(requiredTargets + otherReferenceRequiredTargets).asSequence()
.distinct()
.filter { it.name in validTargets }
.sorted()
.toList()
} ?: emptyList()
}
private fun ClassDescriptor.hasRequiresOptInAnnotation() = annotations.any { it.fqName == FqName("kotlin.RequiresOptIn") }
private fun PsiAnnotation.getActualTargetList(): List<KotlinTarget> {
val target = when (val annotated = this.parent.parent) {
is PsiClass -> KotlinTarget.CLASS
is PsiMethod -> when {
annotated.isConstructor -> KotlinTarget.CONSTRUCTOR
else -> KotlinTarget.FUNCTION
}
is PsiExpression -> KotlinTarget.EXPRESSION
is PsiField -> KotlinTarget.FIELD
is PsiLocalVariable -> KotlinTarget.LOCAL_VARIABLE
is PsiParameter -> KotlinTarget.VALUE_PARAMETER
is PsiTypeParameterList -> KotlinTarget.TYPE
is PsiReferenceList -> KotlinTarget.TYPE_PARAMETER
else -> null
}
return listOfNotNull(target)
}
private fun KtAnnotationEntry.getActualTargetList(): List<KotlinTarget> {
val annotatedElement = getStrictParentOfType<KtModifierList>()?.owner as? KtElement
?: getStrictParentOfType<KtAnnotatedExpression>()?.baseExpression
?: getStrictParentOfType<KtFile>()
?: return emptyList()
val targetList = AnnotationChecker.getActualTargetList(annotatedElement, null, BindingTraceContext().bindingContext)
val useSiteTarget = this.useSiteTarget ?: return targetList.defaultTargets
val annotationUseSiteTarget = useSiteTarget.getAnnotationUseSiteTarget()
val target = KotlinTarget.USE_SITE_MAPPING[annotationUseSiteTarget] ?: return emptyList()
if (annotationUseSiteTarget == AnnotationUseSiteTarget.FIELD) {
if (KotlinTarget.MEMBER_PROPERTY !in targetList.defaultTargets && KotlinTarget.TOP_LEVEL_PROPERTY !in targetList.defaultTargets) {
return emptyList()
}
val property = annotatedElement as? KtProperty
if (property != null && (LightClassUtil.getLightClassPropertyMethods(property).backingField == null || property.hasDelegate())) {
return emptyList()
}
} else {
if (target !in with(targetList) { defaultTargets + canBeSubstituted + onlyWithUseSiteTarget }) {
return emptyList()
}
}
return listOf(target)
}
private fun KtClass.addAnnotationTargets(annotationTargets: List<KotlinTarget>, psiFactory: KtPsiFactory) {
val retentionAnnotationName = StandardNames.FqNames.retention.shortName().asString()
if (annotationTargets.any { it == KotlinTarget.EXPRESSION }) {
val retentionEntry = annotationEntries.firstOrNull { it.typeReference?.text == retentionAnnotationName }
val newRetentionEntry = psiFactory.createAnnotationEntry(
"@$retentionAnnotationName(${StandardNames.FqNames.annotationRetention.shortName()}.${AnnotationRetention.SOURCE.name})"
)
if (retentionEntry == null) {
addAnnotationEntry(newRetentionEntry)
} else {
retentionEntry.replace(newRetentionEntry)
}
}
val targetAnnotationName = StandardNames.FqNames.target.shortName().asString()
val targetAnnotationEntry = annotationEntries.find { it.typeReference?.text == targetAnnotationName } ?: run {
val text = "@$targetAnnotationName${annotationTargets.toArgumentListString()}"
addAnnotationEntry(psiFactory.createAnnotationEntry(text))
return
}
val valueArgumentList = targetAnnotationEntry.valueArgumentList
if (valueArgumentList == null) {
val text = annotationTargets.toArgumentListString()
targetAnnotationEntry.add(psiFactory.createCallArguments(text))
} else {
val arguments = targetAnnotationEntry.valueArguments.mapNotNull { it.getArgumentExpression()?.text }
for (target in annotationTargets) {
val text = target.asNameString()
if (text !in arguments) valueArgumentList.addArgument(psiFactory.createArgument(text))
}
}
}
private fun List<KotlinTarget>.toArgumentListString() = joinToString(separator = ", ", prefix = "(", postfix = ")") { it.asNameString() }
private fun KotlinTarget.asNameString() = "${StandardNames.FqNames.annotationTarget.shortName().asString()}.$name"
|
apache-2.0
|
f64d8ccdd2a8907fdf0ddd6ea2071942
| 47.211712 | 158 | 0.730356 | 5.455148 | false | false | false | false |
apollographql/apollo-android
|
apollo-http-cache/src/main/kotlin/com/apollographql/apollo3/cache/http/internal/DiskLruCache.kt
|
1
|
35092
|
/*
* 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 com.apollographql.apollo3.cache.http.internal
import com.apollographql.apollo3.cache.http.internal.DiskLruCache.Editor
import okio.BufferedSink
import okio.FileSystem
import okio.Path.Companion.toOkioPath
import okio.Sink
import okio.Source
import okio.blackholeSink
import okio.buffer
import java.io.Closeable
import java.io.EOFException
import java.io.File
import java.io.FileNotFoundException
import java.io.Flushable
import java.io.IOException
import java.util.concurrent.Executor
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
import java.util.regex.Pattern
/**
* 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 `Integer.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.
*
*
* Copied from OkHttp 3.14.2: https://github.com/square/okhttp/blob/
* b8b6ee831c65208940c741f8e091ff02425566d5/
* okhttp/src/main/java/okhttp3/internal/cache/DiskLruCache.java
*/
internal class DiskLruCache(
/*
* 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.
*/
private val fileSystem: FileSystem,
/** Returns the directory where this cache stores its data. */
private val directory: File,
private val appVersion: Int, valueCount: Int, maxSize: Long,
executor: Executor,
) : Closeable, Flushable {
private val journalFile: File = File(directory, JOURNAL_FILE)
private val journalFileTmp: File
private val journalFileBackup: File
private var maxSize: Long
val valueCount: Int
private var size: Long = 0
var journalWriter: BufferedSink? = null
val lruEntries = LinkedHashMap<String, Entry?>(0, 0.75f, true)
var redundantOpCount = 0
var hasJournalErrors = false
// Must be read and written when synchronized on 'this'.
var initialized = false
/** Returns true if this cache has been closed. */
@get:Synchronized
var isClosed = false
var mostRecentTrimFailed = false
var mostRecentRebuildFailed = false
/**
* To differentiate between old and current snapshots, each entry is given a sequence number each
* time an edit is committed. A snapshot is stale if its sequence number is not equal to its
* entry's sequence number.
*/
private var nextSequenceNumber: Long = 0
/** Used to run 'cleanupRunnable' for journal rebuilds. */
private val executor: Executor
private val cleanupRunnable: Runnable = object : Runnable {
override fun run() {
synchronized(this@DiskLruCache) {
if (!initialized || isClosed) {
return // Nothing to do
}
try {
trimToSize()
} catch (ignored: IOException) {
mostRecentTrimFailed = true
}
try {
if (journalRebuildRequired()) {
rebuildJournal()
redundantOpCount = 0
}
} catch (e: IOException) {
mostRecentRebuildFailed = true
journalWriter = blackholeSink().buffer()
}
}
}
}
@Synchronized
@Throws(IOException::class)
fun initialize() {
assert(Thread.holdsLock(this))
if (initialized) {
return // Already initialized.
}
// If a bkp 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.rename(journalFileBackup, journalFile)
}
}
// Prefer to pick up where we left off.
if (fileSystem.exists(journalFile)) {
try {
readJournal()
processJournal()
initialized = true
return
} catch (journalIsCorrupt: IOException) {
//logger.w("DiskLruCache " + directory + " is corrupt: "
// + journalIsCorrupt.getMessage() + ", removing", journalIsCorrupt);
}
// 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 {
isClosed = false
}
}
rebuildJournal()
initialized = true
}
@Throws(IOException::class)
private fun readJournal() {
fileSystem.source(journalFile).buffer().use { source ->
val magic = source.readUtf8LineStrict()
val version = source.readUtf8LineStrict()
val appVersionString = source.readUtf8LineStrict()
val valueCountString = source.readUtf8LineStrict()
val blank = source.readUtf8LineStrict()
if (MAGIC != magic
|| VERSION_1 != version
|| appVersion.toString() != appVersionString
|| valueCount.toString() != valueCountString
|| "" != blank) {
throw IOException("unexpected journal header: [" + magic + ", " + version + ", "
+ valueCountString + ", " + blank + "]")
}
var lineCount = 0
while (true) {
try {
readJournalLine(source.readUtf8LineStrict())
lineCount++
} catch (endOfJournal: EOFException) {
break
}
}
redundantOpCount = lineCount - lruEntries.size
// If we ended on a truncated line, rebuild the journal before appending to it.
if (!source.exhausted()) {
rebuildJournal()
} else {
journalWriter = newJournalWriter()
}
}
}
@Throws(FileNotFoundException::class)
private fun newJournalWriter(): BufferedSink {
val fileSink = fileSystem.appendingSink(journalFile)
val faultHidingSink: Sink = object : FaultHidingSink(fileSink) {
override fun onException(e: IOException?) {
assert(Thread.holdsLock(this@DiskLruCache))
hasJournalErrors = true
}
}
return faultHidingSink.buffer()
}
@Throws(IOException::class)
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)
}
var entry = lruEntries[key]
if (entry == null) {
entry = Entry(key)
lruEntries[key] = entry
}
if (secondSpace != -1 && firstSpace == CLEAN.length && line.startsWith(CLEAN)) {
val parts = line.substring(secondSpace + 1).split(" ").toTypedArray()
entry.readable = true
entry.currentEditor = null
entry.setLengths(parts)
} else if (secondSpace == -1 && firstSpace == DIRTY.length && line.startsWith(DIRTY)) {
entry.currentEditor = Editor(entry)
} else if (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 initial size and collects garbage as a part of opening the cache. Dirty entries
* are assumed to be inconsistent and will be deleted.
*/
@Throws(IOException::class)
private fun processJournal() {
fileSystem.delete(journalFileTmp)
val i = lruEntries.values.iterator()
while (i.hasNext()) {
val entry = i.next()
if (entry!!.currentEditor == null) {
for (t in 0 until valueCount) {
size += entry.lengths[t]
}
} else {
entry.currentEditor = null
for (t in 0 until valueCount) {
fileSystem.delete(entry.cleanFiles[t])
fileSystem.delete(entry.dirtyFiles[t])
}
i.remove()
}
}
}
/**
* Creates a new journal that omits redundant information. This replaces the current journal if it
* exists.
*/
@Synchronized
@Throws(IOException::class)
fun rebuildJournal() {
if (journalWriter != null) {
journalWriter!!.close()
}
fileSystem.sink(journalFileTmp).buffer().use { writer ->
writer.writeUtf8(MAGIC).writeByte('\n'.code)
writer.writeUtf8(VERSION_1).writeByte('\n'.code)
writer.writeDecimalLong(appVersion.toLong()).writeByte('\n'.code)
writer.writeDecimalLong(valueCount.toLong()).writeByte('\n'.code)
writer.writeByte('\n'.code)
for (entry in lruEntries.values) {
if (entry!!.currentEditor != null) {
writer.writeUtf8(DIRTY).writeByte(' '.code)
writer.writeUtf8(entry.key)
writer.writeByte('\n'.code)
} else {
writer.writeUtf8(CLEAN).writeByte(' '.code)
writer.writeUtf8(entry.key)
entry.writeLengths(writer)
writer.writeByte('\n'.code)
}
}
}
if (fileSystem.exists(journalFile)) {
fileSystem.rename(journalFile, journalFileBackup)
}
fileSystem.rename(journalFileTmp, journalFile)
fileSystem.delete(journalFileBackup)
journalWriter = newJournalWriter()
hasJournalErrors = false
mostRecentRebuildFailed = false
}
/**
* Returns a snapshot of the entry named `key`, or null if it doesn't exist is not currently
* readable. If a value is returned, it is moved to the head of the LRU queue.
*/
@Synchronized
@Throws(IOException::class)
operator fun get(key: String): Snapshot? {
initialize()
checkNotClosed()
validateKey(key)
val entry = lruEntries[key]
if (entry == null || !entry.readable) return null
val snapshot = entry.snapshot() ?: return null
redundantOpCount++
journalWriter!!.writeUtf8(READ).writeByte(' '.code).writeUtf8(key).writeByte('\n'.code)
if (journalRebuildRequired()) {
executor.execute(cleanupRunnable)
}
return snapshot
}
/**
* Returns an editor for the entry named `key`, or null if another edit is in progress.
*/
@Throws(IOException::class)
fun edit(key: String): Editor? {
return edit(key, ANY_SEQUENCE_NUMBER)
}
@Synchronized
@Throws(IOException::class)
fun edit(key: String, expectedSequenceNumber: Long): Editor? {
initialize()
checkNotClosed()
validateKey(key)
var entry = lruEntries[key]
if (expectedSequenceNumber != ANY_SEQUENCE_NUMBER && (entry == null
|| entry.sequenceNumber != expectedSequenceNumber)) {
return null // Snapshot is stale.
}
if (entry != null && entry.currentEditor != null) {
return null // Another edit is in progress.
}
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!
executor.execute(cleanupRunnable)
return null
}
// Flush the journal before creating files to prevent file leaks.
journalWriter!!.writeUtf8(DIRTY).writeByte(' '.code).writeUtf8(key).writeByte('\n'.code)
journalWriter!!.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
}
/**
* Changes the maximum number of bytes the cache can store and queues a job to trim the existing
* store, if necessary.
*/
@Synchronized
fun setMaxSize(maxSize: Long) {
this.maxSize = maxSize
if (initialized) {
executor.execute(cleanupRunnable)
}
}
/**
* 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
@Throws(IOException::class)
fun size(): Long {
initialize()
return size
}
@Synchronized
@Throws(IOException::class)
fun completeEdit(editor: Editor, success: Boolean) {
val entry = editor.entry
check(entry.currentEditor == editor)
// If this edit is creating the entry for the first time, every index must have a value.
if (success && !entry.readable) {
for (i in 0 until valueCount) {
if (!editor.written!![i]) {
editor.abort()
throw IllegalStateException("Newly created entry didn't create value for index $i")
}
if (!fileSystem.exists(entry.dirtyFiles[i])) {
editor.abort()
return
}
}
}
for (i in 0 until valueCount) {
val dirty = entry.dirtyFiles[i]
if (success) {
if (fileSystem.exists(dirty)) {
val clean = entry.cleanFiles[i]
fileSystem.rename(dirty, clean)
val oldLength = entry.lengths[i]
val newLength = fileSystem.size(clean)
entry.lengths[i] = newLength
size = size - oldLength + newLength
}
} else {
fileSystem.delete(dirty)
}
}
redundantOpCount++
entry.currentEditor = null
if (entry.readable || success) {
entry.readable = true
journalWriter!!.writeUtf8(CLEAN).writeByte(' '.code)
journalWriter!!.writeUtf8(entry.key)
entry.writeLengths(journalWriter)
journalWriter!!.writeByte('\n'.code)
if (success) {
entry.sequenceNumber = nextSequenceNumber++
}
} else {
lruEntries.remove(entry.key)
journalWriter!!.writeUtf8(REMOVE).writeByte(' '.code)
journalWriter!!.writeUtf8(entry.key)
journalWriter!!.writeByte('\n'.code)
}
journalWriter!!.flush()
if (size > maxSize || journalRebuildRequired()) {
executor.execute(cleanupRunnable)
}
}
/**
* We only rebuild the journal when it will halve the size of the journal and eliminate at least
* 2000 ops.
*/
fun journalRebuildRequired(): Boolean {
val redundantOpCompactThreshold = 2000
return (redundantOpCount >= redundantOpCompactThreshold
&& redundantOpCount >= lruEntries.size)
}
/**
* 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
@Throws(IOException::class)
fun remove(key: String): Boolean {
initialize()
checkNotClosed()
validateKey(key)
val entry = lruEntries[key] ?: return false
val removed = removeEntry(entry)
if (removed && size <= maxSize) mostRecentTrimFailed = false
return removed
}
@Throws(IOException::class)
fun removeEntry(entry: Entry?): Boolean {
if (entry!!.currentEditor != null) {
entry.currentEditor!!.detach() // Prevent the edit from completing normally.
}
for (i in 0 until valueCount) {
fileSystem.delete(entry.cleanFiles[i])
size -= entry.lengths[i]
entry.lengths[i] = 0
}
redundantOpCount++
journalWriter!!.writeUtf8(REMOVE).writeByte(' '.code).writeUtf8(entry.key).writeByte('\n'.code)
lruEntries.remove(entry.key)
if (journalRebuildRequired()) {
executor.execute(cleanupRunnable)
}
return true
}
@Synchronized
private fun checkNotClosed() {
check(!isClosed) { "cache is closed" }
}
/** Force buffered operations to the filesystem. */
@Synchronized
@Throws(IOException::class)
override fun flush() {
if (!initialized) return
checkNotClosed()
trimToSize()
journalWriter!!.flush()
}
/** Closes this cache. Stored values will remain on the filesystem. */
@Synchronized
@Throws(IOException::class)
override fun close() {
if (!initialized || isClosed) {
isClosed = true
return
}
// Copying for safe iteration.
for (entry in lruEntries.values.toTypedArray()) {
if (entry?.currentEditor != null) {
entry.currentEditor!!.abort()
}
}
trimToSize()
journalWriter!!.close()
journalWriter = null
isClosed = true
}
@Throws(IOException::class)
fun trimToSize() {
while (size > maxSize) {
val toEvict = lruEntries.values.iterator().next()
removeEntry(toEvict)
}
mostRecentTrimFailed = 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.
*/
@Throws(IOException::class)
fun delete() {
close()
fileSystem.deleteRecursively(directory)
}
/**
* Deletes all stored values from the cache. In-flight edits will complete normally but their
* values will not be stored.
*/
@Synchronized
@Throws(IOException::class)
fun evictAll() {
initialize()
// Copying for safe iteration.
for (entry in lruEntries.values.toTypedArray()) {
removeEntry(entry)
}
mostRecentTrimFailed = false
}
private fun validateKey(key: String) {
val matcher = LEGAL_KEY_PATTERN.matcher(key)
require(matcher.matches()) { "keys must match regex [a-z0-9_-]{1,120}: \"$key\"" }
}
/**
* Returns an iterator over the cache's current entries. This iterator doesn't throw `ConcurrentModificationException`, but if new entries are added while iterating, those new
* entries will not be returned by the iterator. If existing entries are removed during iteration,
* they will be absent (unless they were already returned).
*
*
* If there are I/O problems during iteration, this iterator fails silently. For example, if
* the hosting filesystem becomes unreachable, the iterator will omit elements rather than
* throwing exceptions.
*
*
* **The caller must [close][Snapshot.close]** each snapshot returned by
* [Iterator.next]. Failing to do so leaks open files!
*
*
* The returned iterator supports [Iterator.remove].
*/
@Synchronized
@Throws(IOException::class)
fun snapshots(): MutableIterator<Snapshot> {
initialize()
return object : MutableIterator<Snapshot> {
/** Iterate a copy of the entries to defend against concurrent modification errors. */
val delegate: Iterator<Entry?> = ArrayList(lruEntries.values).iterator()
/** The snapshot to return from [.next]. Null if we haven't computed that yet. */
var nextSnapshot: Snapshot? = null
/** The snapshot to remove with [.remove]. Null if removal is illegal. */
var removeSnapshot: Snapshot? = null
override fun hasNext(): Boolean {
if (nextSnapshot != null) return true
synchronized(this@DiskLruCache) {
// If the cache is closed, truncate the iterator.
if (isClosed) return false
while (delegate.hasNext()) {
val entry = delegate.next()
val snapshot = entry!!.snapshot() ?: continue
// Evicted since we copied the entries.
nextSnapshot = snapshot
return true
}
}
return false
}
override fun next(): Snapshot {
if (!hasNext()) throw NoSuchElementException()
removeSnapshot = nextSnapshot
nextSnapshot = null
return removeSnapshot!!
}
override fun remove() {
checkNotNull(removeSnapshot) { "remove() before next()" }
try {
[email protected](removeSnapshot!!.key)
} catch (ignored: IOException) {
// Nothing useful to do here. We failed to remove from the cache. Most likely that's
// because we couldn't update the journal, but the cached entry will still be gone.
} finally {
removeSnapshot = null
}
}
}
}
@Suppress("UNUSED_PARAMETER")
fun closeQuietly(closeable: Closeable?, name: String?) {
try {
closeable?.close()
} catch (e: Exception) {
//logger.w(e, "Failed to close " + name);
}
}
/** A snapshot of the values for an entry. */
inner class Snapshot internal constructor(val key: String, private val sequenceNumber: Long, private val sources: Array<Source>, private val lengths: LongArray) : Closeable {
fun key(): String {
return key
}
/**
* Returns an editor for this snapshot's entry, or null if either the entry has changed since
* this snapshot was created or if another edit is in progress.
*/
@Throws(IOException::class)
fun edit(): Editor? {
return [email protected](key, sequenceNumber)
}
/** Returns the unbuffered stream with the value for `index`. */
fun getSource(index: Int): Source {
return sources[index]
}
/** Returns the byte length of the value for `index`. */
fun getLength(index: Int): Long {
return lengths[index]
}
override fun close() {
for (`in` in sources) {
closeQuietly(`in`, "source")
}
}
}
/** Edits the values for an entry. */
inner class Editor internal constructor(val entry: Entry) {
val written: BooleanArray? = if (entry.readable) null else BooleanArray(valueCount)
private var done = false
/**
* Prevents this editor from completing normally. This is necessary either when the edit causes
* an I/O error, or if the target entry is evicted while this editor is active. In either case
* we delete the editor's created files and prevent new files from being created. Note that once
* an editor has been detached it is possible for another editor to edit the entry.
*/
fun detach() {
if (entry.currentEditor == this) {
for (i in 0 until valueCount) {
try {
fileSystem.delete(entry.dirtyFiles[i])
} catch (e: IOException) {
// This file is potentially leaked. Not much we can do about that.
}
}
entry.currentEditor = null
}
}
/**
* Returns an unbuffered input stream to read the last committed value, or null if no value has
* been committed.
*/
fun newSource(index: Int): Source? {
synchronized(this@DiskLruCache) {
check(!done)
return if (!entry.readable || entry.currentEditor != this) {
null
} else try {
fileSystem.source(entry.cleanFiles[index])
} catch (e: FileNotFoundException) {
null
}
}
}
/**
* Returns a new unbuffered output stream to write the value at `index`. If the underlying
* output stream encounters errors when writing to the filesystem, this edit will be aborted
* when [.commit] is called. The returned output stream does not throw IOExceptions.
*/
fun newSink(index: Int): Sink {
synchronized(this@DiskLruCache) {
check(!done)
if (entry.currentEditor != this) {
return blackholeSink()
}
if (!entry.readable) {
written!![index] = true
}
val dirtyFile = entry.dirtyFiles[index]
val sink: Sink? = try {
fileSystem.sink(dirtyFile)
} catch (e: FileNotFoundException) {
return blackholeSink()
}
return object : FaultHidingSink(sink) {
override fun onException(e: IOException?) {
synchronized(this@DiskLruCache) { detach() }
}
}
}
}
/**
* Commits this edit so it is visible to readers. This releases the edit lock so another edit
* may be started on the same key.
*/
@Throws(IOException::class)
fun commit() {
synchronized(this@DiskLruCache) {
check(!done)
if (entry.currentEditor == this) {
completeEdit(this, true)
}
done = true
}
}
/**
* Aborts this edit. This releases the edit lock so another edit may be started on the same
* key.
*/
@Throws(IOException::class)
fun abort() {
synchronized(this@DiskLruCache) {
check(!done)
if (entry.currentEditor == this) {
completeEdit(this, false)
}
done = true
}
}
fun abortUnlessCommitted() {
synchronized(this@DiskLruCache) {
if (!done && entry.currentEditor == this) {
try {
completeEdit(this, false)
} catch (ignored: IOException) {
}
}
}
}
}
inner class Entry internal constructor(val key: String) {
/** Lengths of this entry's files. */
val lengths: LongArray = LongArray(valueCount)
val cleanFiles: Array<File>
val dirtyFiles: Array<File>
/** True if this entry has ever been published. */
var readable = false
/** The ongoing edit or null if this entry is not being edited. */
var currentEditor: Editor? = null
/** The sequence number of the most recently committed edit to this entry. */
var sequenceNumber: Long = 0
/** Set lengths using decimal numbers like "10123". */
@Throws(IOException::class)
fun setLengths(strings: Array<String>) {
if (strings.size != valueCount) {
throw invalidLengths(strings)
}
try {
for (i in strings.indices) {
lengths[i] = strings[i].toLong()
}
} catch (e: NumberFormatException) {
throw invalidLengths(strings)
}
}
/** Append space-prefixed lengths to `writer`. */
@Throws(IOException::class)
fun writeLengths(writer: BufferedSink?) {
for (length in lengths) {
writer!!.writeByte(' '.code).writeDecimalLong(length)
}
}
@Throws(IOException::class)
private fun invalidLengths(strings: Array<String>): IOException {
throw IOException("unexpected journal line: " + strings.contentToString())
}
/**
* Returns a snapshot of this entry. This opens all streams eagerly to guarantee that we see a
* single published snapshot. If we opened streams lazily then the streams could come from
* different edits.
*/
fun snapshot(): Snapshot? {
if (!Thread.holdsLock(this@DiskLruCache)) throw AssertionError()
val sources = arrayOfNulls<Source>(valueCount)
val lengths = lengths.clone() // Defensive copy since these can be zeroed out.
return try {
for (i in 0 until valueCount) {
sources[i] = fileSystem.source(cleanFiles[i])
}
@Suppress("UNCHECKED_CAST")
Snapshot(key, sequenceNumber, sources as Array<Source>, lengths)
} catch (e: FileNotFoundException) {
// A file must have been deleted manually!
var i = 0
while (i < valueCount) {
if (sources[i] != null) {
closeQuietly(sources[i], "file")
} else {
break
}
i++
}
// Since the entry is no longer valid, remove it so the metadata is accurate (i.e. the cache
// size.)
try {
removeEntry(this)
} catch (ignored: IOException) {
}
null
}
}
init {
val tmpCleanFiles = mutableListOf<File>()
val tmpDirtyFiles = mutableListOf<File>()
// 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)
tmpCleanFiles.add(File(directory, fileBuilder.toString()))
fileBuilder.append(".tmp")
tmpDirtyFiles.add(File(directory, fileBuilder.toString()))
fileBuilder.setLength(truncateTo)
}
cleanFiles = tmpCleanFiles.toTypedArray()
dirtyFiles = tmpDirtyFiles.toTypedArray()
}
}
companion object {
const val JOURNAL_FILE = "journal"
const val JOURNAL_FILE_TEMP = "journal.tmp"
const val JOURNAL_FILE_BACKUP = "journal.bkp"
const val MAGIC = "libcore.io.DiskLruCache"
const val VERSION_1 = "1"
const val ANY_SEQUENCE_NUMBER: Long = -1
val LEGAL_KEY_PATTERN = Pattern.compile("[a-z0-9_-]{1,120}")
private const val CLEAN = "CLEAN"
private const val DIRTY = "DIRTY"
private const val REMOVE = "REMOVE"
private const val READ = "READ"
/**
* 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 valueCount the number of values per cache entry. Must be positive.
* @param maxSize the maximum number of bytes this cache should use to store
*/
@JvmStatic
fun create(fileSystem: FileSystem, directory: File, appVersion: Int,
valueCount: Int, maxSize: Long): DiskLruCache {
require(maxSize > 0) { "maxSize <= 0" }
require(valueCount > 0) { "valueCount <= 0" }
// Use a single background thread to evict entries.
val executor: Executor = ThreadPoolExecutor(
0,
1,
60L,
TimeUnit.SECONDS,
LinkedBlockingQueue()
) { runnable ->
val result = Thread(runnable, "OkHttp DiskLruCache")
result.isDaemon = true
result
}
return DiskLruCache(fileSystem, directory, appVersion, valueCount, maxSize, executor)
}
}
init {
journalFileTmp = File(directory, JOURNAL_FILE_TEMP)
journalFileBackup = File(directory, JOURNAL_FILE_BACKUP)
this.valueCount = valueCount
this.maxSize = maxSize
this.executor = executor
}
}
private fun FileSystem.exists(file: File) = exists(file.toOkioPath())
private fun FileSystem.delete(file: File) = delete(file.toOkioPath())
private fun FileSystem.rename(from: File, to: File) = atomicMove(from.toOkioPath(), to.toOkioPath())
private fun FileSystem.source(file: File) = source(file.toOkioPath())
private fun FileSystem.appendingSink(file: File) = appendingSink(file.toOkioPath())
private fun FileSystem.sink(file: File): Sink {
if (!file.exists()) {
file.parentFile.mkdirs()
file.createNewFile()
}
return sink(file.toOkioPath())
}
private fun FileSystem.deleteRecursively(file: File) = deleteRecursively(file.toOkioPath())
private fun FileSystem.size(file: File) = metadata(file.toOkioPath()).size ?: 0
|
mit
|
8f7189bbf71790b17cac0641eef8a62f
| 33.003876 | 177 | 0.648153 | 4.484028 | false | false | false | false |
youdonghai/intellij-community
|
platform/diff-impl/tests/com/intellij/diff/util/DiffUtilTest.kt
|
1
|
3030
|
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.diff.util
import com.intellij.diff.DiffTestCase
import com.intellij.openapi.diff.DiffBundle
import com.intellij.util.containers.ContainerUtil
class DiffUtilTest : DiffTestCase() {
fun `test getSortedIndexes`() {
fun <T> doTest(vararg values: T, comparator: (T, T) -> Int) {
val list = values.toList()
val sortedIndexes = DiffUtil.getSortedIndexes(list, comparator)
val expected = ContainerUtil.sorted(list, comparator)
val actual = (0..values.size - 1).map { values[sortedIndexes[it]] }
assertOrderedEquals(actual, expected)
assertEquals(sortedIndexes.toSet().size, list.size)
}
doTest(1, 2, 3, 4, 5, 6, 7, 8) { v1, v2 -> v1 - v2 }
doTest(8, 7, 6, 5, 4, 3, 2, 1) { v1, v2 -> v1 - v2 }
doTest(1, 3, 5, 7, 8, 6, 4, 2) { v1, v2 -> v1 - v2 }
doTest(1, 2, 3, 4, 5, 6, 7, 8) { v1, v2 -> v2 - v1 }
doTest(8, 7, 6, 5, 4, 3, 2, 1) { v1, v2 -> v2 - v1 }
doTest(1, 3, 5, 7, 8, 6, 4, 2) { v1, v2 -> v2 - v1 }
}
fun `test merge conflict partially resolved confirmation message`() {
fun doTest(changes: Int, conflicts: Int, expected: String) {
val actual = DiffBundle.message("merge.dialog.apply.partially.resolved.changes.confirmation.message", changes, conflicts)
assertTrue(actual.startsWith(expected), actual)
}
doTest(1, 0, "There is one change left")
doTest(0, 1, "There is one conflict left")
doTest(1, 1, "There is one change and one conflict left")
doTest(2, 0, "There are 2 changes left")
doTest(0, 2, "There are 2 conflicts left")
doTest(2, 2, "There are 2 changes and 2 conflicts left")
doTest(1, 2, "There is one change and 2 conflicts left")
doTest(2, 1, "There are 2 changes and one conflict left")
doTest(2, 3, "There are 2 changes and 3 conflicts left")
}
}
|
apache-2.0
|
023d96bc4bf4041bfaece926097ba4b8
| 36.407407 | 127 | 0.678218 | 3.50289 | false | true | false | false |
ursjoss/sipamato
|
common/common-wicket/src/test/kotlin/ch/difty/scipamato/common/web/model/CodeLikeModelTest.kt
|
2
|
1437
|
package ch.difty.scipamato.common.web.model
import ch.difty.scipamato.common.entity.CodeClassId
import ch.difty.scipamato.common.entity.CodeLike
import ch.difty.scipamato.common.persistence.CodeLikeService
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import org.amshove.kluent.shouldBeEqualTo
import org.amshove.kluent.shouldContainAll
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.fail
private const val LANG_CODE = "en"
private val CC_ID = CodeClassId.CC1
@Suppress("SpellCheckingInspection")
internal class CodeLikeModelTest {
private val cclMock = mockk<CodeLike>()
private val serviceMock = mockk<CodeLikeService<CodeLike>>()
private val ccls = listOf(cclMock, cclMock)
private val model = object : CodeLikeModel<CodeLike, CodeLikeService<CodeLike>>(CC_ID, LANG_CODE, serviceMock) {
override fun injectThis() {
// no-op
}
}
@Test
fun canGetCodeClass() {
model.codeClassId shouldBeEqualTo CC_ID
}
@Test
fun canGetLanguageCode() {
model.languageCode shouldBeEqualTo LANG_CODE
}
@Test
fun modelObject_gotCodeClassesFromService() {
every { serviceMock.findCodesOfClass(CC_ID, LANG_CODE) } returns ccls
model.getObject()?.shouldContainAll(listOf(cclMock, cclMock)) ?: fail("should have list as object")
verify { serviceMock.findCodesOfClass(CC_ID, LANG_CODE) }
}
}
|
gpl-3.0
|
fe5f9f5f4bdfa1480751e98e42c20743
| 29.574468 | 116 | 0.727209 | 4.02521 | false | true | false | false |
CORDEA/MackerelClient
|
app/src/main/java/jp/cordea/mackerelclient/view/CharCircleView.kt
|
1
|
1517
|
package jp.cordea.mackerelclient.view
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Typeface
import android.util.AttributeSet
import android.view.View
import androidx.core.content.ContextCompat
import jp.cordea.mackerelclient.R
class CharCircleView(context: Context, attrs: AttributeSet?) : View(context, attrs) {
var char: Char = 'U'
set(value) {
field = value
invalidate()
}
private val colorSet: Map<Char, Int> = mapOf(
'C' to R.color.statusCritical,
'O' to R.color.statusOk,
'W' to R.color.statusWarning,
'U' to R.color.statusUnknown
)
private val paint = Paint()
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
paint.reset()
paint.color = ContextCompat.getColor(context, colorSet[char] ?: R.color.statusUnknown)
paint.isAntiAlias = true
val size = width / 2.0f
canvas.drawCircle(size, size, size, paint)
paint.textSize = resources.getDimension(R.dimen.char_circle_font_size)
paint.textAlign = Paint.Align.CENTER
val type = Typeface.create("sans-serif-light", Typeface.NORMAL)
paint.typeface = type
paint.color = ContextCompat.getColor(context, android.R.color.white)
canvas.drawText(
char.toString(),
size,
size - ((paint.ascent() + paint.descent()) / 2.0f),
paint
)
}
}
|
apache-2.0
|
9119272b0424e77753654dbc9a6a4551
| 27.092593 | 94 | 0.63942 | 4.034574 | false | false | false | false |
google/Kotlin-FirViewer
|
src/main/kotlin/io/github/tgeng/firviewer/KtViewerToolWindowFactory.kt
|
1
|
4236
|
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package io.github.tgeng.firviewer
import com.google.common.cache.CacheBuilder
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.FileEditorManagerListener
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowFactory
import com.intellij.psi.*
import org.jetbrains.kotlin.psi.KtFile
import java.awt.event.FocusAdapter
import java.awt.event.FocusEvent
class KtViewerToolWindowFactory : ToolWindowFactory {
private val cache = CacheBuilder.newBuilder().weakKeys().build<PsiFile, TreeUiState>()
override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
toolWindow.title = "KtViewer"
toolWindow.setIcon(AllIcons.Toolwindows.ToolWindowStructure)
refresh(project, toolWindow)
toolWindow.setTitleActions(listOf(object : AnAction(), DumbAware {
override fun update(e: AnActionEvent) {
e.presentation.icon = AllIcons.Actions.Refresh
}
override fun actionPerformed(e: AnActionEvent) {
refresh(project, toolWindow)
}
}))
refresh(project, toolWindow)
project.messageBus.connect()
.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, object : FileEditorManagerListener {
override fun fileOpened(source: FileEditorManager, file: VirtualFile) {
refresh(project, toolWindow)
}
})
project.messageBus.connect().subscribe(EVENT_TOPIC, Runnable { refresh(project, toolWindow) })
}
private fun refresh(project: Project, toolWindow: ToolWindow) {
if (!toolWindow.isVisible) return
val vf = FileEditorManager.getInstance(project).selectedFiles.firstOrNull() ?: return
val ktFile = PsiManager.getInstance(project).findFile(vf) as? KtFile ?: return
val treeUiState = cache.get(ktFile) {
val treeModel = ObjectTreeModel(
ktFile,
PsiElement::class,
{ it }) { consumer ->
ApplicationManager.getApplication().runReadAction {
this.takeIf { it.isValid }?.acceptChildren(object : PsiElementVisitor() {
override fun visitElement(element: PsiElement) {
if (element is PsiWhiteSpace) return
consumer(element)
}
})
}
}
treeModel.setupTreeUi(project).apply {
pane.addFocusListener(object : FocusAdapter() {
override fun focusGained(e: FocusEvent?) {
refresh(project, toolWindow)
}
})
}
}
treeUiState.refreshTree()
if (toolWindow.contentManager.contents.firstOrNull() != treeUiState.pane) {
toolWindow.contentManager.removeAllContents(true)
toolWindow.contentManager.addContent(
toolWindow.contentManager.factory.createContent(
treeUiState.pane,
"Current File",
true
)
)
}
}
}
|
apache-2.0
|
f49aa5a4540bc22c894d2d0aa28d86fc
| 39.740385 | 110 | 0.63763 | 5.355247 | false | false | false | false |
zdary/intellij-community
|
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/columns/renderers/PackageScopeTableCellRenderer.kt
|
1
|
2151
|
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.renderers
import com.intellij.icons.AllIcons
import com.intellij.ui.components.JBComboBoxLabel
import com.jetbrains.packagesearch.intellij.plugin.ui.PackageSearchUI
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageScope
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.ScopeViewModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.colors
import net.miginfocom.swing.MigLayout
import javax.swing.JPanel
import javax.swing.JTable
import javax.swing.table.TableCellRenderer
internal object PackageScopeTableCellRenderer : TableCellRenderer {
override fun getTableCellRendererComponent(
table: JTable,
value: Any,
isSelected: Boolean,
hasFocus: Boolean,
row: Int,
column: Int
) = JPanel(MigLayout("al left center, insets 0 8 0 0")).apply {
table.colors.applyTo(this, isSelected)
val bgColor = if (!isSelected && value is ScopeViewModel.InstallablePackage) {
PackageSearchUI.ListRowHighlightBackground
} else {
background
}
background = bgColor
val jbComboBoxLabel = JBComboBoxLabel().apply {
table.colors.applyTo(this, isSelected)
background = bgColor
icon = AllIcons.General.LinkDropTriangle
text = when (value) {
is ScopeViewModel.InstalledPackage -> scopesMessage(value.installedScopes, value.defaultScope)
is ScopeViewModel.InstallablePackage -> value.selectedScope.displayName
else -> throw IllegalArgumentException("The value is expected to be a ScopeViewModel, but wasn't.")
}
}
add(jbComboBoxLabel)
}
private fun scopesMessage(installedScopes: List<PackageScope>, defaultScope: PackageScope): String {
if (installedScopes.isEmpty()) return defaultScope.displayName
return installedScopes.joinToString { it.displayName }
}
}
|
apache-2.0
|
2280187ac4976006e0a7b62c35fe70eb
| 40.365385 | 115 | 0.721525 | 5.121429 | false | false | false | false |
code-helix/slatekit
|
src/lib/kotlin/slatekit-generator/src/main/kotlin/slatekit/generator/Help.kt
|
1
|
3432
|
package slatekit.generator
import slatekit.common.conf.Conf
import slatekit.common.ext.orElse
import slatekit.utils.writer.ConsoleWriter
import slatekit.context.Context
class Help(val name:String) {
/**
* Shows just the welcome header
*/
open fun intro(){
val writer = ConsoleWriter()
writer.text("**********************************************")
writer.title("Welcome to $name")
writer.text("You can use this CLI to create new Slate Kit projects")
writer.text("**********************************************")
writer.text("")
}
/**
* Shows help info on how to run the generator
*/
open fun show(op:(() -> Unit)? = null) {
val writer = ConsoleWriter()
intro()
// Routing
writer.title("OVERVIEW")
writer.text("1. COMMANDS : are Organized into 3 part ( AREAS, APIS, ACTIONS ) : {area}.{api}.{action}")
writer.text("2. DISCOVERY : available using \"?\" as in \"area ?\" \"area.api ?\" \"area.api.action ?\"")
writer.text("3. EXECUTE : using 3 part name and passing inputs e.g. {area}.{api}.{action} -key=value*")
writer.text("")
op?.let {
it.invoke()
writer.text("")
}
examples()
}
/**
* Shows diagnostics info about directory / versions used
*/
open fun settings(ctx: Context, settings: Conf) {
val writer = ConsoleWriter()
val outputDir = settings.getString("generation.output" ).orElse("CURRENT_DIR")
writer.title("SETTINGS")
writer.keyValue("system.currentDir ", System.getProperty("user.dir"))
writer.keyValue("slatekit.dir ", ctx.dirs?.pathToApp ?: "")
writer.keyValue("slatekit.settings ", java.io.File(ctx.dirs?.pathToConf, "settings.conf").absolutePath)
writer.keyValue("slatekit.tag ", ctx.conf.getString("slatekit.tag"))
writer.keyValue("slatekit.version.cli ", ctx.conf.getString("slatekit.version.cli" ))
writer.keyValue("slatekit.version ", settings.getString("slatekit.version" ))
writer.keyValue("slatekit.version.beta ", settings.getString("slatekit.version.beta"))
writer.keyValue("slatekit.kotlin.version", settings.getString("kotlin.version" ))
writer.keyValue("generation.source ", settings.getString("generation.source" ))
writer.keyValue("generation.output ", outputDir)
}
/**
* Shows examples of usage
*/
open fun examples(){
val writer = ConsoleWriter()
writer.title("EXAMPLES")
writer.text("You can create the various Slate Kit Projects below")
writer.highlight("1. slatekit new app -name=\"MyApp1\" -packageName=\"company1.apps\"")
writer.highlight("2. slatekit new api -name=\"MyAPI1\" -packageName=\"company1.apis\"")
writer.highlight("3. slatekit new cli -name=\"MyCLI1\" -packageName=\"company1.apps\"")
writer.highlight("4. slatekit new env -name=\"MyApp2\" -packageName=\"company1.apps\"")
writer.highlight("5. slatekit new job -name=\"MyJob1\" -packageName=\"company1.jobs\"")
writer.text("")
}
/**
* Shows examples of usage
*/
open fun exit(){
val writer = ConsoleWriter()
writer.failure("Type \"exit\" to exit app")
writer.text("")
}
}
|
apache-2.0
|
ff296aca5ad06badb90cf32d8da12cfb
| 36.315217 | 117 | 0.585664 | 4.306148 | false | false | false | false |
JuliusKunze/kotlin-native
|
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/descriptors/DeepVisitor.kt
|
2
|
6496
|
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.konan.descriptors
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.DescriptorUtils
open class DeepVisitor<D>(val worker: DeclarationDescriptorVisitor<Boolean, D>) : DeclarationDescriptorVisitor<Boolean, D> {
open fun visitChildren(descriptors: Collection<DeclarationDescriptor>, data: D): Boolean {
for (descriptor in descriptors) {
if (!descriptor.accept(this, data)) return false
}
return true
}
open fun visitChildren(descriptor: DeclarationDescriptor?, data: D): Boolean {
if (descriptor == null) return true
return descriptor.accept(this, data)
}
fun applyWorker(descriptor: DeclarationDescriptor, data: D): Boolean {
return descriptor.accept(worker, data)
}
fun processCallable(descriptor: CallableDescriptor, data: D): Boolean {
return applyWorker(descriptor, data)
&& visitChildren(descriptor.getTypeParameters(), data)
&& visitChildren(descriptor.getExtensionReceiverParameter(), data)
&& visitChildren(descriptor.getValueParameters(), data)
}
override fun visitPackageFragmentDescriptor(descriptor: PackageFragmentDescriptor, data: D): Boolean? {
return applyWorker(descriptor, data) && visitChildren(DescriptorUtils.getAllDescriptors(descriptor.getMemberScope()), data)
}
override fun visitPackageViewDescriptor(descriptor: PackageViewDescriptor, data: D): Boolean? {
return applyWorker(descriptor, data) && visitChildren(DescriptorUtils.getAllDescriptors(descriptor.memberScope), data)
}
override fun visitVariableDescriptor(descriptor: VariableDescriptor, data: D): Boolean? {
return processCallable(descriptor, data)
}
override fun visitPropertyDescriptor(descriptor: PropertyDescriptor, data: D): Boolean? {
return processCallable(descriptor, data)
&& visitChildren(descriptor.getter, data)
&& visitChildren(descriptor.setter, data)
}
override fun visitFunctionDescriptor(descriptor: FunctionDescriptor, data: D): Boolean? {
return processCallable(descriptor, data)
}
override fun visitTypeParameterDescriptor(descriptor: TypeParameterDescriptor, data: D): Boolean? {
return applyWorker(descriptor, data)
}
override fun visitClassDescriptor(descriptor: ClassDescriptor, data: D): Boolean? {
return applyWorker(descriptor, data)
&& visitChildren(descriptor.getThisAsReceiverParameter(), data)
&& visitChildren(descriptor.getConstructors(), data)
&& visitChildren(descriptor.getTypeConstructor().getParameters(), data)
&& visitChildren(DescriptorUtils.getAllDescriptors(descriptor.getDefaultType().memberScope), data)
}
override fun visitTypeAliasDescriptor(descriptor: TypeAliasDescriptor, data: D): Boolean? {
return applyWorker(descriptor, data) && visitChildren(descriptor.getDeclaredTypeParameters(), data)
}
override fun visitModuleDeclaration(descriptor: ModuleDescriptor, data: D): Boolean? {
return applyWorker(descriptor, data) && visitChildren(descriptor.getPackage(FqName.ROOT), data)
}
override fun visitConstructorDescriptor(constructorDescriptor: ConstructorDescriptor, data: D): Boolean? {
return visitFunctionDescriptor(constructorDescriptor, data)
}
override fun visitScriptDescriptor(scriptDescriptor: ScriptDescriptor, data: D): Boolean? {
return visitClassDescriptor(scriptDescriptor, data)
}
override fun visitValueParameterDescriptor(descriptor: ValueParameterDescriptor, data: D): Boolean? {
return visitVariableDescriptor(descriptor, data)
}
override fun visitPropertyGetterDescriptor(descriptor: PropertyGetterDescriptor, data: D): Boolean? {
return visitFunctionDescriptor(descriptor, data)
}
override fun visitPropertySetterDescriptor(descriptor: PropertySetterDescriptor, data: D): Boolean? {
return visitFunctionDescriptor(descriptor, data)
}
override fun visitReceiverParameterDescriptor(descriptor: ReceiverParameterDescriptor, data: D): Boolean? {
return applyWorker(descriptor, data)
}
}
open public class EmptyDescriptorVisitorVoid: DeclarationDescriptorVisitor<Boolean, Unit> {
override fun visitPackageFragmentDescriptor(descriptor: PackageFragmentDescriptor, data: Unit) = true
override fun visitPackageViewDescriptor(descriptor: PackageViewDescriptor, data: Unit) = true
override fun visitVariableDescriptor(descriptor: VariableDescriptor, data: Unit) = true
override fun visitFunctionDescriptor(descriptor: FunctionDescriptor, data: Unit) = true
override fun visitTypeParameterDescriptor(descriptor: TypeParameterDescriptor, data: Unit) = true
override fun visitClassDescriptor(descriptor: ClassDescriptor, data: Unit) = true
override fun visitTypeAliasDescriptor(descriptor: TypeAliasDescriptor, data: Unit) = true
override fun visitModuleDeclaration(descriptor: ModuleDescriptor, data: Unit) = true
override fun visitConstructorDescriptor(descriptor: ConstructorDescriptor, data: Unit) = true
override fun visitScriptDescriptor(descriptor: ScriptDescriptor, data: Unit) = true
override fun visitPropertyDescriptor(descriptor: PropertyDescriptor, data: Unit) = true
override fun visitValueParameterDescriptor(descriptor: ValueParameterDescriptor, data: Unit) = true
override fun visitPropertyGetterDescriptor(descriptor: PropertyGetterDescriptor, data: Unit) = true
override fun visitPropertySetterDescriptor(descriptor: PropertySetterDescriptor, data: Unit) = true
override fun visitReceiverParameterDescriptor(descriptor: ReceiverParameterDescriptor, data: Unit) = true
}
|
apache-2.0
|
e5b239d8b3440f1592f6eda403cc4afe
| 47.477612 | 131 | 0.749692 | 5.500423 | false | false | false | false |
smmribeiro/intellij-community
|
uast/uast-java/src/org/jetbrains/uast/java/JavaAbstractUElement.kt
|
2
|
5536
|
// 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.uast.java
import com.intellij.lang.Language
import com.intellij.lang.java.JavaLanguage
import com.intellij.psi.*
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.uast.*
import org.jetbrains.uast.java.internal.JavaUElementWithComments
@ApiStatus.Internal
abstract class JavaAbstractUElement(
givenParent: UElement?
) : JavaUElementWithComments, UElement {
override fun equals(other: Any?): Boolean {
if (other !is UElement || other.javaClass != this.javaClass) return false
return if (this.sourcePsi != null) this.sourcePsi == other.sourcePsi else this === other
}
override fun hashCode(): Int = sourcePsi?.hashCode() ?: System.identityHashCode(this)
override fun asSourceString(): String {
return this.sourcePsi?.text ?: super<JavaUElementWithComments>.asSourceString()
}
override fun toString(): String = asRenderString()
override val uastParent: UElement? by lz { givenParent ?: convertParent() }
protected open fun convertParent(): UElement? =
getPsiParentForLazyConversion()
?.let { JavaConverter.unwrapElements(it).toUElement() }
?.let { unwrapSwitch(it) }
?.let { wrapSingleExpressionLambda(it) }
?.also {
if (it === this) throw IllegalStateException("lazy parent loop for $this")
if (it.sourcePsi != null && it.sourcePsi === this.sourcePsi)
throw IllegalStateException("lazy parent loop: sourcePsi ${this.sourcePsi}(${this.sourcePsi?.javaClass}) for $this of ${this.javaClass}")
}
protected open fun getPsiParentForLazyConversion(): PsiElement? = this.sourcePsi?.parent
//explicitly overridden in abstract class to be binary compatible with Kotlin
override val comments: List<UComment>
get() = super<JavaUElementWithComments>.comments
abstract override val sourcePsi: PsiElement?
override val javaPsi: PsiElement?
get() = super<JavaUElementWithComments>.javaPsi
@Suppress("OverridingDeprecatedMember")
override val psi: PsiElement?
get() = sourcePsi
}
private fun JavaAbstractUElement.wrapSingleExpressionLambda(uParent: UElement): UElement {
val sourcePsi = sourcePsi
return if (uParent is JavaULambdaExpression && sourcePsi is PsiExpression)
(uParent.body as? UBlockExpression)?.expressions?.singleOrNull() ?: uParent
else uParent
}
private fun JavaAbstractUElement.unwrapSwitch(uParent: UElement): UElement {
when (uParent) {
is UBlockExpression -> {
val codeBlockParent = uParent.uastParent
when (codeBlockParent) {
is JavaUSwitchEntryList -> {
if (branchHasElement(sourcePsi, codeBlockParent.sourcePsi) { it is PsiSwitchLabelStatementBase }) {
return codeBlockParent
}
val psiElement = sourcePsi ?: return uParent
return codeBlockParent.findUSwitchEntryForBodyStatementMember(psiElement)?.body ?: return codeBlockParent
}
is UExpressionList -> {
val sourcePsi = codeBlockParent.sourcePsi
if (sourcePsi is PsiSwitchLabeledRuleStatement)
(codeBlockParent.uastParent as? JavaUSwitchEntry)?.let { return it.body }
}
is JavaUSwitchExpression -> return unwrapSwitch(codeBlockParent)
}
return uParent
}
is JavaUSwitchEntry -> {
val parentSourcePsi = uParent.sourcePsi
if (parentSourcePsi is PsiSwitchLabeledRuleStatement && parentSourcePsi.body?.children?.contains(sourcePsi) == true) {
val psi = sourcePsi
return if (psi is PsiExpression && uParent.body.expressions.size == 1)
DummyYieldExpression(psi, uParent.body)
else uParent.body
}
else
return uParent
}
is USwitchExpression -> {
val parentPsi = uParent.sourcePsi as PsiSwitchBlock
return if (this === uParent.body || branchHasElement(sourcePsi, parentPsi) { it === parentPsi.expression })
uParent
else
uParent.body
}
else -> return uParent
}
}
private inline fun branchHasElement(child: PsiElement?, parent: PsiElement?, predicate: (PsiElement) -> Boolean): Boolean {
var current: PsiElement? = child
while (current != null && current != parent) {
if (predicate(current)) return true
current = current.parent
}
return false
}
@ApiStatus.Internal
abstract class JavaAbstractUExpression(
givenParent: UElement?
) : JavaAbstractUElement(givenParent), UExpression {
override fun evaluate(): Any? {
val project = sourcePsi?.project ?: return null
return JavaPsiFacade.getInstance(project).constantEvaluationHelper.computeConstantExpression(sourcePsi)
}
override val uAnnotations: List<UAnnotation>
get() = emptyList()
override fun getExpressionType(): PsiType? {
val expression = sourcePsi as? PsiExpression ?: return null
return expression.type
}
override fun getPsiParentForLazyConversion(): PsiElement? = super.getPsiParentForLazyConversion()?.let {
when (it) {
is PsiResourceExpression -> it.parent
is PsiReferenceExpression -> (it.parent as? PsiMethodCallExpression) ?: it
else -> it
}
}
override fun convertParent(): UElement? = super.convertParent().let { uParent ->
when (uParent) {
is UAnonymousClass -> uParent.uastParent
else -> uParent
}
}.let(this::unwrapCompositeQualifiedReference)
override val lang: Language
get() = JavaLanguage.INSTANCE
}
|
apache-2.0
|
0466ac10edcef628615f4183d3fb0876
| 33.81761 | 147 | 0.710621 | 5.083563 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/tests/testData/structuralsearch/property/receiverFqTypeReference.kt
|
4
|
220
|
val String.foo: Int get() = 1
<warning descr="SSR">val Int.foo: Int get() = 1</warning>
<warning descr="SSR">val kotlin.Int.bar: Int get() = 1</warning>
class A {
class Int
val Int.foo: kotlin.Int get() = 1
}
|
apache-2.0
|
ce4685037d868272e5215f944fad60ff
| 21 | 64 | 0.622727 | 2.857143 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/decompiler/stubBuilder/BuiltInDecompilerConsistencyTest.kt
|
2
|
6076
|
// 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.decompiler.stubBuilder
import com.intellij.ide.highlighter.JavaClassFileType
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.ThrowableRunnable
import com.intellij.util.indexing.FileContentImpl
import org.jetbrains.kotlin.idea.caches.IDEKotlinBinaryClassCache
import org.jetbrains.kotlin.idea.decompiler.builtIns.BuiltInDefinitionFile
import org.jetbrains.kotlin.idea.decompiler.builtIns.KotlinBuiltInDecompiler
import org.jetbrains.kotlin.idea.decompiler.classFile.KotlinClassFileDecompiler
import org.jetbrains.kotlin.idea.decompiler.common.FileWithMetadata
import org.jetbrains.kotlin.idea.stubindex.KotlinFullClassNameIndex
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.jetbrains.kotlin.idea.test.runAll
import org.jetbrains.kotlin.metadata.deserialization.Flags
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.stubs.KotlinClassStub
import org.jetbrains.kotlin.psi.stubs.elements.KtClassElementType
import org.jetbrains.kotlin.serialization.deserialization.builtins.BuiltInSerializerProtocol
import org.jetbrains.kotlin.serialization.deserialization.getClassId
import org.junit.internal.runners.JUnit38ClassRunner
import org.junit.runner.RunWith
@RunWith(JUnit38ClassRunner::class)
class BuiltInDecompilerConsistencyTest : KotlinLightCodeInsightFixtureTestCase() {
private val classFileDecompiler = KotlinClassFileDecompiler()
private val builtInsDecompiler = KotlinBuiltInDecompiler()
override fun setUp() {
super.setUp()
BuiltInDefinitionFile.FILTER_OUT_CLASSES_EXISTING_AS_JVM_CLASS_FILES = false
}
override fun tearDown() {
runAll(
ThrowableRunnable { BuiltInDefinitionFile.FILTER_OUT_CLASSES_EXISTING_AS_JVM_CLASS_FILES = true },
ThrowableRunnable { super.tearDown() }
)
}
fun testSameAsClsDecompilerForCompiledBuiltInClasses() {
doTest("kotlin")
doTest("kotlin.annotation")
doTest("kotlin.collections")
doTest("kotlin.ranges")
doTest("kotlin.reflect", 3,
setOf("KTypeProjection") // TODO: seems @JvmField is @OptionalExpectation that makes KTypeProjection actual one
)
}
// Check stubs for decompiled built-in classes against stubs for decompiled JVM class files, assuming the latter are well tested
// Check only those classes, stubs for which are present in the stub for a decompiled .kotlin_builtins file
private fun doTest(packageFqName: String, minClassesEncountered: Int = 5, excludedClasses: Set<String> = emptySet()) {
val dir = findDir(packageFqName, project)
val groupedByExtension = dir.children.groupBy { it.extension }
val builtInsFile = groupedByExtension.getValue(BuiltInSerializerProtocol.BUILTINS_FILE_EXTENSION).single()
// do not compare commonized classes
// proper fix is to get `expect` modifier from stub rather from bytecode metadata: https://youtrack.jetbrains.com/issue/KT-45534
val expectClassNames = builtInsDecompiler.readFile(builtInsFile)?.let { metadata ->
return@let if (metadata is FileWithMetadata.Compatible) {
metadata.proto.class_List.filter { Flags.IS_EXPECT_CLASS.get(it.flags) }
.map { metadata.nameResolver.getClassId(it.fqName).shortClassName.asString() }.toSet()
} else null
} ?: emptySet()
val classFiles = groupedByExtension.getValue(JavaClassFileType.INSTANCE.defaultExtension)
.map { it.nameWithoutExtension }.filterNot { it in expectClassNames || it in excludedClasses }
val builtInFileStub = builtInsDecompiler.stubBuilder.buildFileStub(FileContentImpl.createByFile(builtInsFile))!!
val classesEncountered = arrayListOf<FqName>()
for (className in classFiles) {
val classFile = dir.findChild(className + "." + JavaClassFileType.INSTANCE.defaultExtension)!!
val fileContent = FileContentImpl.createByFile(classFile)
val file = fileContent.file
if (IDEKotlinBinaryClassCache.getInstance().getKotlinBinaryClassHeaderData(file) == null) continue
val fileStub = classFileDecompiler.stubBuilder.buildFileStub(fileContent) ?: continue
val classStub = fileStub.findChildStubByType(KtClassElementType.getStubType(false)) ?: continue
val classFqName = classStub.getFqName()!!
val builtInClassStub = builtInFileStub.childrenStubs.firstOrNull {
it is KotlinClassStub && it.getFqName() == classFqName
} ?: continue
assertEquals("Stub mismatch for $classFqName", classStub.serializeToString(), builtInClassStub.serializeToString())
classesEncountered.add(classFqName)
}
assertTrue(
"Too few classes encountered in package $packageFqName: $classesEncountered",
classesEncountered.size >= minClassesEncountered
)
}
override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_NO_SOURCES
}
internal fun findDir(packageFqName: String, project: Project): VirtualFile {
val classNameIndex = KotlinFullClassNameIndex.getInstance()
val randomClassInPackage = classNameIndex.getAllKeys(project).first {
it.startsWith("$packageFqName.") && "." !in it.substringAfter("$packageFqName.")
}
val classes = classNameIndex.get(randomClassInPackage, project, GlobalSearchScope.allScope(project))
val firstClass = classes.firstOrNull() ?: error("No classes with this name found: $randomClassInPackage (package name $packageFqName)")
return firstClass.containingFile.virtualFile.parent
}
|
apache-2.0
|
fea391b536392fa859487ea79e9155f7
| 53.738739 | 158 | 0.751481 | 5.063333 | false | true | false | false |
ianhanniballake/muzei
|
muzei-api/src/main/java/com/google/android/apps/muzei/api/provider/MuzeiArtProvider.kt
|
1
|
53309
|
/*
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("DEPRECATION")
package com.google.android.apps.muzei.api.provider
import android.annotation.SuppressLint
import android.app.PendingIntent
import android.content.ActivityNotFoundException
import android.content.ComponentName
import android.content.ContentProvider
import android.content.ContentProviderOperation
import android.content.ContentProviderResult
import android.content.ContentResolver
import android.content.ContentUris
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.content.OperationApplicationException
import android.content.pm.PackageManager
import android.content.pm.ProviderInfo
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.database.sqlite.SQLiteQueryBuilder
import android.net.Uri
import android.os.Binder
import android.os.Build
import android.os.Bundle
import android.os.ParcelFileDescriptor
import android.os.Trace
import android.provider.BaseColumns
import android.provider.DocumentsContract
import android.util.Log
import androidx.annotation.CallSuper
import androidx.annotation.RequiresApi
import androidx.core.app.RemoteActionCompat
import androidx.core.graphics.drawable.IconCompat
import androidx.versionedparcelable.ParcelUtils
import com.google.android.apps.muzei.api.BuildConfig
import com.google.android.apps.muzei.api.R
import com.google.android.apps.muzei.api.UserCommand
import com.google.android.apps.muzei.api.internal.ProtocolConstants.DEFAULT_VERSION
import com.google.android.apps.muzei.api.internal.ProtocolConstants.GET_COMMAND_ACTIONS_MIN_VERSION
import com.google.android.apps.muzei.api.internal.ProtocolConstants.KEY_COMMAND
import com.google.android.apps.muzei.api.internal.ProtocolConstants.KEY_COMMANDS
import com.google.android.apps.muzei.api.internal.ProtocolConstants.KEY_DESCRIPTION
import com.google.android.apps.muzei.api.internal.ProtocolConstants.KEY_GET_ARTWORK_INFO
import com.google.android.apps.muzei.api.internal.ProtocolConstants.KEY_LAST_LOADED_TIME
import com.google.android.apps.muzei.api.internal.ProtocolConstants.KEY_MAX_LOADED_ARTWORK_ID
import com.google.android.apps.muzei.api.internal.ProtocolConstants.KEY_OPEN_ARTWORK_INFO_SUCCESS
import com.google.android.apps.muzei.api.internal.ProtocolConstants.KEY_RECENT_ARTWORK_IDS
import com.google.android.apps.muzei.api.internal.ProtocolConstants.KEY_VERSION
import com.google.android.apps.muzei.api.internal.ProtocolConstants.METHOD_GET_ARTWORK_INFO
import com.google.android.apps.muzei.api.internal.ProtocolConstants.METHOD_GET_COMMANDS
import com.google.android.apps.muzei.api.internal.ProtocolConstants.METHOD_GET_DESCRIPTION
import com.google.android.apps.muzei.api.internal.ProtocolConstants.METHOD_GET_LOAD_INFO
import com.google.android.apps.muzei.api.internal.ProtocolConstants.METHOD_GET_VERSION
import com.google.android.apps.muzei.api.internal.ProtocolConstants.METHOD_MARK_ARTWORK_INVALID
import com.google.android.apps.muzei.api.internal.ProtocolConstants.METHOD_MARK_ARTWORK_LOADED
import com.google.android.apps.muzei.api.internal.ProtocolConstants.METHOD_OPEN_ARTWORK_INFO
import com.google.android.apps.muzei.api.internal.ProtocolConstants.METHOD_REQUEST_LOAD
import com.google.android.apps.muzei.api.internal.ProtocolConstants.METHOD_TRIGGER_COMMAND
import com.google.android.apps.muzei.api.internal.RemoteActionBroadcastReceiver
import com.google.android.apps.muzei.api.internal.getRecentIds
import com.google.android.apps.muzei.api.internal.putRecentIds
import com.google.android.apps.muzei.api.provider.MuzeiArtProvider.Companion.ACCESS_PERMISSION
import com.google.android.apps.muzei.api.provider.MuzeiArtProvider.Companion.ACTION_MUZEI_ART_PROVIDER
import com.google.android.apps.muzei.api.provider.MuzeiArtProvider.Companion.EXTRA_FROM_MUZEI
import org.json.JSONArray
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL
import java.util.ArrayList
import java.util.HashSet
/**
* Base class for a Muzei Live Wallpaper artwork provider. Art providers are a way for other apps to
* feed wallpapers (called [artworks][Artwork]) to Muzei Live Wallpaper.
*
* ### Subclassing [MuzeiArtProvider]
*
* Subclasses must implement at least the [onLoadRequested] callback
* method, which is called whenever Muzei has displayed all available artwork from your provider.
* It is strongly recommended to load new artwork at this point and add it via
* [addArtwork] so that users can continue to move to the next artwork.
*
* All artwork added via [addArtwork] is available to Muzei. Muzei controls how
* often the artwork changes and the order that it proceeds through the artwork. As a
* convenience, you can use [setArtwork] to remove all artwork and set just a
* single new [Artwork]. You can use [ContentResolver.delete] with [contentUri] to delete
* specific artwork based on criteria of your choosing.
*
* Many operations are also available in [ProviderContract.Artwork], allowing you to add,
* update, delete, and query for artwork from anywhere in your app.
*
* ### Registering your provider
*
* Each provider must be added to your application's `AndroidManifest.xml` file via a
* `<provider>` element.
*
* The Muzei app discover available providers using Android's [Intent] mechanism. Ensure
* that your `provider` definition includes an `<intent-filter>` with
* an action of [ACTION_MUZEI_ART_PROVIDER]. It is strongly recommended to protect access
* to your provider's data by adding the [ACCESS_PERMISSION], which will
* ensure that only your app and Muzei can access your data.
*
* Lastly, there are a few `<meta-data>` elements that you should add to your
* provider definition:
*
* * `settingsActivity` (optional): if present, should be the qualified
* component name for a configuration activity in the provider's package that Muzei can offer
* to the user for customizing the extension. This activity must be exported.
* * `setupActivity` (optional): if present, should be the qualified
* component name for an initial setup activity that must be ran before the provider can be
* activated. It will be started with [android.app.Activity.startActivityForResult] and must
* return [android.app.Activity.RESULT_OK] for the provider to be activated. This activity
* must be exported.
*
* ### Example
*
* Below is an example provider declaration in the manifest:
* ```
* <provider android:name=".ExampleArtProvider"
* android:authorities="com.example.artprovider"
* android:label="@string/source_title"
* android:description="@string/source_description"
* android:permission="com.google.android.apps.muzei.api.ACCESS_PROVIDER">
* <intent-filter>
* <action android:name="com.google.android.apps.muzei.api.MuzeiArtProvider" />
* </intent-filter>
* <!-- A settings activity is optional -->
* <meta-data android:name="settingsActivity"
* android:value=".ExampleSettingsActivity" />
* </provider>
* ```
*
* If a `settingsActivity` meta-data element is present, an activity with the given
* component name should be defined and exported in the application's manifest as well. Muzei
* will set the [EXTRA_FROM_MUZEI] extra to true in the launch intent for this
* activity. An example is shown below:
* ```
* <activity android:name=".ExampleSettingsActivity"
* android:label="@string/title_settings"
* android:exported="true" />
* ```
*
* Finally, below is a simple example [MuzeiArtProvider] subclass that publishes a single,
* static artwork:
* ```
* class ExampleArtProvider : MuzeiArtProvider() {
* override fun onLoadRequested(initial: Boolean) {
* if (initial) {
* setArtwork(Artwork(
* title = "Example image",
* byline = "Unknown person, c. 1980",
* persistentUri = Uri.parse("http://example.com/image.jpg"),
* webUri = Uri.parse("http://example.com/imagedetails.html")))
* }
* }
* }
* ```
*
* As onLoadRequested can be called at any time (including when offline), it is
* strongly recommended to use the callback of onLoadRequested to kick off
* a load operation using `WorkManager`, `JobScheduler`, or a comparable API. These
* other components can then use a [ProviderClient] and
* [ProviderClient.addArtwork] to add Artwork to the MuzeiArtProvider.
*
* ### Additional notes
* Providers can also expose additional user-facing commands (such as 'Share artwork') by
* returning one or more [RemoteActionCompat] instances from [getCommandActions].
*
* Providers can provide a dynamic description of the current configuration (e.g.
* 'Popular photos tagged "landscape"'), by overriding [getDescription]. By default,
* the `android:description` element of the provider element in the manifest will be
* used.
*
* All artwork should support opening an Activity to view more details about the artwork.
* You can provider your own functionality by overriding [getArtworkInfo].
*
* If custom behavior is needed to retrieve the artwork's binary data (for example,
* authentication with a remote server), this behavior can be added to
* [openFile]. If you already have binary data available locally for your
* artwork, you can also write it directly via [ContentResolver.openOutputStream].
*
* It is strongly recommended to add a [MuzeiArtDocumentsProvider] to your manifest to make
* artwork from your MuzeiArtProvider available via the default file picker and Files app.
*
* MuzeiArtProvider respects [Log.isLoggable] for debug logging, allowing you to
* use `adb shell setprop log.tag.MuzeiArtProvider VERBOSE` to enable logging of the
* communications between Muzei and your MuzeiArtProvider.
*
* @constructor Constructs a `MuzeiArtProvider`.
*/
@RequiresApi(Build.VERSION_CODES.KITKAT)
public abstract class MuzeiArtProvider : ContentProvider(), ProviderClient {
public companion object {
private const val TAG = "MuzeiArtProvider"
private const val MAX_RECENT_ARTWORK = 100
/**
* Permission that can be used with your [MuzeiArtProvider] to ensure that only your app
* and Muzei can read and write its data.
*
* This is a signature permission that only Muzei can hold.
*/
@Suppress("unused")
public const val ACCESS_PERMISSION: String = "com.google.android.apps.muzei.api.ACCESS_PROVIDER"
/**
* The [Intent] action representing a Muzei art provider. This provider should
* declare an `<intent-filter>` for this action in order to register with
* Muzei.
*/
public const val ACTION_MUZEI_ART_PROVIDER: String = "com.google.android.apps.muzei.api.MuzeiArtProvider"
/**
* Boolean extra that will be set to true when Muzei starts provider settings and setup
* activities.
*
* Check for this extra in your activity if you need to adjust your UI depending on
* whether or not the user came from Muzei.
*/
public const val EXTRA_FROM_MUZEI: String = "com.google.android.apps.muzei.api.extra.FROM_MUZEI_SETTINGS"
private const val PREF_MAX_LOADED_ARTWORK_ID = "maxLoadedArtworkId"
private const val PREF_LAST_LOADED_TIME = "lastLoadTime"
private const val PREF_RECENT_ARTWORK_IDS = "recentArtworkIds"
private const val TABLE_NAME = "artwork"
}
/**
* An identity all column projection mapping for artwork
*/
private val allArtworkColumnProjectionMap = mapOf(
BaseColumns._ID to BaseColumns._ID,
ProviderContract.Artwork.TOKEN to ProviderContract.Artwork.TOKEN,
ProviderContract.Artwork.TITLE to ProviderContract.Artwork.TITLE,
ProviderContract.Artwork.BYLINE to ProviderContract.Artwork.BYLINE,
ProviderContract.Artwork.ATTRIBUTION to ProviderContract.Artwork.ATTRIBUTION,
ProviderContract.Artwork.PERSISTENT_URI to ProviderContract.Artwork.PERSISTENT_URI,
ProviderContract.Artwork.WEB_URI to ProviderContract.Artwork.WEB_URI,
ProviderContract.Artwork.METADATA to ProviderContract.Artwork.METADATA,
ProviderContract.Artwork.DATA to ProviderContract.Artwork.DATA,
ProviderContract.Artwork.DATE_ADDED to ProviderContract.Artwork.DATE_ADDED,
ProviderContract.Artwork.DATE_MODIFIED to ProviderContract.Artwork.DATE_MODIFIED)
private lateinit var databaseHelper: DatabaseHelper
private lateinit var authority: String
private var hasDocumentsProvider = false
final override val contentUri: Uri by lazy {
val context = context
?: throw IllegalStateException("getContentUri() should not be called before onCreate()")
ProviderContract.getProviderClient(context, javaClass).contentUri
}
private val applyingBatch = ThreadLocal<Boolean>()
private val changedUris = ThreadLocal<MutableSet<Uri>>()
private fun applyingBatch(): Boolean {
return applyingBatch.get() != null && applyingBatch.get()!!
}
private fun onOperationComplete() {
val context = context ?: return
val contentResolver = context.contentResolver
for (uri in changedUris.get()!!) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Notified for batch change on $uri")
}
contentResolver.notifyChange(uri, null)
}
}
final override val lastAddedArtwork: Artwork? get() = query(contentUri, null, null, null,
"${BaseColumns._ID} DESC").use { data ->
return if (data.moveToFirst()) Artwork.fromCursor(data) else null
}
final override fun addArtwork(artwork: Artwork): Uri? {
return insert(contentUri, artwork.toContentValues())
}
final override fun addArtwork(artwork: Iterable<Artwork>): List<Uri> {
val operations = ArrayList<ContentProviderOperation>()
for (art in artwork) {
operations.add(ContentProviderOperation.newInsert(contentUri)
.withValues(art.toContentValues())
.build())
}
return try {
applyBatch(operations).mapNotNull { result -> result.uri }
} catch (e: OperationApplicationException) {
if (Log.isLoggable(TAG, Log.INFO)) {
Log.i(TAG, "addArtwork failed", e)
}
emptyList()
}
}
final override fun setArtwork(artwork: Artwork): Uri? {
val operations = ArrayList<ContentProviderOperation>()
operations.add(ContentProviderOperation.newInsert(contentUri)
.withValues(artwork.toContentValues())
.build())
operations.add(ContentProviderOperation.newDelete(contentUri)
.withSelection(BaseColumns._ID + " != ?", arrayOfNulls(1))
.withSelectionBackReference(0, 0)
.build())
return try {
val results = applyBatch(operations)
results[0].uri
} catch (e: OperationApplicationException) {
if (Log.isLoggable(TAG, Log.INFO)) {
Log.i(TAG, "setArtwork failed", e)
}
null
}
}
final override fun setArtwork(artwork: Iterable<Artwork>): List<Uri> {
val operations = ArrayList<ContentProviderOperation>()
for (art in artwork) {
operations.add(ContentProviderOperation.newInsert(contentUri)
.withValues(art.toContentValues())
.build())
}
val artworkCount = operations.size
val resultUris = ArrayList<Uri>(artworkCount)
// Delete any artwork that was not inserted/update in the above operations
val currentTime = System.currentTimeMillis()
operations.add(ContentProviderOperation.newDelete(contentUri)
.withSelection("${ProviderContract.Artwork.DATE_MODIFIED} < ?",
arrayOf(currentTime.toString()))
.build())
try {
val results = applyBatch(operations)
resultUris.addAll(results.take(artworkCount).mapNotNull { result -> result.uri })
} catch (e: OperationApplicationException) {
if (Log.isLoggable(TAG, Log.INFO)) {
Log.i(TAG, "setArtwork failed", e)
}
}
return resultUris
}
/**
* @suppress
*/
@CallSuper
override fun call(
method: String,
arg: String?,
extras: Bundle?
): Bundle? {
val context = context ?: return null
val token = Binder.clearCallingIdentity()
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Received command $method with arg \"$arg\" and extras $extras")
}
try {
when (method) {
METHOD_GET_VERSION -> {
return Bundle().apply {
putInt(KEY_VERSION, BuildConfig.API_VERSION)
}
}
METHOD_REQUEST_LOAD -> databaseHelper.readableDatabase.query(TABLE_NAME,
null, null, null, null, null, null, "1").use { data ->
onLoadRequested(data == null || data.count == 0)
}
METHOD_MARK_ARTWORK_INVALID -> query(Uri.parse(arg), null, null, null, null).use { data ->
if (data.moveToNext()) {
onInvalidArtwork(Artwork.fromCursor(data))
}
}
METHOD_MARK_ARTWORK_LOADED -> query(contentUri, null, null, null, null).use { data ->
val prefs = context.getSharedPreferences(authority, Context.MODE_PRIVATE)
val editor = prefs.edit()
// See if we need to update the maxLoadedArtworkId
val currentMaxId = prefs.getLong(PREF_MAX_LOADED_ARTWORK_ID, 0L)
val loadedId = ContentUris.parseId(Uri.parse(arg))
if (loadedId > currentMaxId) {
editor.putLong(PREF_MAX_LOADED_ARTWORK_ID, loadedId)
}
// Update the last loaded time
editor.putLong(PREF_LAST_LOADED_TIME, System.currentTimeMillis())
// Update the list of recent artwork ids
val recentArtworkIds = prefs.getRecentIds(PREF_RECENT_ARTWORK_IDS)
// Remove the loadedId if it exists in the list already
recentArtworkIds.remove(loadedId)
// Then add the loadedId to the end of the list
recentArtworkIds.addLast(loadedId)
val maxSize = data.count.coerceIn(1, MAX_RECENT_ARTWORK)
while (recentArtworkIds.size > maxSize) {
removeAutoCachedFile(recentArtworkIds.removeFirst())
}
editor.putRecentIds(PREF_RECENT_ARTWORK_IDS, recentArtworkIds)
editor.apply()
}
METHOD_GET_LOAD_INFO -> {
val prefs = context.getSharedPreferences(authority, Context.MODE_PRIVATE)
return Bundle().apply {
putLong(KEY_MAX_LOADED_ARTWORK_ID, prefs.getLong(PREF_MAX_LOADED_ARTWORK_ID, 0L))
putLong(KEY_LAST_LOADED_TIME, prefs.getLong(PREF_LAST_LOADED_TIME, 0L))
putString(KEY_RECENT_ARTWORK_IDS, prefs.getString(PREF_RECENT_ARTWORK_IDS, ""))
}.also {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "For $METHOD_GET_LOAD_INFO returning $it")
}
}
}
METHOD_GET_DESCRIPTION -> {
return Bundle().apply {
putString(KEY_DESCRIPTION, getDescription())
}
}
METHOD_GET_COMMANDS -> query(Uri.parse(arg), null, null, null, null).use { data ->
if (data.moveToNext()) {
return Bundle().apply {
val muzeiVersion = extras?.getInt(KEY_VERSION, DEFAULT_VERSION)
?: DEFAULT_VERSION
if (muzeiVersion >= GET_COMMAND_ACTIONS_MIN_VERSION) {
val userCommands = getCommandActions(Artwork.fromCursor(data))
putInt(KEY_VERSION, BuildConfig.API_VERSION)
ParcelUtils.putVersionedParcelableList(this, KEY_COMMANDS, userCommands)
} else {
val userCommands = getCommands(Artwork.fromCursor(data))
val commandsSerialized = JSONArray()
for (command in userCommands) {
commandsSerialized.put(command.serialize())
}
putString(KEY_COMMANDS, commandsSerialized.toString())
}
}.also {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "For $METHOD_GET_COMMANDS returning $it")
}
}
}
}
METHOD_TRIGGER_COMMAND -> if (extras != null) {
query(Uri.parse(arg), null, null, null, null).use { data ->
if (data.moveToNext()) {
onCommand(Artwork.fromCursor(data), extras.getInt(KEY_COMMAND))
}
}
}
METHOD_OPEN_ARTWORK_INFO -> query(Uri.parse(arg), null, null, null, null).use { data ->
if (data.moveToNext()) {
return Bundle().apply {
val success = openArtworkInfo(Artwork.fromCursor(data))
putBoolean(KEY_OPEN_ARTWORK_INFO_SUCCESS, success)
}.also {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "For $METHOD_OPEN_ARTWORK_INFO returning $it")
}
}
}
}
METHOD_GET_ARTWORK_INFO -> query(Uri.parse(arg), null, null, null, null).use { data ->
if (data.moveToNext()) {
return Bundle().apply {
val artworkInfo = getArtworkInfo(Artwork.fromCursor(data))
putParcelable(KEY_GET_ARTWORK_INFO, artworkInfo)
}.also {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "For $METHOD_GET_ARTWORK_INFO returning $it")
}
}
}
}
}
return null
} finally {
Binder.restoreCallingIdentity(token)
}
}
/**
* Callback method when the user has viewed all of the available artwork. This should be used
* as a cue to load more artwork so that the user has a constant stream of new artwork.
*
* Muzei will always prefer to show unseen artwork, but will automatically cycle through all
* of the available artwork if no new artwork is found (i.e., if you don't load new artwork
* after receiving this callback).
*
* @param initial true when there is no artwork available, such as is the case when this is
* the initial load of this MuzeiArtProvider.
*/
public abstract fun onLoadRequested(initial: Boolean)
/**
* Called when Muzei failed to load the given artwork, usually due to an incompatibility
* in supported image format. The default behavior is to delete the artwork.
*
* If you only support a single artwork, you should use this callback as an opportunity
* to provide an alternate version of the artwork or a backup image to avoid repeatedly
* loading the same artwork, just to mark it as invalid and be left with no valid artwork.
*
* @param artwork Artwork that Muzei has failed to load
*/
public open fun onInvalidArtwork(artwork: Artwork) {
val artworkUri = ContentUris.withAppendedId(contentUri, artwork.id)
delete(artworkUri, null, null)
}
/**
* The longer description for the current state of this MuzeiArtProvider. For example,
* 'Popular photos tagged "landscape"'). The default implementation returns the
* `android:description` element of the provider element in the manifest.
*
* @return A longer description to be displayed alongside the label of the provider.
*/
public open fun getDescription(): String {
val context = context ?: return ""
return try {
@SuppressLint("InlinedApi")
val info = context.packageManager.getProviderInfo(
ComponentName(context, javaClass),
PackageManager.MATCH_DISABLED_COMPONENTS)
if (info.descriptionRes != 0) context.getString(info.descriptionRes) else ""
} catch (e: PackageManager.NameNotFoundException) {
""
}
}
/**
* Retrieve the list of commands available for the given artwork.
*
* @param artwork The associated artwork that can be used to customize the list of available
* commands.
* @return A List of [commands][UserCommand] that the user can trigger.
* @see onCommand
*/
@Deprecated(message = "Override getCommandActions() to set an icon and PendingIntent " +
"that should be triggered. This method will still be called on devices that " +
"have an older version of Muzei installed.",
replaceWith = ReplaceWith("getCommandActions(artwork)"))
public open fun getCommands(artwork: Artwork): List<UserCommand> {
return ArrayList()
}
/**
* Callback method indicating that the user has selected a command returned by
* [getCommands].
*
* @param artwork The artwork at the time when this command was triggered.
* @param id the ID of the command the user has chosen.
* @see getCommands
*/
@Deprecated("Provide your own PendingIntent for each RemoteActionCompat returned " +
"by getCommandActions(). This method will still be called on devices that " +
"have an older version of Muzei installed if you continue to override getCommands().")
public open fun onCommand(artwork: Artwork, id: Int) {
}
/**
* Retrieve the list of commands available for the given artwork. Each action should have
* an icon 24x24dp. Muzei respects the [RemoteActionCompat.setShouldShowIcon] to determine
* when to show the action as an icon (assuming there is enough space). Actions with a
* blank title will be ignored by Muzei.
*
* Each action triggers a [PendingIntent]. This can directly open an Activity for sending
* the user to an external app / website or can point to a [android.content.BroadcastReceiver]
* for doing a small amount of background work.
*
* @param artwork The associated artwork that can be used to customize the list of available
* commands.
* @return A List of [commands][RemoteActionCompat] that the user can trigger.
*/
public open fun getCommandActions(artwork: Artwork) : List<RemoteActionCompat> {
val context = context ?: return listOf()
return getCommands(artwork).map { command ->
RemoteActionCompat(
IconCompat.createWithResource(context, R.drawable.muzei_launch_command),
command.title ?: "",
command.title ?: "",
RemoteActionBroadcastReceiver.createPendingIntent(
context, authority, artwork.id, command.id)
).apply {
setShouldShowIcon(false)
}
}
}
/**
* Callback when the user wishes to see more information about the given artwork. The default
* implementation opens the [web uri][ProviderContract.Artwork.WEB_URI] of the artwork.
*
* @param artwork The artwork the user wants to see more information about.
* @return True if the artwork info was successfully opened.
*/
@Deprecated("Override getArtworkInfo to return a PendingIntent that starts " +
"your artwork info. This method will still be called on devices that " +
"have an older version of Muzei installed.")
public open fun openArtworkInfo(artwork: Artwork): Boolean {
val context = context ?: return false
if (artwork.webUri != null) {
try {
context.startActivity(Intent(Intent.ACTION_VIEW, artwork.webUri)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
return true
} catch (e: ActivityNotFoundException) {
if (Log.isLoggable(TAG, Log.INFO)) {
Log.i(TAG, "Could not open ${artwork.webUri}, artwork info for " +
ContentUris.withAppendedId(contentUri, artwork.id), e)
}
}
}
return false
}
/**
* Callback when the user wishes to see more information about the given artwork. The default
* implementation constructs a [PendingIntent] to the
* [web uri][ProviderContract.Artwork.WEB_URI] of the artwork.
*
* @param artwork The artwork the user wants to see more information about.
* @return A [PendingIntent] generally constructed with
* [PendingIntent.getActivity].
*/
public open fun getArtworkInfo(artwork: Artwork): PendingIntent? {
if (artwork.webUri != null && context != null) {
val intent = Intent(Intent.ACTION_VIEW, artwork.webUri)
return PendingIntent.getActivity(context, 0, intent, 0)
}
return null
}
/**
* @suppress
*/
@CallSuper
override fun onCreate(): Boolean {
authority = contentUri.authority!!
val databaseName = authority.substring(authority.lastIndexOf('.') + 1)
databaseHelper = DatabaseHelper(context!!, databaseName)
return true
}
/**
* @suppress
*/
@CallSuper
override fun attachInfo(context: Context, info: ProviderInfo) {
super.attachInfo(context, info)
val documentsAuthority = "$authority.documents"
val pm = context.packageManager
hasDocumentsProvider = pm.resolveContentProvider(documentsAuthority,
PackageManager.GET_DISABLED_COMPONENTS) != null
}
/**
* @suppress
*/
override fun query(uri: Uri,
projection: Array<String>?,
selection: String?,
selectionArgs: Array<String>?,
sortOrder: String?
): Cursor {
val contentResolver = context?.contentResolver
?: throw IllegalStateException("Called query() before onCreate()")
val qb = SQLiteQueryBuilder().apply {
tables = TABLE_NAME
projectionMap = allArtworkColumnProjectionMap
isStrict = true
}
val db = databaseHelper.readableDatabase
if (uri != contentUri) {
// Appends "_ID = <id>" to the where clause, so that it selects the single artwork
qb.appendWhere("${BaseColumns._ID}=${uri.lastPathSegment}")
}
val orderBy = if (sortOrder.isNullOrEmpty())
"${ProviderContract.Artwork.DATE_ADDED} DESC"
else
sortOrder
val c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy, null)
c.setNotificationUri(contentResolver, uri)
return c
}
/**
* @suppress
*/
override fun getType(uri: Uri): String {
return if (uri == contentUri) {
"vnd.android.cursor.dir/vnd.$authority.$TABLE_NAME"
} else {
"vnd.android.cursor.item/vnd.$authority.$TABLE_NAME"
}
}
/**
* @suppress
*/
@Throws(OperationApplicationException::class)
override fun applyBatch(
operations: ArrayList<ContentProviderOperation>
): Array<ContentProviderResult> {
changedUris.set(HashSet())
val db = databaseHelper.readableDatabase
val results: Array<ContentProviderResult>
db.beginTransaction()
try {
Trace.beginSection("applyBatch")
applyingBatch.set(true)
results = super.applyBatch(operations)
db.setTransactionSuccessful()
} finally {
db.endTransaction()
applyingBatch.set(false)
onOperationComplete()
Trace.endSection()
}
return results
}
/**
* @suppress
*/
override fun bulkInsert(uri: Uri, values: Array<ContentValues>): Int {
changedUris.set(HashSet())
val db = databaseHelper.readableDatabase
val numberInserted: Int
db.beginTransaction()
try {
Trace.beginSection("bulkInsert")
applyingBatch.set(true)
numberInserted = super.bulkInsert(uri, values)
db.setTransactionSuccessful()
} finally {
db.endTransaction()
applyingBatch.set(false)
onOperationComplete()
Trace.endSection()
}
return numberInserted
}
/**
* @suppress
*/
override fun insert(uri: Uri, initialValues: ContentValues?): Uri? {
val values = initialValues ?: ContentValues()
val context = context ?: throw IllegalStateException("Called insert() before onCreate()")
if (values.containsKey(ProviderContract.Artwork.TOKEN)) {
val token = values.getAsString(ProviderContract.Artwork.TOKEN)
if (token.isNullOrEmpty()) {
// Treat empty strings as null
if (token != null) {
if (Log.isLoggable(TAG, Log.INFO)) {
Log.i(TAG, "${ProviderContract.Artwork.TOKEN} must be non-empty if included")
}
}
values.remove(token)
} else {
query(contentUri, null,
"${ProviderContract.Artwork.TOKEN}=?",
arrayOf(token), null).use { existingData ->
if (existingData.moveToFirst()) {
// If there's already a row with the same token, update it rather than
// inserting a new row
// But first check whether there's actually anything changing
val title = existingData.getString(existingData.getColumnIndex(
ProviderContract.Artwork.TITLE))
val byline = existingData.getString(existingData.getColumnIndex(
ProviderContract.Artwork.BYLINE))
val attribution = existingData.getString(existingData.getColumnIndex(
ProviderContract.Artwork.ATTRIBUTION))
val persistentUri = existingData.getString(existingData.getColumnIndex(
ProviderContract.Artwork.PERSISTENT_URI))
val webUri = existingData.getString(existingData.getColumnIndex(
ProviderContract.Artwork.WEB_URI))
val metadata = existingData.getString(existingData.getColumnIndex(
ProviderContract.Artwork.METADATA))
val noChange =
title == values.getAsString(ProviderContract.Artwork.TITLE) &&
byline == values.getAsString(ProviderContract.Artwork.BYLINE) &&
attribution == values.getAsString(ProviderContract.Artwork.ATTRIBUTION) &&
persistentUri == values.getAsString(ProviderContract.Artwork.PERSISTENT_URI) &&
webUri == values.getAsString(ProviderContract.Artwork.WEB_URI) &&
metadata == values.getAsString(ProviderContract.Artwork.METADATA)
val id = existingData.getLong(existingData.getColumnIndex(BaseColumns._ID))
val updateUri = ContentUris.withAppendedId(contentUri, id)
if (noChange) {
// Just update the DATE_MODIFIED and don't send a notifyChange()
values.clear()
values.put(ProviderContract.Artwork.DATE_MODIFIED,
System.currentTimeMillis())
val db = databaseHelper.writableDatabase
db.update(TABLE_NAME, values, "${BaseColumns._ID}=?",
arrayOf(id.toString()))
} else {
// Do a full update
update(updateUri, values, null, null)
}
return updateUri
}
}
}
}
val now = System.currentTimeMillis()
values.put(ProviderContract.Artwork.DATE_ADDED, now)
values.put(ProviderContract.Artwork.DATE_MODIFIED, now)
val db = databaseHelper.writableDatabase
db.beginTransaction()
val rowId = db.insert(TABLE_NAME,
ProviderContract.Artwork.DATE_ADDED, values)
if (rowId <= 0) {
// Insert failed, not much we can do about that
db.endTransaction()
return null
}
// Add the DATA column pointing at the correct location
val hasPersistentUri = values.containsKey(ProviderContract.Artwork.PERSISTENT_URI) &&
!values.getAsString(ProviderContract.Artwork.PERSISTENT_URI).isNullOrEmpty()
val directory = if (hasPersistentUri) {
File(context.cacheDir, "muzei_$authority")
} else {
File(context.filesDir, "muzei_$authority")
}
directory.mkdirs()
val artwork = File(directory, rowId.toString())
db.update(TABLE_NAME, ContentValues().apply {
put(ProviderContract.Artwork.DATA, artwork.absolutePath)
}, "${BaseColumns._ID}=$rowId", null)
db.setTransactionSuccessful()
db.endTransaction()
// Creates a URI with the artwork ID pattern and the new row ID appended to it.
val artworkUri = ContentUris.withAppendedId(contentUri, rowId)
if (applyingBatch()) {
// Only notify changes on the root contentUri for batch operations
// to avoid overloading ContentObservers
changedUris.get()!!.add(contentUri)
if (hasDocumentsProvider) {
val documentUri = DocumentsContract.buildChildDocumentsUri(
"$authority.documents", authority)
changedUris.get()!!.add(documentUri)
}
} else {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Notified for insert on $artworkUri")
}
context.contentResolver.notifyChange(artworkUri, null)
if (hasDocumentsProvider) {
val documentUri = DocumentsContract.buildDocumentUri(
"$authority.documents", "$authority/$rowId")
context.contentResolver.notifyChange(documentUri, null)
}
}
return artworkUri
}
/**
* @suppress
*/
override fun delete(
uri: Uri,
selection: String?,
selectionArgs: Array<String>?
): Int {
val db = databaseHelper.writableDatabase
val count: Int
var finalWhere = selection
if (contentUri != uri) {
finalWhere = "${BaseColumns._ID} = ${uri.lastPathSegment}"
// If there were additional selection criteria, append them to the final WHERE clause
if (selection != null) {
finalWhere = "$finalWhere AND $selection"
}
}
// Delete all of the files associated with the rows being deleted
query(contentUri, arrayOf(ProviderContract.Artwork.DATA),
finalWhere, selectionArgs, null).use { rowsToDelete ->
while (rowsToDelete.moveToNext()) {
val fileName = rowsToDelete.getString(0)
val file = if (fileName != null) File(fileName) else null
if (file != null && file.exists()) {
if (!file.delete()) {
if (Log.isLoggable(TAG, Log.INFO)) {
Log.i(TAG, "Unable to delete $file")
}
}
}
}
}
// Then delete the rows themselves
count = db.delete(TABLE_NAME, finalWhere, selectionArgs)
val context = context ?: return count
if (count > 0) {
val documentUri = DocumentsContract.buildChildDocumentsUri(
"$authority.documents", authority)
if (applyingBatch()) {
// Only notify changes on the root contentUri for batch operations
// to avoid overloading ContentObservers
changedUris.get()!!.add(contentUri)
if (hasDocumentsProvider) {
changedUris.get()!!.add(documentUri)
}
} else {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Notified for delete on $uri")
}
context.contentResolver.notifyChange(uri, null)
if (hasDocumentsProvider) {
context.contentResolver.notifyChange(documentUri, null)
}
}
}
return count
}
/**
* @suppress
*/
override fun update(
uri: Uri,
values: ContentValues?,
selection: String?,
selectionArgs: Array<String>?
): Int {
if (values == null) {
return 0
}
val db = databaseHelper.writableDatabase
val count: Int
var finalWhere = selection
if (contentUri != uri) {
finalWhere = "${BaseColumns._ID} = ${uri.lastPathSegment}"
// If there were additional selection criteria, append them to the final WHERE clause
if (selection != null) {
finalWhere = "$finalWhere AND $selection"
}
}
// TOKEN, DATA and DATE_ADDED cannot be changed
values.remove(ProviderContract.Artwork.TOKEN)
values.remove(ProviderContract.Artwork.DATA)
values.remove(ProviderContract.Artwork.DATE_ADDED)
// Update the DATE_MODIFIED
values.put(ProviderContract.Artwork.DATE_MODIFIED, System.currentTimeMillis())
count = db.update(TABLE_NAME, values, finalWhere, selectionArgs)
val context = context ?: return count
if (count > 0) {
val documentUri = DocumentsContract.buildChildDocumentsUri(
"$authority.documents", authority)
if (applyingBatch()) {
// Only notify changes on the root contentUri for batch operations
// to avoid overloading ContentObservers
changedUris.get()!!.add(contentUri)
if (hasDocumentsProvider) {
changedUris.get()!!.add(documentUri)
}
} else {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Notified for update on $uri")
}
context.contentResolver.notifyChange(uri, null)
if (hasDocumentsProvider) {
context.contentResolver.notifyChange(documentUri, null)
}
}
}
return count
}
private fun removeAutoCachedFile(artworkId: Long) {
val artworkUri = ContentUris.withAppendedId(contentUri, artworkId)
query(artworkUri, null, null, null, null).use { data ->
if (!data.moveToFirst()) {
return
}
val artwork = Artwork.fromCursor(data)
if (artwork.persistentUri != null && artwork.data.exists()) {
artwork.data.delete()
}
}
}
/**
* Called every time an image is loaded (even if there is a cached
* image available). This gives you an opportunity to circumvent the
* typical loading process and remove previously cached artwork on
* demand. The default implementation always returns `true`.
*
* In most cases, you should proactively delete Artwork that you know
* is not valid rather than wait for this callback since at this point
* the user is specifically waiting for the image to appear.
*
* The MuzeiArtProvider will call [onInvalidArtwork] for you
* if you return `false` - there is no need to call this
* manually from within this method.
* @param artwork The Artwork to confirm
* @return Whether the Artwork is valid and should be loaded
*/
public open fun isArtworkValid(artwork: Artwork): Boolean {
return true
}
/**
* Provide an InputStream to the binary data associated with artwork that has not yet been
* cached. The default implementation retrieves the image from the
* [persistent URI][Artwork.persistentUri] and supports URI schemes in the following
* formats:
*
* * `content://...`.
* * `android.resource://...`.
* * `file://...`.
* * `file:///android_asset/...`.
* * `http://...` or `https://...`.
*
* Throwing any exception other than an [IOException] will be considered a permanent
* error that will result in a call to [onInvalidArtwork].
*
* @param artwork The Artwork to open
* @return A valid [InputStream] for the artwork's image
* @throws IOException if an error occurs while opening the image. The request will be retried
* automatically.
*/
@Throws(IOException::class)
public open fun openFile(artwork: Artwork): InputStream {
val context = context ?: throw IOException()
val persistentUri = artwork.persistentUri
?: throw IllegalStateException("Got null persistent URI for $artwork. " +
"The default implementation of openFile() requires a persistent URI. " +
"You must override this method or write the binary data directly to " +
"the artwork's data file.")
val scheme = persistentUri.scheme ?: throw IOException("Uri had no scheme")
return (if (ContentResolver.SCHEME_CONTENT == scheme || ContentResolver.SCHEME_ANDROID_RESOURCE == scheme) {
context.contentResolver.openInputStream(persistentUri)
} else if (ContentResolver.SCHEME_FILE == scheme) {
val segments = persistentUri.pathSegments
if (segments != null && segments.size > 1
&& "android_asset" == segments[0]) {
val assetPath = StringBuilder()
for (i in 1 until segments.size) {
if (i > 1) {
assetPath.append("/")
}
assetPath.append(segments[i])
}
context.assets.open(assetPath.toString())
} else {
FileInputStream(File(persistentUri.path!!))
}
} else if ("http" == scheme || "https" == scheme) {
val url = URL(persistentUri.toString())
val urlConnection = url.openConnection() as HttpURLConnection
val responseCode = urlConnection.responseCode
if (responseCode !in 200..299) {
throw IOException("HTTP error response $responseCode")
}
urlConnection.inputStream
} else {
throw FileNotFoundException("Unsupported scheme $scheme for $persistentUri")
}) ?: throw FileNotFoundException("Null input stream for URI: $persistentUri")
}
/**
* @suppress
*/
@Throws(FileNotFoundException::class)
override fun openFile(
uri: Uri,
mode: String
): ParcelFileDescriptor? {
val artwork = query(uri, null, null, null, null).use { data ->
if (!data.moveToFirst()) {
throw FileNotFoundException("Could not get persistent uri for $uri")
}
Artwork.fromCursor(data)
}
if (!isArtworkValid(artwork)) {
onInvalidArtwork(artwork)
throw SecurityException("Artwork $artwork was marked as invalid")
}
if (!artwork.data.exists() && mode == "r") {
// Download the image from the persistent URI for read-only operations
// rather than throw a FileNotFoundException
val directory = artwork.data.parentFile
// Ensure that the parent directory of the artwork exists
// as otherwise FileOutputStream will fail
if (!directory!!.exists() && !directory.mkdirs()) {
throw FileNotFoundException("Unable to create directory $directory for $artwork")
}
try {
openFile(artwork).use { input ->
FileOutputStream(artwork.data).use { output ->
input.copyTo(output)
}
}
} catch (e: Exception) {
if (e !is IOException) {
if (Log.isLoggable(TAG, Log.INFO)) {
Log.i(TAG, "Unable to open artwork $artwork for $uri", e)
}
onInvalidArtwork(artwork)
}
// Delete the file in cases of an error so that we will try again from scratch next time.
if (artwork.data.exists() && !artwork.data.delete()) {
if (Log.isLoggable(TAG, Log.INFO)) {
Log.i(TAG, "Error deleting partially downloaded file after error", e)
}
}
throw FileNotFoundException("Could not download artwork $artwork for $uri: ${e.message}")
}
}
return ParcelFileDescriptor.open(artwork.data, ParcelFileDescriptor.parseMode(mode))
}
/**
* This class helps open, create, and upgrade the database file.
*/
internal class DatabaseHelper(
context: Context,
databaseName: String
) : SQLiteOpenHelper(context, databaseName, null, DATABASE_VERSION) {
companion object {
private const val DATABASE_VERSION = 1
}
/**
* Creates the underlying database with table name and column names taken from the
* MuzeiContract class.
*/
override fun onCreate(db: SQLiteDatabase) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
+ ProviderContract.Artwork.TOKEN + " TEXT,"
+ ProviderContract.Artwork.TITLE + " TEXT,"
+ ProviderContract.Artwork.BYLINE + " TEXT,"
+ ProviderContract.Artwork.ATTRIBUTION + " TEXT,"
+ ProviderContract.Artwork.PERSISTENT_URI + " TEXT,"
+ ProviderContract.Artwork.WEB_URI + " TEXT,"
+ ProviderContract.Artwork.METADATA + " TEXT,"
+ ProviderContract.Artwork.DATA + " TEXT,"
+ ProviderContract.Artwork.DATE_ADDED + " INTEGER NOT NULL,"
+ ProviderContract.Artwork.DATE_MODIFIED + " INTEGER NOT NULL);")
}
/**
* Upgrades the database.
*/
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {}
}
}
|
apache-2.0
|
e1ec4104938d35553e3f20a8fe76c731
| 44.602224 | 116 | 0.609953 | 5.106226 | false | false | false | false |
leafclick/intellij-community
|
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/frame/XDebuggerThreadsList.kt
|
1
|
5312
|
// 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.xdebugger.impl.frame
import com.intellij.openapi.ui.popup.ListItemDescriptor
import com.intellij.ui.CollectionListModel
import com.intellij.ui.ColoredListCellRenderer
import com.intellij.ui.components.JBList
import com.intellij.ui.popup.list.GroupedItemsListRenderer
import com.intellij.xdebugger.XDebuggerBundle
import com.intellij.xdebugger.frame.XExecutionStack
import java.awt.Component
import java.awt.Point
import javax.swing.*
import javax.swing.plaf.FontUIResource
class XDebuggerThreadsList(private val renderer: ListCellRenderer<StackInfo>) : JBList<StackInfo>(
CollectionListModel()
) {
private var mySelectedFrame: StackInfo? = null
val elementCount: Int
get() = model.size
companion object {
fun createDefault(): XDebuggerThreadsList {
return create(XDebuggerGroupedFrameListRenderer())
}
fun create(renderer: ListCellRenderer<StackInfo>): XDebuggerThreadsList {
val list = XDebuggerThreadsList(renderer)
list.doInit()
return list
}
}
init {
// This is a workaround for the performance issue IDEA-187063
// default font generates too much garbage in deriveFont
val font = font
if (font != null) {
setFont(FontUIResource(font.name, font.style, font.size))
}
}
private fun doInit() {
selectionModel.selectionMode = ListSelectionModel.SINGLE_SELECTION
cellRenderer = renderer
selectionModel.addListSelectionListener { e ->
if (!e.valueIsAdjusting) {
onThreadChanged(selectedValue)
}
}
emptyText.text = XDebuggerBundle.message("threads.list.threads.not.available")
}
private fun onThreadChanged(stack: StackInfo?) {
if (mySelectedFrame != stack) {
SwingUtilities.invokeLater { this.repaint() }
mySelectedFrame = stack
}
}
override fun getModel(): CollectionListModel<StackInfo> {
return super.getModel() as CollectionListModel<StackInfo>
}
override fun setModel(model: ListModel<StackInfo>?) {
// todo throw exception?
// do not allow to change model (e.g. to FilteringListModel)
}
override fun locationToIndex(location: Point): Int {
return if (location.y <= preferredSize.height) super.locationToIndex(location) else -1
}
fun clear() {
model.removeAll()
}
private class XDebuggerGroupedFrameListRenderer : GroupedItemsListRenderer<StackInfo>(XDebuggerListItemDescriptor()) {
private val myOriginalRenderer = XDebuggerThreadsListRenderer()
init {
mySeparatorComponent.setCaptionCentered(false)
}
override fun getListCellRendererComponent(
list: JList<out StackInfo>?,
value: StackInfo?,
index: Int,
isSelected: Boolean,
cellHasFocus: Boolean
): Component {
return myOriginalRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus)
}
override fun createItemComponent(): JComponent {
createLabel()
return XDebuggerThreadsListRenderer()
}
}
private class XDebuggerListItemDescriptor : ListItemDescriptor<StackInfo> {
override fun getTextFor(value: StackInfo?): String? = value?.toString()
override fun getTooltipFor(value: StackInfo?): String? = value?.toString()
override fun getIconFor(value: StackInfo?): Icon? = value?.stack?.icon
override fun hasSeparatorAboveOf(value: StackInfo?): Boolean = false
override fun getCaptionAboveOf(value: StackInfo?): String? = null
}
private class XDebuggerThreadsListRenderer : ColoredListCellRenderer<StackInfo>() {
override fun customizeCellRenderer(
list: JList<out StackInfo>,
value: StackInfo?,
index: Int,
selected: Boolean,
hasFocus: Boolean
) {
val stack = value ?: return
when (stack.kind) {
StackInfo.StackKind.ExecutionStack -> {
append(stack.toString())
icon = stack.stack?.icon
}
StackInfo.StackKind.Error,
StackInfo.StackKind.Loading -> append(stack.toString())
}
}
}
}
data class StackInfo private constructor(val kind: StackKind, val stack: XExecutionStack?, val error: String?) {
companion object {
fun from(executionStack: XExecutionStack): StackInfo = StackInfo(StackKind.ExecutionStack, executionStack, null)
fun error(error: String): StackInfo = StackInfo(StackKind.Error, null, error)
val loading = StackInfo(StackKind.Loading, null, null)
}
override fun toString(): String {
return when (kind) {
StackKind.ExecutionStack -> stack!!.displayName
StackKind.Error -> error!!
StackKind.Loading -> "Loading..."
}
}
enum class StackKind {
ExecutionStack,
Error,
Loading
}
}
|
apache-2.0
|
4219410c7f15c05bad7d1b9d2e4746e9
| 32.620253 | 140 | 0.647779 | 5.301397 | false | false | false | false |
leafclick/intellij-community
|
platform/built-in-server/src/org/jetbrains/io/jsonRpc/JsonRpcServer.kt
|
1
|
11141
|
// 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.io.jsonRpc
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.TypeAdapter
import com.google.gson.TypeAdapterFactory
import com.google.gson.reflect.TypeToken
import com.google.gson.stream.JsonToken
import com.google.gson.stream.JsonWriter
import com.intellij.openapi.Disposable
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.NotNullLazyValue
import com.intellij.util.ArrayUtil
import com.intellij.util.ArrayUtilRt
import com.intellij.util.Consumer
import com.intellij.util.SmartList
import com.intellij.util.io.releaseIfError
import com.intellij.util.io.writeUtf8
import gnu.trove.THashMap
import gnu.trove.TIntArrayList
import io.netty.buffer.*
import org.jetbrains.concurrency.Promise
import org.jetbrains.io.JsonReaderEx
import org.jetbrains.io.JsonUtil
import java.io.IOException
import java.lang.reflect.Method
import java.util.concurrent.atomic.AtomicInteger
private val LOG = Logger.getInstance(JsonRpcServer::class.java)
private val INT_LIST_TYPE_ADAPTER_FACTORY = object : TypeAdapterFactory {
private var typeAdapter: IntArrayListTypeAdapter<TIntArrayList>? = null
override fun <T> create(gson: Gson, type: TypeToken<T>): TypeAdapter<T>? {
if (type.type !== TIntArrayList::class.java) {
return null
}
if (typeAdapter == null) {
typeAdapter = IntArrayListTypeAdapter()
}
@Suppress("UNCHECKED_CAST")
return typeAdapter as TypeAdapter<T>?
}
}
private val gson by lazy {
GsonBuilder()
.registerTypeAdapterFactory(INT_LIST_TYPE_ADAPTER_FACTORY)
.disableHtmlEscaping()
.create()
}
class JsonRpcServer(private val clientManager: ClientManager) : MessageServer {
private val messageIdCounter = AtomicInteger()
private val domains = THashMap<String, NotNullLazyValue<*>>()
fun registerDomain(name: String, commands: NotNullLazyValue<*>, overridable: Boolean = false, disposable: Disposable? = null) {
if (domains.containsKey(name)) {
if (overridable) {
return
}
else {
throw IllegalArgumentException("$name is already registered")
}
}
domains.put(name, commands)
if (disposable != null) {
Disposer.register(disposable, Disposable { domains.remove(name) })
}
}
override fun messageReceived(client: Client, message: CharSequence) {
if (LOG.isDebugEnabled) {
LOG.debug("IN $message")
}
val reader = JsonReaderEx(message)
reader.beginArray()
val messageId = if (reader.peek() == JsonToken.NUMBER) reader.nextInt() else -1
val domainName = reader.nextString()
if (domainName.length == 1) {
val promise = client.messageCallbackMap.remove(messageId)
if (domainName[0] == 'r') {
if (promise == null) {
LOG.error("Response with id $messageId was already processed")
return
}
promise.setResult(JsonUtil.nextAny(reader))
}
else {
promise!!.setError("error")
}
return
}
val domainHolder = domains[domainName]
if (domainHolder == null) {
processClientError(client, "Cannot find domain $domainName", messageId)
return
}
val domain = domainHolder.value
val command = reader.nextString()
if (domain is JsonServiceInvocator) {
domain.invoke(command, client, reader, messageId, message)
return
}
val parameters: Array<Any>
if (reader.hasNext()) {
val list = SmartList<Any>()
JsonUtil.readListBody(reader, list)
parameters = ArrayUtil.toObjectArray(list[0] as List<*>)
}
else {
parameters = ArrayUtilRt.EMPTY_OBJECT_ARRAY
}
val isStatic = domain is Class<*>
val methods: Array<Method>
if (isStatic) {
methods = (domain as Class<*>).declaredMethods
}
else {
methods = domain.javaClass.methods
}
for (method in methods) {
if (method.name == command) {
method.isAccessible = true
val result = method.invoke(if (isStatic) null else domain, *parameters)
if (messageId != -1) {
if (result is ByteBuf) {
result.releaseIfError {
client.send(encodeMessage(client.byteBufAllocator, messageId, rawData = result))
}
}
else {
client.send(encodeMessage(client.byteBufAllocator, messageId, params = if (result == null) ArrayUtilRt.EMPTY_OBJECT_ARRAY else arrayOf(result)))
}
}
return
}
}
processClientError(client, "Cannot find method $domain.$command", messageId)
}
private fun processClientError(client: Client, error: String, messageId: Int) {
try {
LOG.error(error)
}
finally {
if (messageId != -1) {
sendErrorResponse(client, messageId, error)
}
}
}
fun sendResponse(client: Client, messageId: Int, rawData: ByteBuf? = null) {
client.send(encodeMessage(client.byteBufAllocator, messageId, rawData = rawData))
}
fun sendErrorResponse(client: Client, messageId: Int, message: CharSequence?) {
client.send(encodeMessage(client.byteBufAllocator, messageId, "e", params = arrayOf(message)))
}
fun sendWithRawPart(client: Client, domain: String, command: String, rawData: ByteBuf, params: Array<*>): Boolean {
return client.send(encodeMessage(client.byteBufAllocator, -1, domain, command, rawData = rawData, params = params)).cause() == null
}
fun send(client: Client, domain: String, command: String, vararg params: Any?) {
client.send(encodeMessage(client.byteBufAllocator, -1, domain, command, params = params))
}
fun <T> call(client: Client, domain: String, command: String, vararg params: Any?): Promise<T> {
val messageId = messageIdCounter.andIncrement
val message = encodeMessage(client.byteBufAllocator, messageId, domain, command, params = params)
return client.send(messageId, message)!!
}
fun send(domain: String, command: String, vararg params: Any?) {
if (clientManager.hasClients()) {
val messageId = -1
val message = encodeMessage(ByteBufAllocator.DEFAULT, messageId, domain, command, params = params)
clientManager.send<Any?>(messageId, message)
}
}
private fun encodeMessage(byteBufAllocator: ByteBufAllocator,
messageId: Int = -1,
domain: String? = null,
command: String? = null,
rawData: ByteBuf? = null,
params: Array<*> = ArrayUtilRt.EMPTY_OBJECT_ARRAY): ByteBuf {
val buffer = doEncodeMessage(byteBufAllocator, messageId, domain, command, params, rawData)
if (LOG.isDebugEnabled) {
LOG.debug("OUT ${buffer.toString(Charsets.UTF_8)}")
}
return buffer
}
private fun doEncodeMessage(byteBufAllocator: ByteBufAllocator,
id: Int,
domain: String?,
command: String?,
params: Array<*>,
rawData: ByteBuf?): ByteBuf {
var buffer = byteBufAllocator.ioBuffer()
buffer.writeByte('[')
var sb: StringBuilder? = null
if (id != -1) {
sb = StringBuilder()
buffer.writeAscii(sb.append(id))
sb.setLength(0)
}
if (domain != null) {
if (id != -1) {
buffer.writeByte(',')
}
buffer.writeByte('"').writeAscii(domain).writeByte('"')
if (command != null) {
buffer.writeByte(',').writeByte('"').writeAscii(command).writeByte('"')
}
}
var effectiveBuffer = buffer
if (params.isNotEmpty() || rawData != null) {
buffer.writeByte(',').writeByte('[')
encodeParameters(buffer, params, sb)
if (rawData != null) {
if (params.isNotEmpty()) {
buffer.writeByte(',')
}
effectiveBuffer = byteBufAllocator.compositeBuffer().addComponent(buffer).addComponent(rawData)
buffer = byteBufAllocator.ioBuffer()
}
buffer.writeByte(']')
}
buffer.writeByte(']')
return effectiveBuffer.addBuffer(buffer)
}
private fun encodeParameters(buffer: ByteBuf, params: Array<*>, _sb: StringBuilder?) {
var sb = _sb
var writer: JsonWriter? = null
var hasPrev = false
for (param in params) {
if (hasPrev) {
buffer.writeByte(',')
}
else {
hasPrev = true
}
// gson - SOE if param has type class com.intellij.openapi.editor.impl.DocumentImpl$MyCharArray, so, use hack
if (param is CharSequence) {
JsonUtil.escape(param, buffer)
}
else if (param == null) {
buffer.writeAscii("null")
}
else if (param is Boolean) {
buffer.writeAscii(param.toString())
}
else if (param is Number) {
if (sb == null) {
sb = StringBuilder()
}
if (param is Int) {
sb.append(param.toInt())
}
else if (param is Long) {
sb.append(param.toLong())
}
else if (param is Float) {
sb.append(param.toFloat())
}
else if (param is Double) {
sb.append(param.toDouble())
}
else {
sb.append(param.toString())
}
buffer.writeAscii(sb)
sb.setLength(0)
}
else if (param is Consumer<*>) {
if (sb == null) {
sb = StringBuilder()
}
@Suppress("UNCHECKED_CAST")
(param as Consumer<StringBuilder>).consume(sb)
buffer.writeUtf8(sb)
sb.setLength(0)
}
else {
if (writer == null) {
writer = JsonWriter(ByteBufUtf8Writer(buffer))
}
(gson.getAdapter(param.javaClass) as TypeAdapter<Any>).write(writer, param)
}
}
}
}
private fun ByteBuf.writeByte(c: Char) = writeByte(c.toInt())
private fun ByteBuf.writeAscii(s: CharSequence): ByteBuf {
ByteBufUtil.writeAscii(this, s)
return this
}
private class IntArrayListTypeAdapter<T> : TypeAdapter<T>() {
override fun write(out: JsonWriter, value: T) {
var error: IOException? = null
out.beginArray()
(value as TIntArrayList).forEach { intValue ->
try {
out.value(intValue.toLong())
}
catch (e: IOException) {
error = e
}
error == null
}
error?.let { throw it }
out.endArray()
}
override fun read(`in`: com.google.gson.stream.JsonReader) = throw UnsupportedOperationException()
}
// addComponent always add sliced component, so, we must add last buffer only after all writes
private fun ByteBuf.addBuffer(buffer: ByteBuf): ByteBuf {
if (this !== buffer) {
(this as CompositeByteBuf).addComponent(buffer)
writerIndex(capacity())
}
return this
}
fun JsonRpcServer.registerFromEp() {
for (domainBean in JsonRpcDomainBean.EP_NAME.extensions) {
registerDomain(domainBean.name, domainBean.value, domainBean.overridable)
}
}
|
apache-2.0
|
e16148e5859d8be67ef8bfa00e3c9f67
| 30.385915 | 156 | 0.636657 | 4.370734 | false | false | false | false |
ncoe/rosetta
|
Pseudo-random_numbers/PCG32/Kotlin/src/main/kotlin/PCG32.kt
|
1
|
1277
|
import kotlin.math.floor
class PCG32 {
private var state = 0x853c49e6748fea9buL
private var inc = 0xda3e39cb94b95bdbuL
fun nextInt(): UInt {
val old = state
state = old * N + inc
val shifted = old.shr(18).xor(old).shr(27).toUInt()
val rot = old.shr(59)
return (shifted shr rot.toInt()) or shifted.shl((rot.inv() + 1u).and(31u).toInt())
}
fun nextFloat(): Double {
return nextInt().toDouble() / (1L shl 32)
}
fun seed(seedState: ULong, seedSequence: ULong) {
state = 0u
inc = (seedSequence shl 1).or(1uL)
nextInt()
state += seedState
nextInt()
}
companion object {
private const val N = 6364136223846793005uL
}
}
fun main() {
val r = PCG32()
r.seed(42u, 54u)
println(r.nextInt())
println(r.nextInt())
println(r.nextInt())
println(r.nextInt())
println(r.nextInt())
println()
val counts = Array(5) { 0 }
r.seed(987654321u, 1u)
for (i in 0 until 100000) {
val j = floor(r.nextFloat() * 5.0).toInt()
counts[j] += 1
}
println("The counts for 100,000 repetitions are:")
for (iv in counts.withIndex()) {
println(" %d : %d".format(iv.index, iv.value))
}
}
|
mit
|
119c7ec1ff831788a69d2b1bbf31a25a
| 22.648148 | 90 | 0.563038 | 3.30829 | false | false | false | false |
K0zka/kerub
|
src/test/kotlin/com/github/kerubistan/kerub/planner/steps/storage/block/copy/local/LocalBlockCopyTest.kt
|
2
|
6779
|
package com.github.kerubistan.kerub.planner.steps.storage.block.copy.local
import com.github.kerubistan.kerub.hostUp
import com.github.kerubistan.kerub.model.LvmStorageCapability
import com.github.kerubistan.kerub.model.dynamic.VirtualStorageDeviceDynamic
import com.github.kerubistan.kerub.model.dynamic.VirtualStorageLvmAllocation
import com.github.kerubistan.kerub.model.hardware.BlockDevice
import com.github.kerubistan.kerub.planner.OperationalState
import com.github.kerubistan.kerub.planner.reservations.HostReservation
import com.github.kerubistan.kerub.planner.reservations.VirtualStorageReservation
import com.github.kerubistan.kerub.planner.steps.OperationalStepVerifications
import com.github.kerubistan.kerub.planner.steps.storage.lvm.create.CreateLv
import com.github.kerubistan.kerub.testDisk
import com.github.kerubistan.kerub.testHost
import com.github.kerubistan.kerub.testHostCapabilities
import com.github.kerubistan.kerub.testLvmCapability
import io.github.kerubistan.kroki.size.TB
import org.junit.Test
import org.junit.jupiter.api.assertThrows
import java.util.UUID.randomUUID
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
class LocalBlockCopyTest : OperationalStepVerifications() {
override val step = LocalBlockCopy(
sourceDevice = testDisk,
targetDevice = testDisk.copy(id = randomUUID()),
sourceAllocation = VirtualStorageLvmAllocation(
capabilityId = testLvmCapability.id,
actualSize = testDisk.size,
path = "",
vgName = testLvmCapability.volumeGroupName,
hostId = testHost.id
),
allocationStep = CreateLv(
host = testHost,
disk = testDisk,
capability = testLvmCapability
)
)
@Test
fun validate() {
assertThrows<IllegalStateException>("same source and target") {
LocalBlockCopy(
sourceDevice = testDisk,
targetDevice = testDisk,
sourceAllocation = VirtualStorageLvmAllocation(
capabilityId = testLvmCapability.id,
actualSize = testDisk.size,
path = "",
vgName = testLvmCapability.volumeGroupName,
hostId = testHost.id
),
allocationStep = CreateLv(
host = testHost,
disk = testDisk,
capability = testLvmCapability
)
)
}
assertThrows<IllegalStateException>("different hosts") {
LocalBlockCopy(
sourceDevice = testDisk,
targetDevice = testDisk.copy(id = randomUUID()),
sourceAllocation = VirtualStorageLvmAllocation(
capabilityId = testLvmCapability.id,
actualSize = testDisk.size,
path = "",
vgName = testLvmCapability.volumeGroupName,
hostId = randomUUID()
),
allocationStep = CreateLv(
host = testHost,
disk = testDisk,
capability = testLvmCapability
)
)
}
assertNotNull("All OK") {
LocalBlockCopy(
sourceDevice = testDisk,
targetDevice = testDisk.copy(id = randomUUID()),
sourceAllocation = VirtualStorageLvmAllocation(
capabilityId = testLvmCapability.id,
actualSize = testDisk.size,
path = "",
vgName = testLvmCapability.volumeGroupName,
hostId = testHost.id
),
allocationStep = CreateLv(
host = testHost,
disk = testDisk,
capability = testLvmCapability
)
)
}
}
@Test
fun take() {
assertTrue("basic behavior") {
val lvmVg1 = LvmStorageCapability(
id = randomUUID(),
size = 1.TB,
volumeGroupName = "vg-1",
physicalVolumes = mapOf(
"/dev/sda" to 1.TB
)
)
val lvmVg2 = LvmStorageCapability(
id = randomUUID(),
size = 1.TB,
volumeGroupName = "vg-2",
physicalVolumes = mapOf(
"/dev/sdb" to 1.TB
)
)
val host = testHost.copy(
capabilities = testHostCapabilities.copy(
blockDevices = listOf(
BlockDevice(deviceName = "/dev/sda", storageCapacity = 1.TB),
BlockDevice(deviceName = "/dev/sdb", storageCapacity = 1.TB)
),
storageCapabilities = listOf(lvmVg1, lvmVg2)
)
)
val targetDisk = testDisk.copy(
id = randomUUID()
)
val state = LocalBlockCopy(
sourceDevice = testDisk,
targetDevice = targetDisk,
allocationStep = CreateLv(capability = lvmVg1, disk = testDisk, host = host),
sourceAllocation = VirtualStorageLvmAllocation(
capabilityId = lvmVg1.id,
actualSize = testDisk.size,
path = "/dev/vg-1/${testDisk.id}",
vgName = lvmVg1.volumeGroupName,
hostId = host.id
)
).take(
OperationalState.fromLists(
hosts = listOf(host),
hostDyns = listOf(hostUp(host)),
vStorage = listOf(targetDisk, testDisk),
vStorageDyns = listOf(
VirtualStorageDeviceDynamic(
id = testDisk.id,
allocations = listOf(
VirtualStorageLvmAllocation(
hostId = host.id,
vgName = lvmVg2.volumeGroupName,
path = "/dev/${lvmVg2.volumeGroupName}/${testDisk.id}",
actualSize = testDisk.size,
capabilityId = lvmVg2.id
)
)
)
)
))
state.vStorage.getValue(targetDisk.id).dynamic!!.allocations.single().let {
it is VirtualStorageLvmAllocation
&& it.hostId == host.id
&& it.capabilityId == lvmVg1.id
}
}
}
@Test
fun otherReservations() {
assertTrue("reservation for the copied disk allocation, non-exclusive reservation for the host") {
val lvmVg1 = LvmStorageCapability(
id = randomUUID(),
size = 1.TB,
volumeGroupName = "vg-1",
physicalVolumes = mapOf(
"/dev/sda" to 1.TB
)
)
val lvmVg2 = LvmStorageCapability(
id = randomUUID(),
size = 1.TB,
volumeGroupName = "vg-2",
physicalVolumes = mapOf(
"/dev/sdb" to 1.TB
)
)
val host = testHost.copy(
capabilities = testHostCapabilities.copy(
blockDevices = listOf(
BlockDevice(deviceName = "/dev/sda", storageCapacity = 1.TB),
BlockDevice(deviceName = "/dev/sdb", storageCapacity = 1.TB)
),
storageCapabilities = listOf(lvmVg1, lvmVg2)
)
)
val targetDisk = testDisk.copy(id = randomUUID())
LocalBlockCopy(
sourceDevice = testDisk,
targetDevice = targetDisk,
allocationStep = CreateLv(capability = lvmVg1, disk = testDisk, host = host),
sourceAllocation = VirtualStorageLvmAllocation(
capabilityId = lvmVg1.id,
actualSize = testDisk.size,
path = "/dev/vg-1/${testDisk.id}",
vgName = lvmVg1.volumeGroupName,
hostId = host.id
)
).reservations().let { reservations ->
reservations.any {
it is VirtualStorageReservation && it.device == testDisk
} && reservations.any {
it is HostReservation && it.isShared()
}
}
}
}
}
|
apache-2.0
|
d2cea499b84b0725227e61165269b905
| 29.540541 | 100 | 0.662487 | 4.221046 | false | true | false | false |
jwren/intellij-community
|
platform/workspaceModel/jps/tests/testSrc/com/intellij/workspaceModel/ide/impl/jps/serialization/JpsProjectEntitiesLoaderTest.kt
|
2
|
13388
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide.impl.jps.serialization
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.application.ex.PathManagerEx
import com.intellij.openapi.application.runWriteActionAndWait
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ModuleSourceOrderEntry
import com.intellij.project.stateStore
import com.intellij.testFramework.HeavyPlatformTestCase
import com.intellij.util.io.write
import com.intellij.workspaceModel.ide.getInstance
import com.intellij.workspaceModel.storage.WorkspaceEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder
import com.intellij.workspaceModel.storage.bridgeEntities.*
import com.intellij.workspaceModel.storage.checkConsistency
import com.intellij.workspaceModel.storage.impl.url.toVirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.jetbrains.jps.model.serialization.module.JpsModuleRootModelSerializer
import org.jetbrains.jps.util.JpsPathUtil
import org.junit.Test
import java.io.File
class JpsProjectEntitiesLoaderTest : HeavyPlatformTestCase() {
@Test
fun `test load project`() {
val storage = loadProject(sampleDirBasedProjectFile)
checkSampleProjectConfiguration(storage, sampleDirBasedProjectFile)
}
@Test
fun `test load project in ipr format`() {
val projectFile = sampleFileBasedProjectFile
val storage = loadProject(projectFile)
storage.checkConsistency()
checkSampleProjectConfiguration(storage, projectFile.parentFile)
}
@Test
fun `test load module without NewModuleRootManager component`() {
val moduleFile = project.stateStore.projectBasePath.resolve("xxx.iml")
moduleFile.write("""
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
</module>
""".trimIndent())
val module = WriteAction.computeAndWait<Module, Exception> { ModuleManager.getInstance(project).loadModule(moduleFile) }
val orderEntries = ModuleRootManager.getInstance(module).orderEntries
assertEquals(1, orderEntries.size)
assertTrue(orderEntries[0] is ModuleSourceOrderEntry)
}
@Test
fun `test load module with empty NewModuleRootManager component`() {
val moduleFile = project.stateStore.projectBasePath.resolve("xxx.iml")
moduleFile.write("""
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" />
</module>
""".trimIndent())
val module = runWriteActionAndWait { ModuleManager.getInstance(project).loadModule(moduleFile) }
val orderEntries = ModuleRootManager.getInstance(module).orderEntries
assertEquals(1, orderEntries.size)
assertTrue(orderEntries[0] is ModuleSourceOrderEntry)
}
private fun checkSampleProjectConfiguration(storage: WorkspaceEntityStorage, projectDir: File) {
val projectUrl = projectDir.toVirtualFileUrl(VirtualFileUrlManager.getInstance(project))
val modules = storage.entities(ModuleEntity::class.java).sortedBy { it.name }.toList()
assertEquals(3, modules.size)
val mainModule = modules[0]
assertEquals("main", mainModule.name)
assertNull(mainModule.customImlData)
val mainJavaSettings = mainModule.javaSettings!!
assertEquals(true, mainJavaSettings.inheritedCompilerOutput)
assertEquals(true, mainJavaSettings.excludeOutput)
assertNull(mainJavaSettings.compilerOutput)
assertNull(mainJavaSettings.compilerOutputForTests)
assertEquals(projectDir.absolutePath, JpsPathUtil.urlToOsPath(assertOneElement(mainModule.contentRoots.toList()).url.url))
val mainModuleSrc = assertOneElement(mainModule.sourceRoots.toList())
assertEquals(File(projectDir, "src").absolutePath, JpsPathUtil.urlToOsPath(mainModuleSrc.url.url))
assertEquals(JpsModuleRootModelSerializer.JAVA_SOURCE_ROOT_TYPE_ID, mainModuleSrc.rootType)
assertEquals(6, mainModule.dependencies.size)
assertEquals(ModuleDependencyItem.InheritedSdkDependency, mainModule.dependencies[0])
assertEquals(ModuleDependencyItem.ModuleSourceDependency, mainModule.dependencies[1])
assertEquals("log4j", (mainModule.dependencies[2] as ModuleDependencyItem.Exportable.LibraryDependency).library.name)
assertFalse((mainModule.dependencies[2] as ModuleDependencyItem.Exportable.LibraryDependency).exported)
assertEquals(ModuleDependencyItem.DependencyScope.COMPILE, (mainModule.dependencies[2] as ModuleDependencyItem.Exportable.LibraryDependency).scope)
assertEquals(ModuleDependencyItem.DependencyScope.TEST, (mainModule.dependencies[3] as ModuleDependencyItem.Exportable.LibraryDependency).scope)
assertTrue((mainModule.dependencies[4] as ModuleDependencyItem.Exportable.LibraryDependency).exported)
assertEquals("util", (mainModule.dependencies[5] as ModuleDependencyItem.Exportable.ModuleDependency).module.name)
val utilModule = modules[1]
assertEquals("util", utilModule.name)
assertEquals("""<component>
<annotation-paths>
<root url="$projectUrl/lib/anno" />
</annotation-paths>
<javadoc-paths>
<root url="$projectUrl/lib/javadoc" />
</javadoc-paths>
</component>""", utilModule.customImlData!!.rootManagerTagCustomData)
val utilJavaSettings = utilModule.javaSettings!!
assertEquals(false, utilJavaSettings.inheritedCompilerOutput)
assertEquals(true, utilJavaSettings.excludeOutput)
assertEquals("JDK_1_7", utilJavaSettings.languageLevelId)
assertEquals("$projectUrl/out/production-util", utilJavaSettings.compilerOutput?.url)
assertEquals("$projectUrl/out/test-util", utilJavaSettings.compilerOutputForTests?.url)
val utilContentRoot = assertOneElement(utilModule.contentRoots.toList())
assertEquals("$projectUrl/util", utilContentRoot.url.url)
assertEquals("$projectUrl/util/exc", assertOneElement(utilContentRoot.excludedUrls).url)
assertEquals(listOf("*.xml", "cvs"), utilContentRoot.excludedPatterns)
val utilModuleSrc = assertOneElement(utilModule.sourceRoots.toList())
assertEquals("$projectUrl/util/src", utilModuleSrc.url.url)
val utilModuleLibraries = utilModule.getModuleLibraries(storage).sortedBy { it.name }.toList()
val log4jModuleLibrary = utilModuleLibraries[1]
assertEquals("log4j", log4jModuleLibrary.name)
val log4jRoot = log4jModuleLibrary.roots[0]
assertTrue(log4jRoot.url.url.contains("log4j.jar"))
assertEquals("CLASSES", log4jRoot.type.name)
assertEquals(LibraryRoot.InclusionOptions.ROOT_ITSELF, log4jRoot.inclusionOptions)
assertEquals("xxx", modules[2].name)
assertNull(modules[2].customImlData)
val xxxJavaSettings = modules[2].javaSettings!!
assertEquals(false, xxxJavaSettings.inheritedCompilerOutput)
assertEquals(true, xxxJavaSettings.excludeOutput)
assertEquals("$projectUrl/xxx/output", xxxJavaSettings.compilerOutput?.url)
assertNull(xxxJavaSettings.compilerOutputForTests)
val projectLibraries = storage.projectLibraries.sortedBy { it.name }.toList()
assertEquals("jarDir", projectLibraries[0].name)
val roots = projectLibraries[0].roots
assertEquals(2, roots.size)
assertEquals("CLASSES", roots[0].type.name)
assertEquals(LibraryRoot.InclusionOptions.ARCHIVES_UNDER_ROOT, roots[0].inclusionOptions)
assertEquals("SOURCES", roots[1].type.name)
assertEquals(LibraryRoot.InclusionOptions.ARCHIVES_UNDER_ROOT, roots[1].inclusionOptions)
val junitProjectLibrary = projectLibraries[1]
assertEquals("junit", junitProjectLibrary.name)
val artifacts = storage.entities(ArtifactEntity::class.java).sortedBy { it.name }.toList()
assertEquals(2, artifacts.size)
assertEquals("dir", artifacts[0].name)
assertTrue(artifacts[0].includeInProjectBuild)
assertEquals(File(projectDir, "out/artifacts/dir").absolutePath, JpsPathUtil.urlToOsPath(artifacts[0].outputUrl!!.url))
val children = artifacts[0].rootElement!!.children.sortedBy { it::class.qualifiedName }.toList()
assertEquals(2, children.size)
val innerJar = children[0] as ArchivePackagingElementEntity
assertEquals("x.jar", innerJar.fileName)
assertEquals(utilModule, (innerJar.children.single() as ModuleOutputPackagingElementEntity).module!!.resolve(storage))
val innerDir = children[1] as DirectoryPackagingElementEntity
assertEquals("lib", innerDir.directoryName)
val innerChildren = innerDir.children.toList()
assertEquals(5, innerChildren.size)
assertNotNull(innerChildren.find { it is LibraryFilesPackagingElementEntity && it.library?.resolve(storage) == log4jModuleLibrary })
assertNotNull(innerChildren.find { it is LibraryFilesPackagingElementEntity && it.library?.resolve(storage) == junitProjectLibrary })
assertEquals(File(projectDir, "main.iml").absolutePath, JpsPathUtil.urlToOsPath(innerChildren.filterIsInstance<FileCopyPackagingElementEntity>().single().filePath!!.url))
assertEquals(File(projectDir, "lib/junit-anno").absolutePath, JpsPathUtil.urlToOsPath(innerChildren.filterIsInstance<DirectoryCopyPackagingElementEntity>().single().filePath!!.url))
innerChildren.filterIsInstance<ExtractedDirectoryPackagingElementEntity>().single().let {
assertEquals(File(projectDir, "lib/junit.jar").absolutePath, JpsPathUtil.urlToOsPath(it.filePath!!.url))
assertEquals("/junit/", it.pathInArchive)
}
assertEquals("jar", artifacts[1].name)
assertEquals(File(projectDir, "out/artifacts/jar").absolutePath, JpsPathUtil.urlToOsPath(artifacts[1].outputUrl!!.url))
val archiveRoot = artifacts[1].rootElement!! as ArchivePackagingElementEntity
assertEquals("jar.jar", archiveRoot.fileName)
val archiveChildren = archiveRoot.children.toList()
assertEquals(3, archiveChildren.size)
assertEquals(artifacts[0], archiveChildren.filterIsInstance<ArtifactOutputPackagingElementEntity>().single().artifact!!.resolve(storage))
}
@Test
fun `test custom packaging elements`() {
val projectDir = PathManagerEx.findFileUnderCommunityHome("platform/workspaceModel/jps/tests/testData/serialization/customPackagingElements/javaeeSampleProject.ipr")
val storage = loadProject(projectDir)
val artifacts = storage.entities(ArtifactEntity::class.java).sortedBy { it.name }.toList()
assertEquals(6, artifacts.size)
assertEquals("javaeeSampleProject:war exploded", artifacts[5].name)
val artifactChildren = artifacts[5].rootElement!!.children.toList().sortedBy { it::class.qualifiedName }
assertEquals(2, artifactChildren.size)
val customElement = artifactChildren.filterIsInstance<CustomPackagingElementEntity>().single()
assertEquals("javaee-facet-resources", customElement.typeId)
assertEquals("<element id=\"javaee-facet-resources\" facet=\"javaeeSampleProject/web/Web\" />", customElement.propertiesXmlTag)
}
fun `test custom source root`() {
val projectDir = PathManagerEx.findFileUnderCommunityHome("platform/workspaceModel/jps/tests/testData/serialization/customSourceRoot/customSourceRoot.ipr")
val storage = loadProject(projectDir)
val module = assertOneElement(storage.entities(ModuleEntity::class.java).toList())
val sourceRoot = assertOneElement(module.sourceRoots.toList())
assertEquals("erlang-include", sourceRoot.rootType)
assertNull(sourceRoot.asCustomSourceRoot())
}
fun `test load facets`() {
val projectDir = PathManagerEx.findFileUnderCommunityHome("platform/workspaceModel/jps/tests/testData/serialization/facets/facets.ipr")
val storage = loadProject(projectDir)
val modules = storage.entities(ModuleEntity::class.java).associateBy { it.name }
val single = modules.getValue("single").facets.single()
assertEquals("foo", single.facetType)
assertEquals("Foo", single.name)
assertEquals("""
<configuration>
<data />
</configuration>""".trimIndent(), single.configurationXmlTag)
val two = modules.getValue("two").facets.toList()
assertEquals(setOf("a", "b"), two.mapTo(HashSet()) { it.name })
val twoReversed = modules.getValue("two.reversed").facets.toList()
assertEquals(setOf("a", "b"), twoReversed.mapTo(HashSet()) { it.name })
val subFacets = modules.getValue("subFacets").facets.sortedBy { it.name }.toList()
assertEquals(listOf("Bar", "Foo"), subFacets.map { it.name })
val (bar, foo) = subFacets
assertEquals("Foo", bar.underlyingFacet!!.name)
assertEquals("""
<configuration>
<data />
</configuration>""".trimIndent(), foo.configurationXmlTag)
assertEquals("""
<configuration>
<data2 />
</configuration>""".trimIndent(), bar.configurationXmlTag)
}
private fun loadProject(projectFile: File): WorkspaceEntityStorage {
val storageBuilder = WorkspaceEntityStorageBuilder.create()
val virtualFileManager: VirtualFileUrlManager = VirtualFileUrlManager.getInstance(project)
loadProject(projectFile.asConfigLocation(virtualFileManager), storageBuilder, virtualFileManager)
return storageBuilder.toStorage()
}
}
|
apache-2.0
|
61dfa4918e317fadc3e306c19fd51371
| 53.868852 | 185 | 0.767777 | 4.98622 | false | true | false | false |
androidx/androidx
|
tracing/tracing-perfetto/src/main/java/androidx/tracing/perfetto/TracingReceiver.kt
|
3
|
5357
|
/*
* 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.tracing.perfetto
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.JsonWriter
import androidx.annotation.RestrictTo
import androidx.annotation.RestrictTo.Scope.LIBRARY
import androidx.tracing.perfetto.Tracing.EnableTracingResponse
import androidx.tracing.perfetto.PerfettoHandshake.EnableTracingResponse
import androidx.tracing.perfetto.PerfettoHandshake.RequestKeys.ACTION_ENABLE_TRACING
import androidx.tracing.perfetto.PerfettoHandshake.RequestKeys.KEY_PATH
import androidx.tracing.perfetto.PerfettoHandshake.ResponseExitCodes.RESULT_CODE_ERROR_OTHER
import androidx.tracing.perfetto.PerfettoHandshake.ResponseKeys
import java.io.File
import java.io.StringWriter
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
/** Allows for enabling tracing in an app using a broadcast. @see [ACTION_ENABLE_TRACING] */
@RestrictTo(LIBRARY)
class TracingReceiver : BroadcastReceiver() {
private val executor by lazy {
ThreadPoolExecutor(
/* corePoolSize = */ 0,
/* maximumPoolSize = */ 1,
/* keepAliveTime = */ 10, // gives time for tooling to side-load the .so file
/* unit = */ TimeUnit.SECONDS,
/* workQueue = */ LinkedBlockingQueue()
)
}
// TODO: check value on app start
override fun onReceive(context: Context?, intent: Intent?) {
if (intent == null || intent.action != ACTION_ENABLE_TRACING) return
// Path to the provided library binary file (optional). If not provided, local library files
// will be used if present.
val srcPath = intent.extras?.getString(KEY_PATH)
val pendingResult = goAsync()
executor.execute {
try {
val response = enableTracing(srcPath, context)
pendingResult.setResult(response.exitCode, response.toJsonString(), null)
} finally {
pendingResult.finish()
}
}
}
private fun enableTracing(srcPath: String?, context: Context?): EnableTracingResponse =
when {
Build.VERSION.SDK_INT < Build.VERSION_CODES.R -> {
// TODO(234351579): Support API < 30
EnableTracingResponse(
RESULT_CODE_ERROR_OTHER,
"SDK version not supported. Current minimum SDK = ${Build.VERSION_CODES.R}"
)
}
srcPath != null && context != null -> {
try {
val dstFile = copyExternalLibraryFile(context, srcPath)
Tracing.enable(dstFile, context)
} catch (e: Exception) {
EnableTracingResponse(RESULT_CODE_ERROR_OTHER, e)
}
}
srcPath != null && context == null -> {
EnableTracingResponse(
RESULT_CODE_ERROR_OTHER,
"Cannot copy source file: $srcPath without access to a Context instance."
)
}
else -> {
// Library path was not provided, trying to resolve using app's local library files.
Tracing.enable()
}
}
private fun copyExternalLibraryFile(
context: Context,
srcPath: String
): File {
// Prepare a location to copy the library into with the following properties:
// 1) app has exclusive write access in
// 2) app can load binaries from
val abi: String = File(context.applicationInfo.nativeLibraryDir).name // e.g. arm64
val dstDir = context.cacheDir.resolve("lib/$abi")
dstDir.mkdirs()
// Copy the library file over
//
// TODO: load into memory and verify in-memory to prevent from copying a malicious
// library into app's local files. Use SHA or Signature to verify the binaries.
val srcFile = File(srcPath)
val dstFile = dstDir.resolve(srcFile.name)
srcFile.copyTo(dstFile, overwrite = true)
return dstFile
}
private fun EnableTracingResponse.toJsonString(): String {
val output = StringWriter()
JsonWriter(output).use {
it.beginObject()
it.name(ResponseKeys.KEY_EXIT_CODE)
it.value(exitCode)
it.name(ResponseKeys.KEY_REQUIRED_VERSION)
it.value(requiredVersion)
message?.let { msg ->
it.name(ResponseKeys.KEY_MESSAGE)
it.value(msg)
}
it.endObject()
}
return output.toString()
}
}
|
apache-2.0
|
817ccf594d6d029d9ad805497ccdb6a5
| 36.201389 | 100 | 0.633564 | 4.84358 | false | false | false | false |
androidx/androidx
|
window/window/src/main/java/androidx/window/layout/adapter/extensions/ExtensionsWindowLayoutInfoAdapter.kt
|
3
|
3648
|
/*
* 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.window.layout.adapter.extensions
import androidx.window.extensions.layout.FoldingFeature as OEMFoldingFeature
import androidx.window.extensions.layout.WindowLayoutInfo as OEMWindowLayoutInfo
import android.app.Activity
import androidx.window.core.Bounds
import androidx.window.layout.FoldingFeature
import androidx.window.layout.FoldingFeature.State.Companion.FLAT
import androidx.window.layout.FoldingFeature.State.Companion.HALF_OPENED
import androidx.window.layout.HardwareFoldingFeature
import androidx.window.layout.HardwareFoldingFeature.Type.Companion.FOLD
import androidx.window.layout.HardwareFoldingFeature.Type.Companion.HINGE
import androidx.window.layout.WindowLayoutInfo
import androidx.window.layout.WindowMetricsCalculatorCompat.computeCurrentWindowMetrics
internal object ExtensionsWindowLayoutInfoAdapter {
internal fun translate(activity: Activity, oemFeature: OEMFoldingFeature): FoldingFeature? {
val type = when (oemFeature.type) {
OEMFoldingFeature.TYPE_FOLD -> FOLD
OEMFoldingFeature.TYPE_HINGE -> HINGE
else -> return null
}
val state = when (oemFeature.state) {
OEMFoldingFeature.STATE_FLAT -> FLAT
OEMFoldingFeature.STATE_HALF_OPENED -> HALF_OPENED
else -> return null
}
val bounds = Bounds(oemFeature.bounds)
return if (validBounds(activity, bounds)) {
HardwareFoldingFeature(Bounds(oemFeature.bounds), type, state)
} else {
null
}
}
internal fun translate(activity: Activity, info: OEMWindowLayoutInfo): WindowLayoutInfo {
val features = info.displayFeatures.mapNotNull { feature ->
when (feature) {
is OEMFoldingFeature -> translate(activity, feature)
else -> null
}
}
return WindowLayoutInfo(features)
}
/**
* Validate the bounds for a [FoldingFeature] within a given [Activity]. Check the following
* <ul>
* <li>Bounds are not 0</li>
* <li>Bounds are either full width or full height</li>
* <li>Bounds do not take up the entire window</li>
* </ul>
*
* @param activity housing the [FoldingFeature].
* @param bounds the bounds of a [FoldingFeature]
* @return true if the bounds are valid for the [Activity], false otherwise.
*/
private fun validBounds(activity: Activity, bounds: Bounds): Boolean {
val windowBounds = computeCurrentWindowMetrics(activity).bounds
if (bounds.isZero) {
return false
}
if (bounds.width != windowBounds.width() && bounds.height != windowBounds.height()) {
return false
}
if (bounds.width < windowBounds.width() && bounds.height < windowBounds.height()) {
return false
}
if (bounds.width == windowBounds.width() && bounds.height == windowBounds.height()) {
return false
}
return true
}
}
|
apache-2.0
|
98976ec5937db76e166fad3f367fedbd
| 38.663043 | 96 | 0.684211 | 4.768627 | false | false | false | false |
GunoH/intellij-community
|
platform/lang-impl/src/com/intellij/ide/bookmark/actions/AddAnotherBookmarkAction.kt
|
2
|
1344
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.bookmark.actions
import com.intellij.ide.bookmark.BookmarkBundle
import com.intellij.ide.bookmark.LineBookmark
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
internal class AddAnotherBookmarkAction : DumbAwareAction(BookmarkBundle.messagePointer("bookmark.add.another.action.text")) {
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT
override fun update(event: AnActionEvent) {
event.presentation.isEnabledAndVisible = process(event, false)
}
override fun actionPerformed(event: AnActionEvent) {
process(event, true)
}
private fun process(event: AnActionEvent, perform: Boolean): Boolean {
if (event.contextBookmarks != null) { return false }
val manager = event.bookmarksManager ?: return false
val bookmark = event.contextBookmark ?: return false
if (bookmark is LineBookmark) return false
val type = manager.getType(bookmark) ?: return false
if (perform) manager.add(bookmark, type)
return true
}
init {
isEnabledInModalContext = true
}
}
|
apache-2.0
|
33f5f9f6a4a5525724ad40faf11264b1
| 37.4 | 158 | 0.775298 | 4.682927 | false | false | false | false |
siosio/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/CanBeValInspection.kt
|
1
|
7837
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.IntentionWrapper
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.search.searches.ReferencesSearch
import org.jetbrains.kotlin.cfg.pseudocode.Pseudocode
import org.jetbrains.kotlin.cfg.pseudocode.PseudocodeUtil
import org.jetbrains.kotlin.cfg.pseudocode.containingDeclarationForPseudocode
import org.jetbrains.kotlin.cfg.pseudocode.instructions.Instruction
import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionWithNext
import org.jetbrains.kotlin.cfg.pseudocode.instructions.eval.AccessTarget
import org.jetbrains.kotlin.cfg.pseudocode.instructions.eval.WriteValueInstruction
import org.jetbrains.kotlin.cfg.pseudocode.instructions.special.LocalFunctionDeclarationInstruction
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.quickfix.ChangeVariableMutabilityFix
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.idea.references.readWriteAccess
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class CanBeValInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return object : KtVisitorVoid() {
private val pseudocodeCache = HashMap<KtDeclaration, Pseudocode>()
override fun visitDeclaration(declaration: KtDeclaration) {
super.visitDeclaration(declaration)
if (declaration is KtValVarKeywordOwner && canBeVal(declaration, pseudocodeCache, ignoreNotUsedVals = true)) {
reportCanBeVal(declaration)
}
}
private fun reportCanBeVal(declaration: KtValVarKeywordOwner) {
val keyword = declaration.valOrVarKeyword!!
val problemDescriptor = holder.manager.createProblemDescriptor(
keyword,
keyword,
KotlinBundle.message("variable.is.never.modified.and.can.be.declared.immutable.using.val"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
isOnTheFly,
IntentionWrapper(ChangeVariableMutabilityFix(declaration, false), declaration.containingFile)
)
holder.registerProblem(problemDescriptor)
}
}
}
companion object {
fun canBeVal(
declaration: KtDeclaration,
pseudocodeCache: HashMap<KtDeclaration, Pseudocode> = HashMap(),
ignoreNotUsedVals: Boolean
): Boolean {
when (declaration) {
is KtProperty -> {
if (declaration.isVar && declaration.isLocal && !declaration.hasModifier(KtTokens.LATEINIT_KEYWORD) &&
canBeVal(
declaration,
declaration.hasInitializer() || declaration.hasDelegateExpression(),
listOf(declaration),
ignoreNotUsedVals,
pseudocodeCache
)
) {
return true
}
}
is KtDestructuringDeclaration -> {
val entries = declaration.entries
if (declaration.isVar && entries.all { canBeVal(it, true, entries, ignoreNotUsedVals, pseudocodeCache) }) {
return true
}
}
}
return false
}
private fun canBeVal(
declaration: KtVariableDeclaration,
hasInitializerOrDelegate: Boolean,
allDeclarations: Collection<KtVariableDeclaration>,
ignoreNotUsedVals: Boolean,
pseudocodeCache: MutableMap<KtDeclaration, Pseudocode>
): Boolean {
if (ignoreNotUsedVals && allDeclarations.all { ReferencesSearch.search(it, it.useScope).none() }) {
// do not report for unused var's (otherwise we'll get it highlighted immediately after typing the declaration
return false
}
return if (hasInitializerOrDelegate) {
val hasWriteUsages = ReferencesSearch.search(declaration, declaration.useScope).any {
(it as? KtSimpleNameReference)?.element?.readWriteAccess(useResolveForReadWrite = true)?.isWrite == true
}
!hasWriteUsages
} else {
val bindingContext = declaration.analyze(BodyResolveMode.FULL)
val pseudocode = pseudocode(declaration, bindingContext, pseudocodeCache) ?: return false
val descriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, declaration] ?: return false
val writeInstructions = pseudocode.collectWriteInstructions(descriptor)
if (writeInstructions.isEmpty()) return false // incorrect code - do not report
writeInstructions.none { it.owner !== pseudocode || canReach(it, writeInstructions) }
}
}
private fun pseudocode(
element: KtElement,
bindingContext: BindingContext,
pseudocodeCache: MutableMap<KtDeclaration, Pseudocode>
): Pseudocode? {
val declaration = element.containingDeclarationForPseudocode ?: return null
return pseudocodeCache.getOrPut(declaration) { PseudocodeUtil.generatePseudocode(declaration, bindingContext) }
}
private fun Pseudocode.collectWriteInstructions(descriptor: DeclarationDescriptor): Set<WriteValueInstruction> =
with(instructionsIncludingDeadCode) {
filterIsInstance<WriteValueInstruction>()
.asSequence()
.filter { (it.target as? AccessTarget.Call)?.resolvedCall?.resultingDescriptor == descriptor }
.toSet() +
filterIsInstance<LocalFunctionDeclarationInstruction>()
.map { it.body.collectWriteInstructions(descriptor) }
.flatten()
}
private fun canReach(
from: Instruction,
targets: Set<Instruction>,
visited: HashSet<Instruction> = HashSet<Instruction>()
): Boolean {
// special algorithm for linear code to avoid too deep recursion
var instruction = from
while (instruction is InstructionWithNext) {
if (instruction is LocalFunctionDeclarationInstruction) {
if (canReach(instruction.body.enterInstruction, targets, visited)) return true
}
val next = instruction.next ?: return false
if (next in visited) return false
if (next in targets) return true
visited.add(next)
instruction = next
}
for (next in instruction.nextInstructions) {
if (next in visited) continue
if (next in targets) return true
visited.add(next)
if (canReach(next, targets, visited)) return true
}
return false
}
}
}
|
apache-2.0
|
f2e483d127f5fbb1f56602f2c2294bed
| 47.08589 | 158 | 0.63315 | 6.033102 | false | false | false | false |
K0zka/kerub
|
src/main/kotlin/com/github/kerubistan/kerub/services/impl/TemplateServiceImpl.kt
|
2
|
2029
|
package com.github.kerubistan.kerub.services.impl
import com.github.kerubistan.kerub.data.TemplateDao
import com.github.kerubistan.kerub.data.VirtualMachineDao
import com.github.kerubistan.kerub.data.VirtualStorageDeviceDao
import com.github.kerubistan.kerub.model.Template
import com.github.kerubistan.kerub.model.expectations.CloneOfStorageExpectation
import com.github.kerubistan.kerub.security.AssetAccessController
import com.github.kerubistan.kerub.services.TemplateService
import com.github.kerubistan.kerub.utils.byId
import java.util.UUID
class TemplateServiceImpl(
dao: TemplateDao,
private val vmDao: VirtualMachineDao,
private val virtualStorageDeviceDao: VirtualStorageDeviceDao,
accessController: AssetAccessController
) : TemplateService, AbstractAssetService<Template>(accessController, dao, "template") {
override fun buildFromVm(vmId: UUID): Template {
val vm = assertExist("vm", accessController.doAndCheck { vmDao[vmId] }, vmId)
val storageDevices = virtualStorageDeviceDao.list(vm.virtualStorageLinks.map { it.virtualStorageId })
val storageDeicesById = storageDevices.byId()
val clonedStorageDevices = storageDevices.filterNot { it.readOnly }.map { sourceStorageDevice ->
val newDevice = sourceStorageDevice.copy(
id = UUID.randomUUID(),
expectations = sourceStorageDevice.expectations
+ CloneOfStorageExpectation(sourceStorageId = sourceStorageDevice.id)
)
sourceStorageDevice.id to newDevice
}.toMap()
virtualStorageDeviceDao.addAll(clonedStorageDevices.values)
val templateVm = vm.copy(
virtualStorageLinks = vm.virtualStorageLinks.map {
val storage = requireNotNull(storageDeicesById[it.virtualStorageId])
if (storage.readOnly) {
it
} else {
it.copy(
virtualStorageId = requireNotNull(clonedStorageDevices[it.virtualStorageId]).id
)
}
}
)
val template = Template(
vm = templateVm,
name = "template from ${vm.name}",
vmNamePrefix = ""
)
dao.add(template)
return template
}
}
|
apache-2.0
|
b885795808729d79759031ec63d3f083
| 36.592593 | 103 | 0.77378 | 4.058 | false | false | false | false |
googlearchive/android-FingerprintDialog
|
kotlinApp/app/src/main/java/com/example/android/fingerprintdialog/MainActivity.kt
|
3
|
13541
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.example.android.fingerprintdialog
import android.app.KeyguardManager
import android.content.Intent
import android.content.SharedPreferences
import android.hardware.fingerprint.FingerprintManager
import android.os.Bundle
import android.preference.PreferenceManager
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyPermanentlyInvalidatedException
import android.security.keystore.KeyProperties
import android.security.keystore.KeyProperties.BLOCK_MODE_CBC
import android.security.keystore.KeyProperties.ENCRYPTION_PADDING_PKCS7
import android.security.keystore.KeyProperties.KEY_ALGORITHM_AES
import android.support.v7.app.AppCompatActivity
import android.util.Base64
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import java.io.IOException
import java.security.InvalidAlgorithmParameterException
import java.security.InvalidKeyException
import java.security.KeyStore
import java.security.KeyStoreException
import java.security.NoSuchAlgorithmException
import java.security.NoSuchProviderException
import java.security.UnrecoverableKeyException
import java.security.cert.CertificateException
import javax.crypto.BadPaddingException
import javax.crypto.Cipher
import javax.crypto.IllegalBlockSizeException
import javax.crypto.KeyGenerator
import javax.crypto.NoSuchPaddingException
import javax.crypto.SecretKey
/**
* Main entry point for the sample, showing a backpack and "Purchase" button.
*/
class MainActivity : AppCompatActivity(),
FingerprintAuthenticationDialogFragment.Callback {
private lateinit var keyStore: KeyStore
private lateinit var keyGenerator: KeyGenerator
private lateinit var sharedPreferences: SharedPreferences
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(findViewById(R.id.toolbar))
setupKeyStoreAndKeyGenerator()
val (defaultCipher: Cipher, cipherNotInvalidated: Cipher) = setupCiphers()
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
setUpPurchaseButtons(cipherNotInvalidated, defaultCipher)
}
/**
* Enables or disables purchase buttons and sets the appropriate click listeners.
*
* @param cipherNotInvalidated cipher for the not invalidated purchase button
* @param defaultCipher the default cipher, used for the purchase button
*/
private fun setUpPurchaseButtons(cipherNotInvalidated: Cipher, defaultCipher: Cipher) {
val purchaseButton = findViewById<Button>(R.id.purchase_button)
val purchaseButtonNotInvalidated =
findViewById<Button>(R.id.purchase_button_not_invalidated)
purchaseButtonNotInvalidated.run {
isEnabled = true
setOnClickListener(PurchaseButtonClickListener(
cipherNotInvalidated, KEY_NAME_NOT_INVALIDATED))
}
val keyguardManager = getSystemService(KeyguardManager::class.java)
if (!keyguardManager.isKeyguardSecure) {
// Show a message that the user hasn't set up a fingerprint or lock screen.
showToast(getString(R.string.setup_lock_screen))
purchaseButton.isEnabled = false
purchaseButtonNotInvalidated.isEnabled = false
return
}
val fingerprintManager = getSystemService(FingerprintManager::class.java)
if (!fingerprintManager.hasEnrolledFingerprints()) {
purchaseButton.isEnabled = false
// This happens when no fingerprints are registered.
showToast(getString(R.string.register_fingerprint))
return
}
createKey(DEFAULT_KEY_NAME)
createKey(KEY_NAME_NOT_INVALIDATED, false)
purchaseButton.run {
isEnabled = true
setOnClickListener(PurchaseButtonClickListener(defaultCipher, DEFAULT_KEY_NAME))
}
}
/**
* Sets up KeyStore and KeyGenerator
*/
private fun setupKeyStoreAndKeyGenerator() {
try {
keyStore = KeyStore.getInstance(ANDROID_KEY_STORE)
} catch (e: KeyStoreException) {
throw RuntimeException("Failed to get an instance of KeyStore", e)
}
try {
keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM_AES, ANDROID_KEY_STORE)
} catch (e: Exception) {
when (e) {
is NoSuchAlgorithmException,
is NoSuchProviderException ->
throw RuntimeException("Failed to get an instance of KeyGenerator", e)
else -> throw e
}
}
}
/**
* Sets up default cipher and a non-invalidated cipher
*/
private fun setupCiphers(): Pair<Cipher, Cipher> {
val defaultCipher: Cipher
val cipherNotInvalidated: Cipher
try {
val cipherString = "$KEY_ALGORITHM_AES/$BLOCK_MODE_CBC/$ENCRYPTION_PADDING_PKCS7"
defaultCipher = Cipher.getInstance(cipherString)
cipherNotInvalidated = Cipher.getInstance(cipherString)
} catch (e: Exception) {
when (e) {
is NoSuchAlgorithmException,
is NoSuchPaddingException ->
throw RuntimeException("Failed to get an instance of Cipher", e)
else -> throw e
}
}
return Pair(defaultCipher, cipherNotInvalidated)
}
/**
* Initialize the [Cipher] instance with the created key in the [createKey] method.
*
* @param keyName the key name to init the cipher
* @return `true` if initialization succeeded, `false` if the lock screen has been disabled or
* reset after key generation, or if a fingerprint was enrolled after key generation.
*/
private fun initCipher(cipher: Cipher, keyName: String): Boolean {
try {
keyStore.load(null)
cipher.init(Cipher.ENCRYPT_MODE, keyStore.getKey(keyName, null) as SecretKey)
return true
} catch (e: Exception) {
when (e) {
is KeyPermanentlyInvalidatedException -> return false
is KeyStoreException,
is CertificateException,
is UnrecoverableKeyException,
is IOException,
is NoSuchAlgorithmException,
is InvalidKeyException -> throw RuntimeException("Failed to init Cipher", e)
else -> throw e
}
}
}
/**
* Proceed with the purchase operation
*
* @param withFingerprint `true` if the purchase was made by using a fingerprint
* @param crypto the Crypto object
*/
override fun onPurchased(withFingerprint: Boolean, crypto: FingerprintManager.CryptoObject?) {
if (withFingerprint) {
// If the user authenticated with fingerprint, verify using cryptography and then show
// the confirmation message.
if (crypto != null) {
tryEncrypt(crypto.cipher)
}
} else {
// Authentication happened with backup password. Just show the confirmation message.
showConfirmation()
}
}
// Show confirmation message. Also show crypto information if fingerprint was used.
private fun showConfirmation(encrypted: ByteArray? = null) {
findViewById<View>(R.id.confirmation_message).visibility = View.VISIBLE
if (encrypted != null) {
findViewById<TextView>(R.id.encrypted_message).run {
visibility = View.VISIBLE
text = Base64.encodeToString(encrypted, 0 /* flags */)
}
}
}
/**
* Tries to encrypt some data with the generated key from [createKey]. This only works if the
* user just authenticated via fingerprint.
*/
private fun tryEncrypt(cipher: Cipher) {
try {
showConfirmation(cipher.doFinal(SECRET_MESSAGE.toByteArray()))
} catch (e: Exception) {
when (e) {
is BadPaddingException,
is IllegalBlockSizeException -> {
Toast.makeText(this, "Failed to encrypt the data with the generated key. "
+ "Retry the purchase", Toast.LENGTH_LONG).show()
Log.e(TAG, "Failed to encrypt the data with the generated key. ${e.message}")
}
else -> throw e
}
}
}
/**
* Creates a symmetric key in the Android Key Store which can only be used after the user has
* authenticated with a fingerprint.
*
* @param keyName the name of the key to be created
* @param invalidatedByBiometricEnrollment if `false` is passed, the created key will not be
* invalidated even if a new fingerprint is enrolled. The default value is `true` - the key will
* be invalidated if a new fingerprint is enrolled.
*/
override fun createKey(keyName: String, invalidatedByBiometricEnrollment: Boolean) {
// The enrolling flow for fingerprint. This is where you ask the user to set up fingerprint
// for your flow. Use of keys is necessary if you need to know if the set of enrolled
// fingerprints has changed.
try {
keyStore.load(null)
val keyProperties = KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
val builder = KeyGenParameterSpec.Builder(keyName, keyProperties)
.setBlockModes(BLOCK_MODE_CBC)
.setUserAuthenticationRequired(true)
.setEncryptionPaddings(ENCRYPTION_PADDING_PKCS7)
.setInvalidatedByBiometricEnrollment(invalidatedByBiometricEnrollment)
keyGenerator.run {
init(builder.build())
generateKey()
}
} catch (e: Exception) {
when (e) {
is NoSuchAlgorithmException,
is InvalidAlgorithmParameterException,
is CertificateException,
is IOException -> throw RuntimeException(e)
else -> throw e
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.action_settings) {
val intent = Intent(this, SettingsActivity::class.java)
startActivity(intent)
return true
}
return super.onOptionsItemSelected(item)
}
private inner class PurchaseButtonClickListener internal constructor(
internal var cipher: Cipher,
internal var keyName: String
) : View.OnClickListener {
override fun onClick(view: View) {
findViewById<View>(R.id.confirmation_message).visibility = View.GONE
findViewById<View>(R.id.encrypted_message).visibility = View.GONE
val fragment = FingerprintAuthenticationDialogFragment()
fragment.setCryptoObject(FingerprintManager.CryptoObject(cipher))
fragment.setCallback(this@MainActivity)
// Set up the crypto object for later, which will be authenticated by fingerprint usage.
if (initCipher(cipher, keyName)) {
// Show the fingerprint dialog. The user has the option to use the fingerprint with
// crypto, or can fall back to using a server-side verified password.
val useFingerprintPreference = sharedPreferences
.getBoolean(getString(R.string.use_fingerprint_to_authenticate_key), true)
if (useFingerprintPreference) {
fragment.setStage(Stage.FINGERPRINT)
} else {
fragment.setStage(Stage.PASSWORD)
}
} else {
// This happens if the lock screen has been disabled or or a fingerprint was
// enrolled. Thus, show the dialog to authenticate with their password first and ask
// the user if they want to authenticate with a fingerprint in the future.
fragment.setStage(Stage.NEW_FINGERPRINT_ENROLLED)
}
fragment.show(fragmentManager, DIALOG_FRAGMENT_TAG)
}
}
companion object {
private val ANDROID_KEY_STORE = "AndroidKeyStore"
private val DIALOG_FRAGMENT_TAG = "myFragment"
private val KEY_NAME_NOT_INVALIDATED = "key_not_invalidated"
private val SECRET_MESSAGE = "Very secret message"
private val TAG = MainActivity::class.java.simpleName
}
}
|
apache-2.0
|
dbdea673aba3b64cc4be962625c37312
| 39.786145 | 100 | 0.656672 | 5.252521 | false | false | false | false |
GunoH/intellij-community
|
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/bridgeEntities/artifact.kt
|
1
|
23460
|
// 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.workspaceModel.storage.bridgeEntities
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Abstract
import org.jetbrains.deft.annotations.Child
interface ArtifactEntity : WorkspaceEntityWithSymbolicId {
val name: String
val artifactType: String
val includeInProjectBuild: Boolean
val outputUrl: VirtualFileUrl?
@Child val rootElement: CompositePackagingElementEntity?
val customProperties: List<@Child ArtifactPropertiesEntity>
@Child val artifactOutputPackagingElement: ArtifactOutputPackagingElementEntity?
override val symbolicId: ArtifactId
get() = ArtifactId(name)
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : ArtifactEntity, WorkspaceEntity.Builder<ArtifactEntity>, ObjBuilder<ArtifactEntity> {
override var entitySource: EntitySource
override var name: String
override var artifactType: String
override var includeInProjectBuild: Boolean
override var outputUrl: VirtualFileUrl?
override var rootElement: CompositePackagingElementEntity?
override var customProperties: List<ArtifactPropertiesEntity>
override var artifactOutputPackagingElement: ArtifactOutputPackagingElementEntity?
}
companion object : Type<ArtifactEntity, Builder>() {
operator fun invoke(name: String,
artifactType: String,
includeInProjectBuild: Boolean,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): ArtifactEntity {
val builder = builder()
builder.name = name
builder.artifactType = artifactType
builder.includeInProjectBuild = includeInProjectBuild
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ArtifactEntity, modification: ArtifactEntity.Builder.() -> Unit) = modifyEntity(
ArtifactEntity.Builder::class.java, entity, modification)
var ArtifactEntity.Builder.artifactExternalSystemIdEntity: @Child ArtifactExternalSystemIdEntity?
by WorkspaceEntity.extension()
//endregion
interface ArtifactPropertiesEntity : WorkspaceEntity {
val artifact: ArtifactEntity
val providerType: String
val propertiesXmlTag: String?
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : ArtifactPropertiesEntity, WorkspaceEntity.Builder<ArtifactPropertiesEntity>, ObjBuilder<ArtifactPropertiesEntity> {
override var entitySource: EntitySource
override var artifact: ArtifactEntity
override var providerType: String
override var propertiesXmlTag: String?
}
companion object : Type<ArtifactPropertiesEntity, Builder>() {
operator fun invoke(providerType: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ArtifactPropertiesEntity {
val builder = builder()
builder.providerType = providerType
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ArtifactPropertiesEntity,
modification: ArtifactPropertiesEntity.Builder.() -> Unit) = modifyEntity(
ArtifactPropertiesEntity.Builder::class.java, entity, modification)
//endregion
@Abstract interface PackagingElementEntity : WorkspaceEntity {
val parentEntity: CompositePackagingElementEntity?
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder<T : PackagingElementEntity> : PackagingElementEntity, WorkspaceEntity.Builder<T>, ObjBuilder<T> {
override var entitySource: EntitySource
override var parentEntity: CompositePackagingElementEntity?
}
companion object : Type<PackagingElementEntity, Builder<PackagingElementEntity>>() {
operator fun invoke(entitySource: EntitySource, init: (Builder<PackagingElementEntity>.() -> Unit)? = null): PackagingElementEntity {
val builder = builder()
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
@Abstract interface CompositePackagingElementEntity : PackagingElementEntity {
val artifact: ArtifactEntity?
val children: List<@Child PackagingElementEntity>
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder<T : CompositePackagingElementEntity> : CompositePackagingElementEntity, PackagingElementEntity.Builder<T>, WorkspaceEntity.Builder<T>, ObjBuilder<T> {
override var entitySource: EntitySource
override var parentEntity: CompositePackagingElementEntity?
override var artifact: ArtifactEntity?
override var children: List<PackagingElementEntity>
}
companion object : Type<CompositePackagingElementEntity, Builder<CompositePackagingElementEntity>>(PackagingElementEntity) {
operator fun invoke(entitySource: EntitySource,
init: (Builder<CompositePackagingElementEntity>.() -> Unit)? = null): CompositePackagingElementEntity {
val builder = builder()
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
interface DirectoryPackagingElementEntity: CompositePackagingElementEntity {
val directoryName: String
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : DirectoryPackagingElementEntity, CompositePackagingElementEntity.Builder<DirectoryPackagingElementEntity>, WorkspaceEntity.Builder<DirectoryPackagingElementEntity>, ObjBuilder<DirectoryPackagingElementEntity> {
override var entitySource: EntitySource
override var parentEntity: CompositePackagingElementEntity?
override var artifact: ArtifactEntity?
override var children: List<PackagingElementEntity>
override var directoryName: String
}
companion object : Type<DirectoryPackagingElementEntity, Builder>(CompositePackagingElementEntity) {
operator fun invoke(directoryName: String,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): DirectoryPackagingElementEntity {
val builder = builder()
builder.directoryName = directoryName
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: DirectoryPackagingElementEntity,
modification: DirectoryPackagingElementEntity.Builder.() -> Unit) = modifyEntity(
DirectoryPackagingElementEntity.Builder::class.java, entity, modification)
//endregion
interface ArchivePackagingElementEntity: CompositePackagingElementEntity {
val fileName: String
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : ArchivePackagingElementEntity, CompositePackagingElementEntity.Builder<ArchivePackagingElementEntity>, WorkspaceEntity.Builder<ArchivePackagingElementEntity>, ObjBuilder<ArchivePackagingElementEntity> {
override var entitySource: EntitySource
override var parentEntity: CompositePackagingElementEntity?
override var artifact: ArtifactEntity?
override var children: List<PackagingElementEntity>
override var fileName: String
}
companion object : Type<ArchivePackagingElementEntity, Builder>(CompositePackagingElementEntity) {
operator fun invoke(fileName: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ArchivePackagingElementEntity {
val builder = builder()
builder.fileName = fileName
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ArchivePackagingElementEntity,
modification: ArchivePackagingElementEntity.Builder.() -> Unit) = modifyEntity(
ArchivePackagingElementEntity.Builder::class.java, entity, modification)
//endregion
interface ArtifactRootElementEntity: CompositePackagingElementEntity {
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : ArtifactRootElementEntity, CompositePackagingElementEntity.Builder<ArtifactRootElementEntity>, WorkspaceEntity.Builder<ArtifactRootElementEntity>, ObjBuilder<ArtifactRootElementEntity> {
override var entitySource: EntitySource
override var parentEntity: CompositePackagingElementEntity?
override var artifact: ArtifactEntity?
override var children: List<PackagingElementEntity>
}
companion object : Type<ArtifactRootElementEntity, Builder>(CompositePackagingElementEntity) {
operator fun invoke(entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ArtifactRootElementEntity {
val builder = builder()
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ArtifactRootElementEntity,
modification: ArtifactRootElementEntity.Builder.() -> Unit) = modifyEntity(
ArtifactRootElementEntity.Builder::class.java, entity, modification)
//endregion
interface ArtifactOutputPackagingElementEntity: PackagingElementEntity {
val artifact: ArtifactId?
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : ArtifactOutputPackagingElementEntity, PackagingElementEntity.Builder<ArtifactOutputPackagingElementEntity>, WorkspaceEntity.Builder<ArtifactOutputPackagingElementEntity>, ObjBuilder<ArtifactOutputPackagingElementEntity> {
override var entitySource: EntitySource
override var parentEntity: CompositePackagingElementEntity?
override var artifact: ArtifactId?
}
companion object : Type<ArtifactOutputPackagingElementEntity, Builder>(PackagingElementEntity) {
operator fun invoke(entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ArtifactOutputPackagingElementEntity {
val builder = builder()
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ArtifactOutputPackagingElementEntity,
modification: ArtifactOutputPackagingElementEntity.Builder.() -> Unit) = modifyEntity(
ArtifactOutputPackagingElementEntity.Builder::class.java, entity, modification)
var ArtifactOutputPackagingElementEntity.Builder.artifactEntity: ArtifactEntity
by WorkspaceEntity.extension()
//endregion
val ArtifactOutputPackagingElementEntity.artifactEntity: ArtifactEntity
by WorkspaceEntity.extension()
interface ModuleOutputPackagingElementEntity : PackagingElementEntity {
val module: ModuleId?
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : ModuleOutputPackagingElementEntity, PackagingElementEntity.Builder<ModuleOutputPackagingElementEntity>, WorkspaceEntity.Builder<ModuleOutputPackagingElementEntity>, ObjBuilder<ModuleOutputPackagingElementEntity> {
override var entitySource: EntitySource
override var parentEntity: CompositePackagingElementEntity?
override var module: ModuleId?
}
companion object : Type<ModuleOutputPackagingElementEntity, Builder>(PackagingElementEntity) {
operator fun invoke(entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ModuleOutputPackagingElementEntity {
val builder = builder()
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ModuleOutputPackagingElementEntity,
modification: ModuleOutputPackagingElementEntity.Builder.() -> Unit) = modifyEntity(
ModuleOutputPackagingElementEntity.Builder::class.java, entity, modification)
//endregion
interface LibraryFilesPackagingElementEntity : PackagingElementEntity {
val library: LibraryId?
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : LibraryFilesPackagingElementEntity, PackagingElementEntity.Builder<LibraryFilesPackagingElementEntity>, WorkspaceEntity.Builder<LibraryFilesPackagingElementEntity>, ObjBuilder<LibraryFilesPackagingElementEntity> {
override var entitySource: EntitySource
override var parentEntity: CompositePackagingElementEntity?
override var library: LibraryId?
}
companion object : Type<LibraryFilesPackagingElementEntity, Builder>(PackagingElementEntity) {
operator fun invoke(entitySource: EntitySource, init: (Builder.() -> Unit)? = null): LibraryFilesPackagingElementEntity {
val builder = builder()
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: LibraryFilesPackagingElementEntity,
modification: LibraryFilesPackagingElementEntity.Builder.() -> Unit) = modifyEntity(
LibraryFilesPackagingElementEntity.Builder::class.java, entity, modification)
var LibraryFilesPackagingElementEntity.Builder.libraryEntity: LibraryEntity
by WorkspaceEntity.extension()
//endregion
val LibraryFilesPackagingElementEntity.libraryEntity: LibraryEntity
by WorkspaceEntity.extension()
interface ModuleSourcePackagingElementEntity : PackagingElementEntity {
val module: ModuleId?
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : ModuleSourcePackagingElementEntity, PackagingElementEntity.Builder<ModuleSourcePackagingElementEntity>, WorkspaceEntity.Builder<ModuleSourcePackagingElementEntity>, ObjBuilder<ModuleSourcePackagingElementEntity> {
override var entitySource: EntitySource
override var parentEntity: CompositePackagingElementEntity?
override var module: ModuleId?
}
companion object : Type<ModuleSourcePackagingElementEntity, Builder>(PackagingElementEntity) {
operator fun invoke(entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ModuleSourcePackagingElementEntity {
val builder = builder()
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ModuleSourcePackagingElementEntity,
modification: ModuleSourcePackagingElementEntity.Builder.() -> Unit) = modifyEntity(
ModuleSourcePackagingElementEntity.Builder::class.java, entity, modification)
//endregion
interface ModuleTestOutputPackagingElementEntity : PackagingElementEntity {
val module: ModuleId?
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : ModuleTestOutputPackagingElementEntity, PackagingElementEntity.Builder<ModuleTestOutputPackagingElementEntity>, WorkspaceEntity.Builder<ModuleTestOutputPackagingElementEntity>, ObjBuilder<ModuleTestOutputPackagingElementEntity> {
override var entitySource: EntitySource
override var parentEntity: CompositePackagingElementEntity?
override var module: ModuleId?
}
companion object : Type<ModuleTestOutputPackagingElementEntity, Builder>(PackagingElementEntity) {
operator fun invoke(entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ModuleTestOutputPackagingElementEntity {
val builder = builder()
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ModuleTestOutputPackagingElementEntity,
modification: ModuleTestOutputPackagingElementEntity.Builder.() -> Unit) = modifyEntity(
ModuleTestOutputPackagingElementEntity.Builder::class.java, entity, modification)
//endregion
@Abstract interface FileOrDirectoryPackagingElementEntity : PackagingElementEntity {
val filePath: VirtualFileUrl
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder<T : FileOrDirectoryPackagingElementEntity> : FileOrDirectoryPackagingElementEntity, PackagingElementEntity.Builder<T>, WorkspaceEntity.Builder<T>, ObjBuilder<T> {
override var entitySource: EntitySource
override var parentEntity: CompositePackagingElementEntity?
override var filePath: VirtualFileUrl
}
companion object : Type<FileOrDirectoryPackagingElementEntity, Builder<FileOrDirectoryPackagingElementEntity>>(PackagingElementEntity) {
operator fun invoke(filePath: VirtualFileUrl,
entitySource: EntitySource,
init: (Builder<FileOrDirectoryPackagingElementEntity>.() -> Unit)? = null): FileOrDirectoryPackagingElementEntity {
val builder = builder()
builder.filePath = filePath
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
interface DirectoryCopyPackagingElementEntity : FileOrDirectoryPackagingElementEntity {
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : DirectoryCopyPackagingElementEntity, FileOrDirectoryPackagingElementEntity.Builder<DirectoryCopyPackagingElementEntity>, WorkspaceEntity.Builder<DirectoryCopyPackagingElementEntity>, ObjBuilder<DirectoryCopyPackagingElementEntity> {
override var entitySource: EntitySource
override var parentEntity: CompositePackagingElementEntity?
override var filePath: VirtualFileUrl
}
companion object : Type<DirectoryCopyPackagingElementEntity, Builder>(FileOrDirectoryPackagingElementEntity) {
operator fun invoke(filePath: VirtualFileUrl,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): DirectoryCopyPackagingElementEntity {
val builder = builder()
builder.filePath = filePath
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: DirectoryCopyPackagingElementEntity,
modification: DirectoryCopyPackagingElementEntity.Builder.() -> Unit) = modifyEntity(
DirectoryCopyPackagingElementEntity.Builder::class.java, entity, modification)
//endregion
interface ExtractedDirectoryPackagingElementEntity: FileOrDirectoryPackagingElementEntity {
val pathInArchive: String
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : ExtractedDirectoryPackagingElementEntity, FileOrDirectoryPackagingElementEntity.Builder<ExtractedDirectoryPackagingElementEntity>, WorkspaceEntity.Builder<ExtractedDirectoryPackagingElementEntity>, ObjBuilder<ExtractedDirectoryPackagingElementEntity> {
override var entitySource: EntitySource
override var parentEntity: CompositePackagingElementEntity?
override var filePath: VirtualFileUrl
override var pathInArchive: String
}
companion object : Type<ExtractedDirectoryPackagingElementEntity, Builder>(FileOrDirectoryPackagingElementEntity) {
operator fun invoke(filePath: VirtualFileUrl,
pathInArchive: String,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): ExtractedDirectoryPackagingElementEntity {
val builder = builder()
builder.filePath = filePath
builder.pathInArchive = pathInArchive
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ExtractedDirectoryPackagingElementEntity,
modification: ExtractedDirectoryPackagingElementEntity.Builder.() -> Unit) = modifyEntity(
ExtractedDirectoryPackagingElementEntity.Builder::class.java, entity, modification)
//endregion
interface FileCopyPackagingElementEntity : FileOrDirectoryPackagingElementEntity {
val renamedOutputFileName: String?
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : FileCopyPackagingElementEntity, FileOrDirectoryPackagingElementEntity.Builder<FileCopyPackagingElementEntity>, WorkspaceEntity.Builder<FileCopyPackagingElementEntity>, ObjBuilder<FileCopyPackagingElementEntity> {
override var entitySource: EntitySource
override var parentEntity: CompositePackagingElementEntity?
override var filePath: VirtualFileUrl
override var renamedOutputFileName: String?
}
companion object : Type<FileCopyPackagingElementEntity, Builder>(FileOrDirectoryPackagingElementEntity) {
operator fun invoke(filePath: VirtualFileUrl,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): FileCopyPackagingElementEntity {
val builder = builder()
builder.filePath = filePath
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: FileCopyPackagingElementEntity,
modification: FileCopyPackagingElementEntity.Builder.() -> Unit) = modifyEntity(
FileCopyPackagingElementEntity.Builder::class.java, entity, modification)
//endregion
interface CustomPackagingElementEntity : CompositePackagingElementEntity {
val typeId: String
val propertiesXmlTag: String
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : CustomPackagingElementEntity, CompositePackagingElementEntity.Builder<CustomPackagingElementEntity>, WorkspaceEntity.Builder<CustomPackagingElementEntity>, ObjBuilder<CustomPackagingElementEntity> {
override var entitySource: EntitySource
override var parentEntity: CompositePackagingElementEntity?
override var artifact: ArtifactEntity?
override var children: List<PackagingElementEntity>
override var typeId: String
override var propertiesXmlTag: String
}
companion object : Type<CustomPackagingElementEntity, Builder>(CompositePackagingElementEntity) {
operator fun invoke(typeId: String,
propertiesXmlTag: String,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): CustomPackagingElementEntity {
val builder = builder()
builder.typeId = typeId
builder.propertiesXmlTag = propertiesXmlTag
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: CustomPackagingElementEntity,
modification: CustomPackagingElementEntity.Builder.() -> Unit) = modifyEntity(
CustomPackagingElementEntity.Builder::class.java, entity, modification)
//endregion
|
apache-2.0
|
e6c238db3ffa6eba330a9acb51fb7968
| 40.743772 | 274 | 0.76445 | 6.689478 | false | false | false | false |
ianhanniballake/muzei
|
legacy-standalone/src/main/java/com/google/android/apps/muzei/legacy/LegacySourceService.kt
|
1
|
21593
|
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei.legacy
import android.app.Service
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.content.pm.ServiceInfo
import android.content.res.Resources
import android.graphics.Color
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.Message
import android.os.Messenger
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import androidx.lifecycle.lifecycleScope
import androidx.room.withTransaction
import com.google.android.apps.muzei.sources.SourceSubscriberService
import com.google.android.apps.muzei.util.goAsync
import com.google.android.apps.muzei.util.launchWhenStartedIn
import com.google.android.apps.muzei.util.toastFromBackground
import com.google.firebase.analytics.ktx.analytics
import com.google.firebase.ktx.Firebase
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import net.nurik.roman.muzei.legacy.BuildConfig
import net.nurik.roman.muzei.legacy.R
import java.util.HashSet
import java.util.concurrent.Executors
/**
* Class responsible for managing interactions with sources such as subscribing, unsubscribing, and sending actions.
*/
@OptIn(ExperimentalCoroutinesApi::class)
class LegacySourceService : Service(), LifecycleOwner {
companion object {
private const val TAG = "LegacySourceService"
private const val ACTION_SUBSCRIBE = "com.google.android.apps.muzei.api.action.SUBSCRIBE"
private const val EXTRA_SUBSCRIBER_COMPONENT = "com.google.android.apps.muzei.api.extra.SUBSCRIBER_COMPONENT"
private const val EXTRA_TOKEN = "com.google.android.apps.muzei.api.extra.TOKEN"
private const val USER_PROPERTY_SELECTED_SOURCE = "selected_source"
private const val USER_PROPERTY_SELECTED_SOURCE_PACKAGE = "selected_source_package"
private const val MAX_VALUE_LENGTH = 36
suspend fun selectSource(
context: Context,
source: ComponentName
): Source {
val database = LegacyDatabase.getInstance(context)
val selectedSource = database.sourceDao().getCurrentSource()
if (source == selectedSource?.componentName) {
return selectedSource
}
if (BuildConfig.DEBUG) {
Log.d(TAG, "Source $source selected.")
}
return database.withTransaction {
if (selectedSource != null) {
// Unselect the old source
selectedSource.selected = false
database.sourceDao().update(selectedSource)
}
// Select the new source
val newSource = database.sourceDao().getSourceByComponentName(source)?.apply {
selected = true
database.sourceDao().update(this)
} ?: Source(source).apply {
selected = true
database.sourceDao().insert(this)
}
newSource
}
}
}
private val lifecycleRegistry = LifecycleRegistry(this)
private val singleThreadContext by lazy {
Executors.newSingleThreadExecutor { target ->
Thread(target, "LegacySourceService")
}.asCoroutineDispatcher()
}
private var replyToMessenger: Messenger? = null
private val messenger by lazy {
Messenger(Handler(Looper.getMainLooper()) { message ->
when (message.what) {
LegacySourceServiceProtocol.WHAT_REGISTER_REPLY_TO -> {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Registered")
}
replyToMessenger = message.replyTo
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
}
LegacySourceServiceProtocol.WHAT_NEXT_ARTWORK -> lifecycleScope.launch(singleThreadContext) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Got next artwork command")
}
val database = LegacyDatabase.getInstance(applicationContext)
val source = database.sourceDao().getCurrentSource()
if (source?.supportsNextArtwork == true) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Sending next artwork command to ${source.componentName}")
}
source.sendAction(this@LegacySourceService,
LegacySourceServiceProtocol.LEGACY_COMMAND_ID_NEXT_ARTWORK)
}
}
LegacySourceServiceProtocol.WHAT_ALLOWS_NEXT_ARTWORK -> {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Got allows next artwork")
}
val replyMessenger = message.replyTo
lifecycleScope.launch(singleThreadContext) {
val allowsNextArtwork = LegacyDatabase.getInstance(applicationContext)
.sourceDao().getCurrentSource()?.supportsNextArtwork == true
if (BuildConfig.DEBUG) {
Log.d(TAG, "Sending allows next artwork of $allowsNextArtwork")
}
replyMessenger.send(Message.obtain().apply {
arg1 = if (allowsNextArtwork) 1 else 0
})
}
}
LegacySourceServiceProtocol.WHAT_UNREGISTER_REPLY_TO -> {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Unregistered")
}
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
replyToMessenger = null
}
}
true
})
}
private val sourcePackageChangeReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
if (intent?.data == null) {
return
}
val packageName = intent.data?.schemeSpecificPart
// Update the sources from the changed package
GlobalScope.launch(singleThreadContext) {
updateSources(packageName)
}
if (lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
goAsync(lifecycleScope) {
val source = LegacyDatabase.getInstance(context)
.sourceDao().getCurrentSource()
if (source != null && packageName == source.componentName.packageName) {
try {
context.packageManager.getServiceInfo(source.componentName, 0)
} catch (e: PackageManager.NameNotFoundException) {
Log.i(TAG, "Selected source ${source.componentName} is no longer available")
LegacyDatabase.getInstance(context).sourceDao().delete(source)
return@goAsync
}
// Some other change.
Log.i(TAG, "Source package changed or replaced. Re-subscribing to ${source.componentName}")
source.subscribe()
}
}
}
}
}
private suspend fun updateSources(packageName: String? = null) {
val queryIntent = Intent(LegacySourceServiceProtocol.ACTION_MUZEI_ART_SOURCE)
if (packageName != null) {
queryIntent.`package` = packageName
}
val pm = packageManager
val database = LegacyDatabase.getInstance(this)
database.withTransaction {
val existingSources = HashSet(if (packageName != null)
database.sourceDao().getSourcesComponentNamesByPackageName(packageName)
else
database.sourceDao().getSourceComponentNames())
val resolveInfos = pm.queryIntentServices(queryIntent,
PackageManager.GET_META_DATA)
for (ri in resolveInfos) {
existingSources.remove(ComponentName(ri.serviceInfo.packageName,
ri.serviceInfo.name))
updateSourceFromServiceInfo(ri.serviceInfo)
}
// Delete sources in the database that have since been removed
database.sourceDao().deleteAll(existingSources.toTypedArray())
}
// Enable or disable the SourceArtProvider based on whether
// there are any available sources
val sources = database.sourceDao().getSources()
val legacyComponentName = ComponentName(this, SourceArtProvider::class.java)
val currentState = pm.getComponentEnabledSetting(legacyComponentName)
val newState = if (sources.isEmpty()) {
PackageManager.COMPONENT_ENABLED_STATE_DISABLED
} else {
PackageManager.COMPONENT_ENABLED_STATE_ENABLED
}
if (currentState != newState) {
pm.setComponentEnabledSetting(legacyComponentName,
newState,
PackageManager.DONT_KILL_APP)
}
}
@Suppress("RemoveExplicitTypeArguments")
private fun getSubscribedSource() = callbackFlow<Source> {
var currentSource: Source? = null
val database = LegacyDatabase.getInstance(this@LegacySourceService)
database.sourceDao().currentSource.collect { source ->
if (currentSource != null && source != null &&
currentSource?.componentName == source.componentName) {
// Don't do anything if it is the same Source
return@collect
}
currentSource?.unsubscribe()
currentSource = source
if (source != null) {
source.subscribe()
send(source)
}
}
awaitClose {
currentSource?.unsubscribe()
}
}
init {
lifecycle.addObserver(NetworkChangeObserver(this))
}
override fun getLifecycle() = lifecycleRegistry
override fun onBind(intent: Intent): IBinder? {
return messenger.binder
}
override fun onCreate() {
super.onCreate()
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
getSubscribedSource().onEach { source: Source ->
sendSelectedSourceAnalytics(source.componentName)
}.launchWhenStartedIn(this)
val database = LegacyDatabase.getInstance(this)
var currentSource: Source? = null
database.sourceDao().currentSource.onEach { source ->
if (currentSource != null && source == null) {
// The selected source has been removed or was otherwise deselected
replyToMessenger?.send(Message.obtain().apply {
what = LegacySourceServiceProtocol.WHAT_REPLY_TO_NO_SELECTED_SOURCE
})
}
currentSource = source
}.launchWhenStartedIn(this)
// Register for package change events
val packageChangeFilter = IntentFilter().apply {
addDataScheme("package")
addAction(Intent.ACTION_PACKAGE_ADDED)
addAction(Intent.ACTION_PACKAGE_CHANGED)
addAction(Intent.ACTION_PACKAGE_REPLACED)
addAction(Intent.ACTION_PACKAGE_REMOVED)
}
registerReceiver(sourcePackageChangeReceiver, packageChangeFilter)
// Update the available sources in case we missed anything while Muzei was disabled
GlobalScope.launch(singleThreadContext) {
updateSources()
}
}
private suspend fun updateSourceFromServiceInfo(info: ServiceInfo) {
val pm = packageManager
val metaData = info.metaData
val componentName = ComponentName(info.packageName, info.name)
val sourceDao = LegacyDatabase.getInstance(this).sourceDao()
val existingSource = sourceDao.getSourceByComponentName(componentName)
if (metaData != null && metaData.containsKey("replacement")) {
// Skip sources having a replacement MuzeiArtProvider that should be used instead
if (existingSource != null) {
if (existingSource.selected) {
// If this is the selected source, switch Muzei to the new MuzeiArtProvider
// rather than continue to use the legacy art source
metaData.getString("replacement").takeUnless { it.isNullOrEmpty() }?.run {
val providerInfo = pm.resolveContentProvider(this, 0)
?: try {
val replacement = ComponentName(packageName, this)
pm.getProviderInfo(replacement, 0)
} catch (e: PackageManager.NameNotFoundException) {
// Invalid
null
}
if (providerInfo != null) {
replyToMessenger?.send(Message.obtain().apply {
what = LegacySourceServiceProtocol.WHAT_REPLY_TO_REPLACEMENT
obj = providerInfo.authority
})
}
}
}
sourceDao.delete(existingSource)
}
return
} else if (!info.isEnabled) {
// Disabled sources can't be used
if (existingSource != null) {
sourceDao.delete(existingSource)
}
return
}
val source = existingSource ?: Source(componentName)
source.label = info.loadLabel(pm).toString()
source.targetSdkVersion = info.applicationInfo.targetSdkVersion
if (source.targetSdkVersion >= Build.VERSION_CODES.O) {
// The Legacy API is incompatible with apps
// targeting Android O+
source.selected = false
}
if (info.descriptionRes != 0) {
try {
val packageContext = createPackageContext(
source.componentName.packageName, 0)
val packageRes = packageContext.resources
source.defaultDescription = packageRes.getString(info.descriptionRes)
} catch (e: PackageManager.NameNotFoundException) {
Log.e(TAG, "Can't read package resources for source ${source.componentName}")
} catch (e: Resources.NotFoundException) {
Log.e(TAG, "Can't read package resources for source ${source.componentName}")
}
}
source.color = Color.WHITE
if (metaData != null) {
val settingsActivity = metaData.getString("settingsActivity")
if (!settingsActivity.isNullOrEmpty()) {
source.settingsActivity = ComponentName.unflattenFromString(
"${info.packageName}/$settingsActivity")
}
val setupActivity = metaData.getString("setupActivity")
if (!setupActivity.isNullOrEmpty()) {
source.setupActivity = ComponentName.unflattenFromString(
"${info.packageName}/$setupActivity")
}
source.color = metaData.getInt("color", source.color)
try {
val hsv = FloatArray(3)
Color.colorToHSV(source.color, hsv)
var adjust = false
if (hsv[2] < 0.8f) {
hsv[2] = 0.8f
adjust = true
}
if (hsv[1] > 0.4f) {
hsv[1] = 0.4f
adjust = true
}
if (adjust) {
source.color = Color.HSVToColor(hsv)
}
if (Color.alpha(source.color) != 255) {
source.color = Color.argb(255,
Color.red(source.color),
Color.green(source.color),
Color.blue(source.color))
}
} catch (ignored: IllegalArgumentException) {
}
}
if (existingSource == null) {
sourceDao.insert(source)
} else {
sourceDao.update(source)
}
}
override fun onDestroy() {
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
unregisterReceiver(sourcePackageChangeReceiver)
super.onDestroy()
}
private fun sendSelectedSourceAnalytics(selectedSource: ComponentName) {
// The current limit for user property values
var packageName = selectedSource.packageName
if (packageName.length > MAX_VALUE_LENGTH) {
packageName = packageName.substring(packageName.length - MAX_VALUE_LENGTH)
}
Firebase.analytics.setUserProperty(USER_PROPERTY_SELECTED_SOURCE_PACKAGE, packageName)
var className = selectedSource.flattenToShortString()
className = className.substring(className.indexOf('/') + 1)
if (className.length > MAX_VALUE_LENGTH) {
className = className.substring(className.length - MAX_VALUE_LENGTH)
}
Firebase.analytics.setUserProperty(USER_PROPERTY_SELECTED_SOURCE, className)
}
private suspend fun Source.subscribe() {
val selectedSource = componentName
try {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Subscribing to $selectedSource")
}
// Ensure that we have a valid service before subscribing
packageManager.getServiceInfo(selectedSource, 0)
startService(Intent(ACTION_SUBSCRIBE)
.setComponent(selectedSource)
.putExtra(EXTRA_SUBSCRIBER_COMPONENT,
ComponentName(this@LegacySourceService, SourceSubscriberService::class.java))
.putExtra(EXTRA_TOKEN, selectedSource.flattenToShortString()))
} catch (e: PackageManager.NameNotFoundException) {
Log.i(TAG, "Selected source $selectedSource is no longer available; switching to default.", e)
toastFromBackground(R.string.legacy_source_unavailable, Toast.LENGTH_LONG)
LegacyDatabase.getInstance(this@LegacySourceService).sourceDao().delete(this)
} catch (e: IllegalStateException) {
Log.i(TAG, "Selected source $selectedSource is no longer available; switching to default.", e)
toastFromBackground(R.string.legacy_source_unavailable, Toast.LENGTH_LONG)
LegacyDatabase.getInstance(this@LegacySourceService).sourceDao()
.update(apply { selected = false })
} catch (e: SecurityException) {
Log.i(TAG, "Selected source $selectedSource is no longer available; switching to default.", e)
toastFromBackground(R.string.legacy_source_unavailable, Toast.LENGTH_LONG)
LegacyDatabase.getInstance(this@LegacySourceService).sourceDao()
.update(apply { selected = false })
}
}
private fun Source.unsubscribe() {
val selectedSource = componentName
try {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Unsubscribing to $selectedSource")
}
// Ensure that we have a valid service before subscribing
packageManager.getServiceInfo(selectedSource, 0)
startService(Intent(ACTION_SUBSCRIBE)
.setComponent(selectedSource)
.putExtra(EXTRA_SUBSCRIBER_COMPONENT,
ComponentName(this@LegacySourceService, SourceSubscriberService::class.java))
.putExtra(EXTRA_TOKEN, null as String?))
} catch (e: PackageManager.NameNotFoundException) {
Log.i(TAG, "Unsubscribing to $selectedSource failed.", e)
} catch (e: IllegalStateException) {
Log.i(TAG, "Unsubscribing to $selectedSource failed.", e)
} catch (e: SecurityException) {
Log.i(TAG, "Unsubscribing to $selectedSource failed.", e)
}
}
}
|
apache-2.0
|
44adb35e191f212719154eabaf768545
| 43.430041 | 117 | 0.593526 | 5.607115 | false | false | false | false |
android/storage-samples
|
ScopedStorage/app/src/main/java/com/samples/storage/scopedstorage/saf/SelectDocumentFileViewModel.kt
|
1
|
2461
|
/*
* 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
*
* 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.samples.storage.scopedstorage.saf
import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.net.Uri
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.viewModelScope
import com.samples.storage.scopedstorage.common.FileResource
import com.samples.storage.scopedstorage.common.SafUtils
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.launch
class SelectDocumentFileViewModel(
application: Application,
private val savedStateHandle: SavedStateHandle
) : AndroidViewModel(application) {
companion object {
private val TAG = this::class.java.simpleName
const val SELECTED_FILE_KEY = "selectedFile"
}
private val context: Context
get() = getApplication()
private val _errorFlow = MutableSharedFlow<String>()
val errorFlow: SharedFlow<String> = _errorFlow
/**
* We keep the current media [Uri] in the savedStateHandle to re-render it if there is a
* configuration change and we expose it as a [LiveData] to the UI
*/
val selectedFile: LiveData<FileResource?> =
savedStateHandle.getLiveData<FileResource?>(SELECTED_FILE_KEY)
@SuppressLint("NewApi")
fun onFileSelect(uri: Uri) {
viewModelScope.launch {
savedStateHandle[SELECTED_FILE_KEY] = SafUtils.getResourceByUri(context, uri)
try {
savedStateHandle[SELECTED_FILE_KEY] = SafUtils.getResourceByUri(context, uri)
} catch (e: Exception) {
Log.e(TAG, e.printStackTrace().toString())
_errorFlow.emit("Couldn't load $uri")
}
}
}
}
|
apache-2.0
|
4b27f33f0dc26c3e8608482bd7ffc3bb
| 34.171429 | 93 | 0.725315 | 4.591418 | false | false | false | false |
Cognifide/gradle-aem-plugin
|
src/main/kotlin/com/cognifide/gradle/aem/pkg/tasks/PackageSync.kt
|
1
|
7048
|
package com.cognifide.gradle.aem.pkg.tasks
import com.cognifide.gradle.aem.AemDefaultTask
import com.cognifide.gradle.aem.AemException
import com.cognifide.gradle.aem.common.instance.Instance
import com.cognifide.gradle.aem.common.instance.service.pkg.Package
import com.cognifide.gradle.aem.common.pkg.vault.FilterFile
import com.cognifide.gradle.common.utils.Formats
import com.cognifide.gradle.aem.common.pkg.vault.VaultClient
import com.cognifide.gradle.aem.pkg.tasks.sync.Cleaner
import com.cognifide.gradle.aem.pkg.tasks.sync.Downloader
import com.cognifide.gradle.common.utils.using
import org.gradle.api.file.Directory
import org.gradle.api.provider.Provider
import java.io.File
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.TaskAction
open class PackageSync : AemDefaultTask() {
/**
* Determines what need to be done (content copied and clean or something else).
*/
@Internal
val mode = aem.obj.typed<Mode> {
convention(Mode.COPY_AND_CLEAN)
aem.prop.string("package.sync.mode")?.let { set(Mode.of(it)) }
}
fun mode(name: String) {
mode.set(Mode.of(name))
}
/**
* Determines a method of getting JCR content from remote instance.
*/
@Internal
val transfer = aem.obj.typed<Transfer> {
convention(Transfer.PACKAGE_DOWNLOAD)
aem.prop.string("package.sync.transfer")?.let { set(Transfer.of(it)) }
}
fun transfer(name: String) {
transfer.set(Transfer.of(name))
}
/**
* Source instance from which JCR content will be copied.
*/
@Internal
val instance = aem.obj.typed<Instance> { convention(aem.obj.provider { aem.anyInstance }) }
/**
* Determines which content will be copied from source instance.
*/
@Internal
val filter = aem.obj.typed<FilterFile> { convention(aem.obj.provider { aem.filter }) }
fun filter(path: String) {
filter.set(aem.filter(path))
}
fun filter(file: File) {
filter.set(aem.filter(file))
}
fun filter(file: Provider<File>) {
filter.set(file.map { aem.filter(it) })
}
/**
* Location of JCR content root to which content will be copied.
*/
@Internal
val contentDir = aem.obj.dir { convention(aem.packageOptions.contentDir) }
fun contentDir(rootPath: String) = contentDir(project.rootProject.layout.projectDirectory.dir(rootPath))
fun contentDir(dir: File) {
contentDir.set(dir)
filter.set(project.provider {
FilterFile.cmd(aem) ?: FilterFile(dir.resolve("${Package.VLT_PATH}/${FilterFile.BUILD_NAME}"))
})
}
fun contentDir(dir: Directory) {
contentDir.set(dir)
filter.set(contentDir.map {
aem.filter(it.file("${Package.VLT_PATH}/${FilterFile.BUILD_NAME}").asFile)
})
}
private val filterRootFiles: List<File>
get() = contentDir.get().asFile.run {
if (!exists()) {
logger.warn("JCR content directory does not exist: $this")
listOf<File>()
}
filter.get().rootDirs(this)
}
fun cleaner(options: Cleaner.() -> Unit) = cleaner.using(options)
@get:Internal
val cleaner by lazy { Cleaner(aem) }
fun vaultClient(options: VaultClient.() -> Unit) = vaultClient.using(options)
@get:Internal
val vaultClient by lazy {
VaultClient(aem).apply {
contentDir.convention([email protected])
command.convention(aem.obj.provider {
"--credentials ${instance.get().credentialsString} checkout --force" +
" --filter ${filter.get().file} ${instance.get().httpUrl}/crx/server/crx.default"
})
}
}
fun downloader(options: Downloader.() -> Unit) = downloader.using(options)
@get:Internal
val downloader by lazy {
Downloader(aem).apply {
instance.convention([email protected])
filter.convention([email protected])
extractDir.convention(contentDir.dir(Package.JCR_ROOT))
definition {
destinationDirectory.convention(project.layout.buildDirectory.dir([email protected]))
archiveFileName.convention("downloader.zip")
}
}
}
@TaskAction
fun sync() {
if (mode.get() != Mode.CLEAN_ONLY) {
instance.get().examine()
}
common.progress {
step = "Initializing"
try {
contentDir.get().asFile.mkdirs()
if (mode.get() != Mode.COPY_ONLY) {
step = "Preparing content"
prepareContent()
}
if (mode.get() != Mode.CLEAN_ONLY) {
when (transfer.get()) {
Transfer.VLT_CHECKOUT -> {
step = "Checking out content"
vaultClient.run()
}
Transfer.PACKAGE_DOWNLOAD -> {
step = "Downloading content"
downloader.download()
}
else -> {}
}
}
common.notifier.notify(
"Synchronized JCR content",
"Instance: ${instance.get().name}. Directory: ${Formats.rootProjectPath(contentDir.get().asFile, project)}"
)
} finally {
step = "Cleaning content"
if (mode.get() != Mode.COPY_ONLY) {
cleanContent()
}
}
}
}
private fun prepareContent() {
logger.info("Preparing files to be cleaned up (before copying new ones) using: ${filter.get()}")
filterRootFiles.forEach { root ->
cleaner.prepare(root)
}
}
private fun cleanContent() {
logger.info("Cleaning copied files using: ${filter.get()}")
filterRootFiles.forEach { root ->
cleaner.beforeClean(root)
}
filterRootFiles.forEach { root ->
cleaner.clean(root)
}
}
init {
description = "Check out then clean JCR content."
}
enum class Transfer {
VLT_CHECKOUT,
PACKAGE_DOWNLOAD;
companion object {
fun of(name: String): Transfer {
return values().find { it.name.equals(name, true) }
?: throw AemException("Unsupported sync transport: $name")
}
}
}
enum class Mode {
COPY_AND_CLEAN,
CLEAN_ONLY,
COPY_ONLY;
companion object {
fun of(name: String): Mode {
return values().find { it.name.equals(name, true) }
?: throw AemException("Unsupported sync mode: $name")
}
}
}
companion object {
const val NAME = "packageSync"
}
}
|
apache-2.0
|
524fd0c9e7dedc73d5596d1ab495f406
| 29.248927 | 127 | 0.567111 | 4.399501 | false | false | false | false |
excref/kotblog
|
blog/service/impl/src/test/kotlin/com/excref/kotblog/blog/service/user/impl/UserServiceImplTest.kt
|
1
|
4834
|
package com.excref.kotblog.blog.service.user.impl
import com.excref.kotblog.blog.persistence.user.UserRepository
import com.excref.kotblog.blog.service.test.AbstractServiceImplTest
import com.excref.kotblog.blog.service.user.UserService
import com.excref.kotblog.blog.service.user.domain.User
import com.excref.kotblog.blog.service.user.domain.UserRole
import com.excref.kotblog.blog.service.user.exception.UserAlreadyExistsForEmailException
import com.excref.kotblog.blog.service.user.exception.UserNotFoundForUuidException
import org.assertj.core.api.Assertions.assertThat
import org.easymock.EasyMock.*
import org.easymock.Mock
import org.easymock.TestSubject
import org.junit.Assert.fail
import org.junit.Test
import java.util.*
/**
* @author Arthur Asatryan
* @since 6/7/17 12:16 AM
*/
class UserServiceImplTest : AbstractServiceImplTest() {
//region Test subject and mocks
@TestSubject
private val userService: UserService = UserServiceImpl()
@Mock
private lateinit var userRepository: UserRepository
//endregion
//region Test methods
//region Initial
@Test
fun testUserService() {
resetAll()
// test data
// expectations
replayAll()
// test scenario
assertThat(userService).isNotNull()
verifyAll()
}
@Test
fun testUserRepository() {
resetAll()
// test data
// expectations
replayAll()
// test scenario
assertThat(userRepository).isNotNull()
verifyAll()
}
//endregion
//region create
/**
* When user already exists for email
*/
@Test
fun testCreate1() {
resetAll()
// test data
val user = helper.buildUser()
// expectations
expect(userRepository.findByEmail(user.email)).andReturn(user)
replayAll()
// test scenario
try {
userService.create(user.email, UUID.randomUUID().toString(), UserRole.USER)
fail()
} catch(ex: UserAlreadyExistsForEmailException) {
assertThat(ex).isNotNull().extracting("email").containsOnly(user.email)
}
verifyAll()
}
/**
* When user does not exists
*/
@Test
fun testCreate2() {
resetAll()
// test data
val email = "[email protected]"
val password = "you can't even guess me! :P"
val role = UserRole.USER
// expectations
expect(userRepository.findByEmail(email)).andReturn(null)
expect(userRepository.save(isA(User::class.java))).andAnswer({ getCurrentArguments()[0] as User })
replayAll()
// test scenario
val result = userService.create(email, password, role)
assertThat(result).isNotNull().extracting("email", "password", "role").containsOnly(email, password, role)
verifyAll()
}
//endregion
//region getByUuid
/**
* When user does not exists
*/
@Test
fun testGetByUuid1() {
resetAll()
// test data
// expectations
val uuid = UUID.randomUUID().toString()
expect(userRepository.findByUuid(uuid)).andReturn(null)
replayAll()
// test scenario
try {
userService.getByUuid(uuid)
fail()
} catch(ex: UserNotFoundForUuidException) {
assertThat(ex).isNotNull().extracting("uuid").containsOnly(uuid)
}
verifyAll()
}
/**
* When user exists
*/
@Test
fun testGetByUuid2() {
resetAll()
// test data
// expectations
val user = helper.buildUser()
val uuid = user.uuid
expect(userRepository.findByUuid(uuid)).andReturn(user)
replayAll()
// test scenario
val result = userService.getByUuid(uuid)
assertThat(result).isNotNull().isEqualTo(user)
verifyAll()
}
//endregion
//region existsForEmail
/**
* When exists
*/
@Test
fun testExistsForEmail1() {
resetAll()
// test data
val email = "[email protected]"
val user = helper.buildUser(email = email)
// expectations
expect(userRepository.findByEmail(email)).andReturn(user)
replayAll()
// test scenario
assertThat(userService.existsForEmail(email)).isNotNull().isTrue()
verifyAll()
}
/**
* When does not exists
*/
@Test
fun testExistsForEmail2() {
resetAll()
// test data
val email = "[email protected]"
// expectations
expect(userRepository.findByEmail(email)).andReturn(null)
replayAll()
// test scenario
assertThat(userService.existsForEmail(email)).isFalse()
verifyAll()
}
//endregion
//endregion
}
|
apache-2.0
|
8c928eb3e1022aa5db31bb09a338a7e8
| 26.011173 | 114 | 0.616674 | 4.693204 | false | true | false | false |
fkorotkov/k8s-kotlin-dsl
|
example/src/main/kotlin/BaseService.kt
|
1
|
804
|
import com.fkorotkov.kubernetes.metadata
import com.fkorotkov.kubernetes.newServicePort
import com.fkorotkov.kubernetes.spec
import io.fabric8.kubernetes.api.model.Service
open class BaseService(val serviceName: String) : Service() {
companion object {
val HTTP_PORT = 8080
val GRPC_PORT = 8239
}
val grpcPort = GRPC_PORT
val httpPort = HTTP_PORT
init {
metadata {
name = serviceName
labels = Defaults.labels(serviceName)
}
spec {
type = "NodePort"
ports = listOf(
newServicePort {
name = "http"
protocol = "TCP"
port = httpPort
},
newServicePort {
name = "grpc"
port = grpcPort
}
)
selector = Defaults.labels(serviceName)
}
}
}
|
mit
|
df8c31fc21f7d3cff6825dd00b85eedf
| 21.333333 | 61 | 0.593284 | 4.253968 | false | false | false | false |
vector-im/vector-android
|
vector/src/main/java/im/vector/fragments/keysbackup/restore/KeysBackupRestoreSuccessFragment.kt
|
2
|
2585
|
/*
* Copyright 2019 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector.fragments.keysbackup.restore
import android.os.Bundle
import android.widget.TextView
import androidx.lifecycle.ViewModelProviders
import butterknife.BindView
import butterknife.OnClick
import im.vector.R
import im.vector.fragments.VectorBaseFragment
import im.vector.ui.arch.LiveEvent
class KeysBackupRestoreSuccessFragment : VectorBaseFragment() {
override fun getLayoutResId() = R.layout.fragment_keys_backup_restore_success
@BindView(R.id.keys_backup_restore_success)
lateinit var mSuccessText: TextView
@BindView(R.id.keys_backup_restore_success_info)
lateinit var mSuccessDetailsText: TextView
private lateinit var sharedViewModel: KeysBackupRestoreSharedViewModel
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
sharedViewModel = activity?.run {
ViewModelProviders.of(this).get(KeysBackupRestoreSharedViewModel::class.java)
} ?: throw Exception("Invalid Activity")
sharedViewModel.importKeyResult?.let {
val part1 = resources.getQuantityString(R.plurals.keys_backup_restore_success_description_part1,
it.totalNumberOfKeys, it.totalNumberOfKeys)
val part2 = resources.getQuantityString(R.plurals.keys_backup_restore_success_description_part2,
it.successfullyNumberOfImportedKeys, it.successfullyNumberOfImportedKeys)
mSuccessDetailsText.text = String.format("%s\n%s", part1, part2)
}
//We don't put emoji in string xml as it will crash on old devices
mSuccessText.text = context?.getString(R.string.keys_backup_restore_success_title, "🎉")
}
@OnClick(R.id.keys_backup_setup_done_button)
fun onDone() {
sharedViewModel.importRoomKeysFinishWithResult.value = LiveEvent(sharedViewModel.importKeyResult!!)
}
companion object {
fun newInstance() = KeysBackupRestoreSuccessFragment()
}
}
|
apache-2.0
|
fc67926669c1896a79590bc46eca9df5
| 38.738462 | 108 | 0.739737 | 4.506108 | false | false | false | false |
Werb/PickPhotoSample
|
pickphotoview/src/main/java/com/werb/pickphotoview/util/PickPhotoHelper.kt
|
1
|
4190
|
package com.werb.pickphotoview.util
import android.content.ContentResolver
import android.database.Cursor
import android.provider.MediaStore
import android.support.annotation.Keep
import android.util.Log
import com.werb.eventbus.EventBus
import com.werb.pickphotoview.event.PickFinishEvent
import com.werb.pickphotoview.model.DirImage
import com.werb.pickphotoview.model.GroupImage
import java.io.File
import java.util.*
/**
* Created by wanbo on 2016/12/31.
*/
object PickPhotoHelper {
val selectImages: MutableList<String> by lazy { mutableListOf<String>() }
private val mGroupMap = LinkedHashMap<String, ArrayList<String>>()
private val dirNames = ArrayList<String>()
var groupImage: GroupImage? = null
private set
var dirImage: DirImage? = null
private set
fun start(showGif: Boolean, resolver: ContentResolver) {
clear()
imageThread(showGif, resolver).start()
Log.d("PickPhotoView", "PickPhotoHelper start")
}
fun stop() {
clear()
Log.d("PickPhotoView", "PickPhotoHelper stop")
}
private fun clear() {
selectImages.clear()
dirNames.clear()
mGroupMap.clear()
groupImage = null
dirImage = null
}
private fun imageThread(showGif: Boolean, resolver: ContentResolver): Thread {
return Thread(Runnable {
val mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
//jpeg & png & gif & video
val mCursor: Cursor?
mCursor = if (showGif) {
resolver.query(mImageUri, null,
MediaStore.Images.Media.MIME_TYPE + "=? or "
+ MediaStore.Images.Media.MIME_TYPE + "=? or "
+ MediaStore.Images.Media.MIME_TYPE + "=? or "
+ MediaStore.Images.Media.MIME_TYPE + "=?",
arrayOf("image/jpeg", "image/png", "image/x-ms-bmp", "image/gif"), MediaStore.Images.Media.DATE_MODIFIED + " desc")
} else {
resolver.query(mImageUri, null,
MediaStore.Images.Media.MIME_TYPE + "=? or "
+ MediaStore.Images.Media.MIME_TYPE + "=? or "
+ MediaStore.Images.Media.MIME_TYPE + "=?",
arrayOf("image/jpeg", "image/png", "image/x-ms-bmp"), MediaStore.Images.Media.DATE_MODIFIED + " desc")
}
if (mCursor == null) {
return@Runnable
}
while (mCursor.moveToNext()) {
// get image path
val path = mCursor.getString(mCursor
.getColumnIndex(MediaStore.Images.Media.DATA))
val file = File(path)
if (!file.exists()) {
continue
}
// get image parent name
val parentName = File(path).parentFile.name
// Log.d(PickConfig.TAG, parentName + ":" + path)
// save all Photo
if (!mGroupMap.containsKey(PickConfig.ALL_PHOTOS)) {
dirNames.add(PickConfig.ALL_PHOTOS)
val chileList = ArrayList<String>()
chileList.add(path)
mGroupMap.put(PickConfig.ALL_PHOTOS, chileList)
} else {
mGroupMap[PickConfig.ALL_PHOTOS]?.add(path)
}
// save by parent name
if (!mGroupMap.containsKey(parentName)) {
dirNames.add(parentName)
val chileList = ArrayList<String>()
chileList.add(path)
mGroupMap.put(parentName, chileList)
} else {
mGroupMap[parentName]?.add(path)
}
}
mCursor.close()
val groupImage = GroupImage()
groupImage.mGroupMap = mGroupMap
val dirImage = DirImage(dirNames)
this.groupImage = groupImage
this.dirImage = dirImage
EventBus.post(PickFinishEvent())
})
}
}
|
apache-2.0
|
9ea082a7f57a428ab887b929da64975a
| 35.754386 | 139 | 0.540095 | 4.866434 | false | false | false | false |
blademainer/intellij-community
|
platform/platform-impl/src/org/jetbrains/util/concurrency/Promise.kt
|
3
|
3683
|
/*
* 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.util.concurrency
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import org.jetbrains.concurrency
interface Promise<T> {
enum class State {
PENDING,
FULFILLED,
REJECTED
}
val state: State
fun done(done: (T) -> Unit): Promise<T>
fun rejected(rejected: (Throwable) -> Unit): Promise<T>
fun processed(processed: (T?) -> Unit): Promise<T>
fun <SUB_RESULT> then(done: (T) -> SUB_RESULT): Promise<SUB_RESULT>
fun <SUB_RESULT> thenAsync(done: (T) -> Promise<SUB_RESULT>): Promise<SUB_RESULT>
fun notify(child: AsyncPromise<T>): Promise<T>
companion object {
/**
* Log error if not message error
*/
fun logError(logger: Logger, e: Throwable) {
if (e !is MessageError || ApplicationManager.getApplication().isUnitTestMode) {
logger.error(e)
}
}
fun all(promises: Collection<Promise<*>>): Promise<*> = all<Any?>(promises, null)
fun <T> all(promises: Collection<Promise<*>>, totalResult: T): Promise<T> {
if (promises.isEmpty()) {
@Suppress("UNCHECKED_CAST")
return DONE as Promise<T>
}
val totalPromise = AsyncPromise<T>()
val done = CountDownConsumer(promises.size(), totalPromise, totalResult)
val rejected = {it: Throwable ->
if (totalPromise.state == Promise.State.PENDING) {
totalPromise.setError(it)
}
}
for (promise in promises) {
//noinspection unchecked
promise.done(done)
promise.rejected(rejected)
}
return totalPromise
}
}
}
private val DONE: Promise<*> = DonePromise(null)
private val REJECTED: Promise<*> = RejectedPromise<Any>(MessageError("rejected"))
internal class MessageError(error: String) : RuntimeException(error) {
@Synchronized fun fillInStackTrace(): Throwable? = this
}
fun <T> RejectedPromise(error: String): Promise<T> = RejectedPromise(MessageError(error))
fun ResolvedPromise(): Promise<*> = DONE
fun <T> ResolvedPromise(result: T): Promise<T> = DonePromise(result)
fun <T> concurrency.Promise<T>.toPromise(): AsyncPromise<T> {
val promise = AsyncPromise<T>()
val oldPromise = this
done({ promise.setResult(it) })
.rejected({ promise.setError(it) })
if (oldPromise is concurrency.AsyncPromise) {
promise
.done { oldPromise.setResult(it) }
.rejected { oldPromise.setError(it) }
}
return promise
}
fun <T> Promise<T>.toPromise(): concurrency.AsyncPromise<T> {
val promise = concurrency.AsyncPromise<T>()
done { promise.setResult(it) }
.rejected { promise.setError(it) }
return promise
}
private class CountDownConsumer<T>(private @field:Volatile var countDown: Int, private val promise: AsyncPromise<T>, private val totalResult: T) : (T) -> Unit {
override fun invoke(p1: T) {
if (--countDown == 0) {
promise.setResult(totalResult)
}
}
}
val Promise<*>.isPending: Boolean
get() = state == Promise.State.PENDING
val Promise<*>.isRejected: Boolean
get() = state == Promise.State.REJECTED
|
apache-2.0
|
7193d39334603234e5a126291e5d698e
| 28.472 | 160 | 0.680424 | 3.955961 | false | false | false | false |
fossasia/rp15
|
app/src/main/java/org/fossasia/openevent/general/auth/AuthHolder.kt
|
2
|
1000
|
package org.fossasia.openevent.general.auth
import org.fossasia.openevent.general.data.Preference
import org.fossasia.openevent.general.utils.JWTUtils
private const val TOKEN_KEY = "TOKEN"
class AuthHolder(private val preference: Preference) {
var token: String? = null
get() {
return preference.getString(TOKEN_KEY)
}
set(value) {
if (value != null && JWTUtils.isExpired(value))
throw IllegalStateException("Cannot set expired token")
field = value
preference.putString(TOKEN_KEY, value)
}
fun getAuthorization(): String? {
if (!isLoggedIn())
return null
return "JWT $token"
}
fun isLoggedIn(): Boolean {
if (token == null || JWTUtils.isExpired(token)) {
token = null
return false
}
return true
}
fun getId(): Long {
return if (!isLoggedIn()) -1 else JWTUtils.getIdentity(token)
}
}
|
apache-2.0
|
b64771451ec43066950bba8c9726c0e6
| 24.641026 | 71 | 0.591 | 4.545455 | false | false | false | false |
Yorxxx/played-next-kotlin
|
app/src/main/java/com/piticlistudio/playednext/util/ext/DesignSupport.kt
|
1
|
2463
|
package com.piticlistudio.playednext.util.ext
import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.graphics.Point
import android.support.annotation.StringRes
import android.support.design.widget.Snackbar
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentActivity
import android.view.View
import android.view.WindowManager
import android.widget.TextView
fun View.snackbar(text: CharSequence, duration: Int = Snackbar.LENGTH_SHORT, init: Snackbar.() -> Unit = {}): Snackbar {
val snack = Snackbar.make(this, text, duration)
snack.init()
snack.show()
return snack
}
fun View.snackbar(@StringRes() text: Int, duration: Int = Snackbar.LENGTH_SHORT, init: Snackbar.() -> Unit = {}): Snackbar {
val snack = Snackbar.make(this, text, duration)
snack.init()
snack.show()
return snack
}
fun Fragment.snackbar(text: CharSequence, duration: Int = Snackbar.LENGTH_LONG, init: Snackbar.() -> Unit = {}): Snackbar {
return getView()!!.snackbar(text, duration, init)
}
fun Fragment.snackbar(@StringRes() text: Int, duration: Int = Snackbar.LENGTH_LONG, init: Snackbar.() -> Unit = {}): Snackbar {
return getView()!!.snackbar(text, duration, init)
}
fun Activity.snackbar(view: View, text: CharSequence, duration: Int = Snackbar.LENGTH_LONG, init: Snackbar.() -> Unit = {}): Snackbar {
return view.snackbar(text, duration, init)
}
fun Activity.snackbar(view: View, @StringRes() text: Int, duration: Int = Snackbar.LENGTH_LONG, init: Snackbar.() -> Unit = {}): Snackbar {
return view.snackbar(text, duration, init)
}
fun FragmentActivity.setContentFragment(containerViewId: Int, f: () -> Fragment): Fragment? {
val manager = supportFragmentManager
val fragment = manager?.findFragmentById(containerViewId)
fragment?.let { return it }
return f().apply {
manager?.beginTransaction()?.add(containerViewId, this)?.commit()
}
}
inline fun Activity.getScreenHeight(): Int {
(this.applicationContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay?.let {
val size = Point()
it.getSize(size)
return size.y
}
return 0
}
fun Context.getScreenHeight(): Int {
(this.applicationContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay?.let {
val size = Point()
it.getSize(size)
return size.y
}
return 0
}
|
mit
|
d8676ae90948effb61bdc8e6f09ceec2
| 33.208333 | 139 | 0.709704 | 4.118729 | false | false | false | false |
vjache/klips
|
src/test/java/org/klips/dsl/AgendaManagerTest.kt
|
1
|
10417
|
package org.klips.dsl
import org.junit.Test
import org.klips.dsl.ActivationFilter.Both
import org.klips.engine.*
import org.klips.engine.LandKind.SandDesert
import org.klips.engine.ActorKind.*
import org.klips.engine.ActorKind.Guard
import org.klips.engine.State.*
import org.klips.engine.rete.ReteInput
import org.klips.engine.rete.builder.EscalatingAgendaManager
import org.klips.engine.rete.builder.PriorityAgendaManager
import org.klips.engine.rete.builder.RuleClause
import org.klips.engine.util.Log
class AgendaManagerTest {
companion object {
val aidVoid = ActorId(-1).facet
val pid1 = PlayerId(1)
val pid2 = PlayerId(2)
val players = mapOf(
pid1 to MyPlayer(pid1),
pid2 to MyPlayer(pid2)
)
}
class MyPlayer(val playerId: PlayerId) : PriorityAgendaManager(), Player {
private var lim = 1
override fun startTurn() {
lim = 1
}
override fun next() = if (lim > 0) decide()?.also {
super.remove(it.first, it.second)
lim--
} else null
private fun decide(): Pair<Modification<Binding>, RuleClause>? {
val asts = pqueue.filter { it.first.isAssert() }
if (asts.isEmpty()) return null
asts.random()?.let { first ->
val sol = first.first
val aid = sol[ref<ActorId>("aid")]
if (first.second.group == "Move") {
val e = sol[ref<Level>("nrgy")]
val fromCid = sol[ref<CellId>("cid1")]
val toCid = sol[ref<CellId>("cid2")]
println("### Player $playerId decide to act: [$aid] ${first.second.group}[$e] from [$fromCid] to [$toCid]")
} else {
println("### Player $playerId decide to act: [$aid] ${first.second.group}")
}
return first
}
return null
}
}
class TestRules :
RuleSet(
Log(),
// Log(workingMemory = true, agenda = true),
agendaManager = EscalatingAgendaManager(10000.0,
MultiplayerAgendaManager(players.values.toList()) { sol, _ ->
val pid: PlayerId = sol.fetchValue(ref<PlayerId>("pid"))
players[pid]!!
})
) {
val cid = ref<CellId>("cid")
val cid1 = ref<CellId>("cid1")
val cid2 = ref<CellId>("cid2")
val cid3 = ref<CellId>("cid3")
val cid4 = ref<CellId>("cid4")
val aid = ref<ActorId>("aid")
val aid1 = ref<ActorId>("aid1")
val kind = ref<ActorKind>("kind")
val land1 = ref<LandKind>("land1")
val land2 = ref<LandKind>("land2")
val pid = ref<PlayerId>("pid")
val pid1 = ref<PlayerId>("pid1")
val nrgy = ref<Level>("nrgy")
val nrgy1 = ref<Level>("nrgy1")
val hlth = ref<Level>("hlth")
val hlth1 = ref<Level>("hlth1")
val state = ref<State>("state")
val rtype = ref<ResourceType>("rtype")
init {
rule(name = "Adj-Symmetry") {
// Symmetry of adjacency
+Adjacent(cid, cid1)
effect {
+Adjacent(cid1, cid)
}
}
rule(name = "Move", priority = 10000.0) {
-At(aid, cid1)
+Adjacent(cid1, cid2)
-At(aidVoid, cid2)
+Land(cid1, land1)
+Land(cid2, land2)
val a = -Actor(aid, pid, kind, nrgy, hlth, OnMarch.facet)
val dE = 0.5f
guard {
it[nrgy].value >= dE
}
effect { sol ->
+At(aidVoid, cid1)
+At(aid, cid2)
+a.substitute(
nrgy to sol[nrgy].inc(-dE).facet
)
}
}
rule(name = "Deploy", priority = 10000.0) {
val a = -Actor(aid, pid, kind, nrgy, hlth, OnMarch.facet)
val dE = 0.5f
guard {
it[nrgy].value >= dE
}
effect { sol ->
+a.substitute(
nrgy to sol[nrgy].inc(-dE).facet,
OnMarch.facet to Deployed.facet
)
}
}
rule(name = "OnMarch", priority = 10000.0) {
val a = -Actor(aid, pid, kind, nrgy, hlth, Deployed.facet)
val dE = 0.5f
guard {
it[nrgy].value >= dE
}
effect { sol ->
+a.substitute(
nrgy to sol[nrgy].inc(-dE).facet,
Deployed.facet to OnMarch.facet
)
}
}
rule(name = "Attack", priority = 10000.0) {
+At(aid, cid)
+Adjacent(cid, cid1)
+At(aid1, cid1)
val attacker = -Actor(aid = aid, energy = nrgy, type = Guard.facet, state = OnMarch.facet, pid = pid)
val enemy = -Actor(aid = aid1, health = hlth1, pid = pid1)
val dE = 0.5f
val dH = 2.0f
guard { it[nrgy].value > dE }
guard(pid ne pid1)
effect { sol ->
+attacker.substitute(nrgy to sol[nrgy].inc(-dE).facet)
+enemy.substitute(hlth1 to sol[hlth1].inc(-dH).facet)
}
}
rule(name = "Repair", priority = 10000.0) {
+At(aid, cid)
+Adjacent(cid, cid1)
+At(aid1, cid1)
val repairer = -Actor(aid = aid, energy = nrgy, type = Worker.facet, state = OnMarch.facet, pid = pid)
val friend = -Actor(aid = aid1, health = hlth1, pid = pid)
val dE = 2.0f
val dH = 1.0f
guard { it[nrgy].value > dE }
effect { sol ->
+repairer.substitute(nrgy to sol[nrgy].inc(-dE).facet)
+friend.substitute(hlth1 to sol[hlth1].inc(dH).facet)
}
}
rule(name = "Charge", priority = 10000.0) {
+At(aid, cid)
+Adjacent(cid, cid1)
+At(aid1, cid1)
val charger = -Actor(aid = aid, energy = nrgy, type = Solar.facet, state = Deployed.facet, pid = pid)
val friend = -Actor(aid = aid1, health = hlth1, pid = pid)
val dE = 2.0f
val dE1 = 1.5f
guard { it[nrgy].value > dE }
effect { sol ->
+charger.substitute(nrgy to sol[nrgy].inc(-dE).facet)
+friend.substitute(hlth1 to sol[hlth1].inc(dE1).facet)
}
}
rule(name = "FeedAim", priority = 10000.0) {
val qty = ref<Int>("qty")
val cap = ref<Level>("cap")
+At(aid, cid)
val rsc = -Resource(cid, rtype, qty)
guard(qty gt 0)
val feeder = -Actor(aid = aid, health = hlth, energy = nrgy, pid = pid,
type = Worker.facet, state = Deployed.facet)
guard { it[hlth].value > 0.0f && it[nrgy].value > 0.0f }
+Actor(aid = aid1, type = Aim.facet, pid = pid)
val cb = -CargoBay(aid1, rtype, cap)
val dE = 0.1f
effect { sol ->
+feeder.substitute(nrgy to sol[nrgy].inc(-dE).facet)
+cb.substitute(cap to sol[cap].inc(sol[qty].toFloat()).facet)
val qty1 = sol[qty]-1
if(qty1 > 0)
+rsc.substitute(qty to qty1.facet)
}
}
rule(name = "Comm-Deployed") {
+Actor(aid, pid, Comm.facet, nrgy, hlth, Deployed.facet)
+At(aid, cid1)
+Adjacent(cid1, cid2)
+Adjacent(cid2, cid3)
// +Adjacent(cid3, cid4)
effect(activation = Both) {
!CommField(aid, cid2)
!CommField(aid, cid3)
// !CommField(aid, cid4)
}
}
}
}
@Test
fun basicTest() {
with(TestRules().input) {
flush("Adj-Symmetry") {
createSpace()
}
flush("Move") {
-At(aidVoid, cid(1, 1))
+At(aid(1), cid(1, 1))
+Actor(aid(1), pid1.facet, Worker.facet, Level().facet, Level().facet, OnMarch.facet)
-At(aidVoid, cid(5, 5))
+At(aid(3), cid(5, 5))
+Actor(aid(3), pid1.facet, Comm.facet, Level().facet, Level().facet, OnMarch.facet)
-At(aidVoid, cid(2, 2))
+At(aid(2), cid(2, 2))
+Actor(aid(2), pid2.facet, Worker.facet, Level().facet, Level().facet, OnMarch.facet)
}
for (i in 1..10)
flush {}
// flush{}
//
// flush{}
}
}
fun ReteInput.createSpace() {
for (i in 1..10) {
for (j in 1..10) {
val cid1 = cid(i, j)
+Land(cid1, SandDesert.facet)
+At(aidVoid, cid1)
+Adjacent(cid1, cid(i, j + 1))
+Adjacent(cid1, cid(i + 1, j))
}
}
}
fun ReteInput.placeAims(): Pair<ActorId, ActorId> {
val aim1 = ActorId()
val aim2 = ActorId()
+Actor(aim1, pid1, Aim, Deployed)
+Actor(aim2, pid2, Aim, Deployed)
+At(aim1.facet, cid(10, 10))
+At(aim2.facet, cid(90, 90))
return Pair(aim1, aim2)
}
val cidPool = mutableMapOf<Int, Facet.ConstFacet<CellId>>()
fun cid(i: Int, j: Int): Facet.ConstFacet<CellId> {
val n = i * 1000 + j
return cidPool.getOrPut(n) {
CellId(n).facet
}
}
val aidPool = mutableMapOf<Int, Facet<ActorId>>()
fun aid(i: Int): Facet<ActorId> {
return aidPool.getOrPut(i) {
ActorId(i).facet
}
}
}
|
apache-2.0
|
ab8d61c8a2f65af381123f64008bb704
| 29.641176 | 127 | 0.450706 | 4.025116 | false | false | false | false |
UweTrottmann/SeriesGuide
|
app/src/main/java/com/battlelancer/seriesguide/stats/StatsViewModel.kt
|
1
|
6894
|
package com.battlelancer.seriesguide.stats
import android.app.Application
import android.text.format.DateUtils
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.liveData
import androidx.lifecycle.viewModelScope
import com.battlelancer.seriesguide.provider.SgRoomDatabase
import com.battlelancer.seriesguide.settings.DisplaySettings
import com.battlelancer.seriesguide.shows.tools.ShowStatus
import kotlinx.coroutines.Dispatchers
class StatsViewModel(application: Application) : AndroidViewModel(application) {
val hideSpecials = MutableLiveData<Boolean>()
val statsData = Transformations.switchMap(hideSpecials) { hideSpecials ->
loadStats(hideSpecials)
}
init {
hideSpecials.value = DisplaySettings.isHidingSpecials(application)
}
private fun loadStats(excludeSpecials: Boolean) = liveData(
context = viewModelScope.coroutineContext + Dispatchers.IO
) {
val stats = Stats()
// movies
countMovies(stats)
emit(buildUpdate(stats))
// shows
val showRuntimes = countShows(stats, excludeSpecials)
emit(buildUpdate(stats))
// episodes
countEpisodes(stats, excludeSpecials)
emit(buildUpdate(stats))
// calculate runtime of watched episodes per show
var totalRuntimeMin: Long = 0
var previewTime = System.currentTimeMillis() + PREVIEW_UPDATE_INTERVAL_MS
for (showRuntime in showRuntimes) {
val showId = showRuntime.key
val runtimeOfShowMin = showRuntime.value
val helper = SgRoomDatabase.getInstance(getApplication()).sgEpisode2Helper()
val watchedEpisodesOfShowCount = if (excludeSpecials) {
helper.countWatchedEpisodesOfShowWithoutSpecials(showId)
} else {
helper.countWatchedEpisodesOfShow(showId)
}
if (watchedEpisodesOfShowCount == -1) {
// episode query failed, return what we have so far
stats.episodesWatchedRuntime = totalRuntimeMin * DateUtils.MINUTE_IN_MILLIS
emit(
StatsUpdateEvent(
stats,
finalValues = false,
successful = false
)
)
return@liveData
}
// make sure we calculate with long here (first arg is long) to avoid overflows
val runtimeOfEpisodesMin = runtimeOfShowMin * watchedEpisodesOfShowCount
totalRuntimeMin += runtimeOfEpisodesMin
// post regular update of minimum
val currentTime = System.currentTimeMillis()
if (currentTime > previewTime) {
previewTime = currentTime + PREVIEW_UPDATE_INTERVAL_MS
stats.episodesWatchedRuntime = totalRuntimeMin * DateUtils.MINUTE_IN_MILLIS
emit(buildUpdate(stats))
}
}
stats.episodesWatchedRuntime = totalRuntimeMin * DateUtils.MINUTE_IN_MILLIS
// return final values
emit(
StatsUpdateEvent(
stats,
finalValues = true,
successful = true
)
)
}
private fun buildUpdate(stats: Stats): StatsUpdateEvent {
return StatsUpdateEvent(
stats,
finalValues = false,
successful = true
)
}
private fun countMovies(stats: Stats) {
val helper = SgRoomDatabase.getInstance(getApplication()).movieHelper()
val countMovies = helper.countMovies()
val statsWatched = helper.getStatsWatched()
val statsInWatchlist = helper.getStatsInWatchlist()
val statsInCollection = helper.getStatsInCollection()
stats.movies = countMovies
stats.moviesWatched = statsWatched?.count ?: 0
stats.moviesWatchedRuntime = (statsWatched?.runtime ?: 0) * DateUtils.MINUTE_IN_MILLIS
stats.moviesWatchlist = statsInWatchlist?.count ?: 0
stats.moviesWatchlistRuntime = (statsInWatchlist?.runtime ?: 0) * DateUtils.MINUTE_IN_MILLIS
stats.moviesCollection = statsInCollection?.count ?: 0
stats.moviesCollectionRuntime =
(statsInCollection?.runtime ?: 0) * DateUtils.MINUTE_IN_MILLIS
}
/**
* Returns shows mapped to their runtime.
*/
private fun countShows(stats: Stats, excludeSpecials: Boolean): Map<Long, Int> {
val helper = SgRoomDatabase.getInstance(getApplication()).sgShow2Helper()
val showStats = helper.getStats()
var continuing = 0
var withnext = 0
val showRuntimes = mutableMapOf<Long, Int>()
for (show in showStats) {
// count continuing shows
if (show.status == ShowStatus.RETURNING) {
continuing++
}
// count shows that are planned to receive new episodes
if (show.status == ShowStatus.RETURNING
|| show.status == ShowStatus.PLANNED
|| show.status == ShowStatus.IN_PRODUCTION) {
withnext++
}
// map show to its runtime
showRuntimes[show.id] = show.runtime
}
stats.shows = showStats.size
stats.showsContinuing = continuing
stats.showsWithNextEpisodes = withnext
stats.showsFinished = if (excludeSpecials) {
helper.countShowsFinishedWatchingWithoutSpecials()
} else {
helper.countShowsFinishedWatching()
}
return showRuntimes
}
private fun countEpisodes(stats: Stats, excludeSpecials: Boolean) {
val helper = SgRoomDatabase.getInstance(getApplication()).sgEpisode2Helper()
stats.episodes = if (excludeSpecials) {
helper.countEpisodesWithoutSpecials()
} else {
helper.countEpisodes()
}
stats.episodesWatched = if (excludeSpecials) {
helper.countWatchedEpisodesWithoutSpecials()
} else {
helper.countWatchedEpisodes()
}
}
companion object {
private const val PREVIEW_UPDATE_INTERVAL_MS = DateUtils.SECOND_IN_MILLIS
}
}
data class Stats(
var shows: Int = 0,
var showsFinished: Int = 0,
var showsContinuing: Int = 0,
var showsWithNextEpisodes: Int = 0,
var episodes: Int = 0,
var episodesWatched: Int = 0,
var episodesWatchedRuntime: Long = 0,
var movies: Int = 0,
var moviesWatchlist: Int = 0,
var moviesWatchlistRuntime: Long = 0,
var moviesWatched: Int = 0,
var moviesWatchedRuntime: Long = 0,
var moviesCollection: Int = 0,
var moviesCollectionRuntime: Long = 0
)
data class StatsUpdateEvent(
val stats: Stats,
val finalValues: Boolean,
val successful: Boolean
)
|
apache-2.0
|
db8c1ccff0aafb4e024f314530f37af9
| 34.353846 | 100 | 0.63606 | 5.191265 | false | false | false | false |
elect86/modern-jogl-examples
|
src/main/kotlin/main/tut15/manyImages.kt
|
2
|
10287
|
package main.tut15
import com.jogamp.newt.event.KeyEvent
import com.jogamp.opengl.GL2ES3.*
import com.jogamp.opengl.GL2GL3.GL_UNSIGNED_INT_8_8_8_8_REV
import com.jogamp.opengl.GL3
import com.jogamp.opengl.GL3.GL_DEPTH_CLAMP
import com.jogamp.opengl.util.texture.spi.DDSImage
import glNext.*
import glm.*
import glm.mat.Mat4
import glm.vec._3.Vec3
import main.framework.Framework
import main.framework.Semantic
import main.framework.component.Mesh
import uno.buffer.*
import uno.glm.MatrixStack
import uno.glsl.programOf
import uno.time.Timer
import java.io.File
import java.nio.ByteBuffer
/**
* Created by GBarbieri on 31.03.2017.
*/
fun main(args: Array<String>) {
ManyImages_().setup("Tutorial 15 - Many Images")
}
class ManyImages_ : Framework() {
lateinit var program: ProgramData
lateinit var plane: Mesh
lateinit var corridor: Mesh
val projBufferName = intBufferBig(1)
object Texture {
val Checker = 0
val MipmapTest = 1
val MAX = 2
}
val textureName = intBufferBig(Texture.MAX)
val samplerName = intBufferBig(Sampler.MAX)
val camTimer = Timer(Timer.Type.Loop, 5f)
var useMipmapTexture = false
var currSampler = 0
var drawCorridor = false
override fun init(gl: GL3) = with(gl) {
initializeProgram(gl)
plane = Mesh(gl, javaClass, "tut15/BigPlane.xml")
corridor = Mesh(gl, javaClass, "tut15/Corridor.xml")
glEnable(GL_CULL_FACE)
glCullFace(GL_BACK)
glFrontFace(GL_CW)
val depthZNear = 0f
val depthZFar = 1f
glEnable(GL_DEPTH_TEST)
glDepthMask(true)
glDepthFunc(GL_LEQUAL)
glDepthRangef(depthZNear, depthZFar)
glEnable(GL_DEPTH_CLAMP)
//Setup our Uniform Buffers
glGenBuffer(projBufferName)
glBindBuffer(GL_UNIFORM_BUFFER, projBufferName)
glBufferData(GL_UNIFORM_BUFFER, Mat4.SIZE, GL_DYNAMIC_DRAW)
glBindBufferRange(GL_UNIFORM_BUFFER, Semantic.Uniform.PROJECTION, projBufferName, 0, Mat4.SIZE)
glBindBuffer(GL_UNIFORM_BUFFER)
// Generate all the texture names
glGenTextures(textureName)
loadCheckerTexture(gl)
loadMipmapTexture(gl)
createSamplers(gl)
}
fun initializeProgram(gl: GL3) {
program = ProgramData(gl, "pt.vert", "tex.frag")
}
fun loadCheckerTexture(gl: GL3) = with(gl) {
val file = File(javaClass.getResource("/tut15/checker.dds").toURI())
val ddsImage = DDSImage.read(file)
glBindTexture(GL_TEXTURE_2D, textureName[Texture.Checker])
repeat(ddsImage.numMipMaps) { mipmapLevel ->
val mipmap = ddsImage.getMipMap(mipmapLevel)
glTexImage2D(GL_TEXTURE_2D, mipmapLevel, GL_RGB8, mipmap.width, mipmap.height, 0,
GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, mipmap.data)
}
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, ddsImage.numMipMaps - 1)
glBindTexture(GL_TEXTURE_2D)
}
fun loadMipmapTexture(gl: GL3) = with(gl) {
glBindTexture(GL_TEXTURE_2D, textureName[Texture.MipmapTest])
val oldAlign = glGetInteger(GL_UNPACK_ALIGNMENT)
glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
for (mipmapLevel in 0..7) {
val width = 128 shr mipmapLevel
val height = 128 shr mipmapLevel
val currColor = mipmapColors[mipmapLevel]
val buffer = fillWithColors(currColor, width, height)
glTexImage2D(GL_TEXTURE_2D, mipmapLevel, GL_RGB8, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, buffer)
buffer.destroy()
}
glPixelStorei(GL_UNPACK_ALIGNMENT, oldAlign)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 7)
glBindTexture(GL_TEXTURE_2D)
}
val mipmapColors = arrayOf(
byteArrayOf(0xFF.b, 0xFF.b, 0x00.b),
byteArrayOf(0xFF.b, 0x00.b, 0xFF.b),
byteArrayOf(0x00.b, 0xFF.b, 0xFF.b),
byteArrayOf(0xFF.b, 0x00.b, 0x00.b),
byteArrayOf(0x00.b, 0xFF.b, 0x00.b),
byteArrayOf(0x00.b, 0x00.b, 0xFF.b),
byteArrayOf(0x00.b, 0x00.b, 0x00.b),
byteArrayOf(0xFF.b, 0xFF.b, 0xFF.b))
fun fillWithColors(color: ByteArray, width: Int, height: Int): ByteBuffer {
val numTexels = width * height
val buffer = byteBufferBig(numTexels * 3)
val (red, green, blue) = color
while (buffer.hasRemaining())
buffer
.put(red)
.put(green)
.put(blue)
buffer.position(0)
return buffer
}
fun createSamplers(gl: GL3) = with(gl) {
glGenSamplers(Sampler.MAX, samplerName)
repeat(Sampler.MAX) {
glSamplerParameteri(samplerName[it], GL_TEXTURE_WRAP_S, GL_REPEAT)
glSamplerParameteri(samplerName[it], GL_TEXTURE_WRAP_T, GL_REPEAT)
}
glSamplerParameteri(samplerName[Sampler.Nearest], GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glSamplerParameteri(samplerName[Sampler.Nearest], GL_TEXTURE_MIN_FILTER, GL_NEAREST)
glSamplerParameteri(samplerName[Sampler.Linear], GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glSamplerParameteri(samplerName[Sampler.Linear], GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glSamplerParameteri(samplerName[Sampler.Linear_MipMap_Nearest], GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glSamplerParameteri(samplerName[Sampler.Linear_MipMap_Nearest], GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST)
glSamplerParameteri(samplerName[Sampler.Linear_MipMap_Linear], GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glSamplerParameteri(samplerName[Sampler.Linear_MipMap_Linear], GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR)
glSamplerParameteri(samplerName[Sampler.LowAnysotropic], GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glSamplerParameteri(samplerName[Sampler.LowAnysotropic], GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR)
glSamplerParameterf(samplerName[Sampler.LowAnysotropic], GL_TEXTURE_MAX_ANISOTROPY_EXT, 4.0f)
val maxAniso = caps.limits.MAX_TEXTURE_MAX_ANISOTROPY_EXT
println("Maximum anisotropy: " + maxAniso)
glSamplerParameteri(samplerName[Sampler.MaxAnysotropic], GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glSamplerParameteri(samplerName[Sampler.MaxAnysotropic], GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR)
glSamplerParameteri(samplerName[Sampler.MaxAnysotropic], GL_TEXTURE_MAX_ANISOTROPY_EXT, maxAniso)
}
override fun display(gl: GL3) = with(gl) {
glClearBufferf(GL_COLOR, 0.75f, 0.75f, 1.0f, 1.0f)
glClearBufferf(GL_DEPTH)
camTimer.update()
val cyclicAngle = camTimer.getAlpha() * 6.28f
val hOffset = glm.cos(cyclicAngle) * .25f
val vOffset = glm.sin(cyclicAngle) * .25f
val modelMatrix = MatrixStack()
val worldToCamMat = glm.lookAt(
Vec3(hOffset, 1f, -64f),
Vec3(hOffset, -5f + vOffset, -44f),
Vec3(0f, 1f, 0f))
modelMatrix.applyMatrix(worldToCamMat) run {
glUseProgram(program.theProgram)
glUniformMatrix4f(program.modelToCameraMatrixUL, top())
glActiveTexture(GL_TEXTURE0 + Semantic.Sampler.DIFFUSE)
glBindTexture(GL_TEXTURE_2D, textureName[if (useMipmapTexture) Texture.MipmapTest else Texture.Checker])
glBindSampler(Semantic.Sampler.DIFFUSE, samplerName[currSampler])
if (drawCorridor)
corridor.render(gl, "tex")
else
plane.render(gl, "tex")
glBindSampler(Semantic.Sampler.DIFFUSE)
glBindTexture(GL_TEXTURE_2D)
glUseProgram()
}
}
override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) {
val persMatrix = MatrixStack()
persMatrix.perspective(90f, w / h.f, 1f, 1000f)
glBindBuffer(GL_UNIFORM_BUFFER, projBufferName)
glBufferSubData(GL_UNIFORM_BUFFER, persMatrix.top())
glBindBuffer(GL_UNIFORM_BUFFER)
glViewport(w, h)
}
override fun end(gl: GL3) = with(gl) {
plane.dispose(gl)
corridor.dispose(gl)
glDeleteProgram(program.theProgram)
glDeleteBuffer(projBufferName)
glDeleteTextures(textureName)
glDeleteSamplers(samplerName)
destroyBuffers(projBufferName, textureName, samplerName)
}
override fun keyPressed(ke: KeyEvent) {
when (ke.keyCode) {
KeyEvent.VK_ESCAPE -> quit()
KeyEvent.VK_SPACE -> useMipmapTexture = !useMipmapTexture
KeyEvent.VK_Y -> drawCorridor = !drawCorridor
KeyEvent.VK_P -> camTimer.togglePause()
}
if (ke.keyCode in KeyEvent.VK_1 .. KeyEvent.VK_9) {
val number = ke.keyCode - KeyEvent.VK_1
if (number < Sampler.MAX) {
println("Sampler: " + samplerNames[number])
currSampler = number
}
}
}
object Sampler {
val Nearest = 0
val Linear = 1
val Linear_MipMap_Nearest = 2
val Linear_MipMap_Linear = 3
val LowAnysotropic = 4
val MaxAnysotropic = 5
val MAX = 6
}
val samplerNames = arrayOf("Nearest", "Linear", "Linear with nearest mipmaps", "Linear with linear mipmaps", "Low anisotropic", "Max anisotropic")
class ProgramData(gl: GL3, vertex: String, fragment: String) {
val theProgram = programOf(gl, javaClass, "tut15", vertex, fragment)
val modelToCameraMatrixUL = gl.glGetUniformLocation(theProgram, "modelToCameraMatrix")
init {
with(gl) {
glUniformBlockBinding(
theProgram,
glGetUniformBlockIndex(theProgram, "Projection"),
Semantic.Uniform.PROJECTION)
glUseProgram(theProgram)
glUniform1i(
glGetUniformLocation(theProgram, "colorTexture"),
Semantic.Sampler.DIFFUSE)
glUseProgram()
}
}
}
}
|
mit
|
8dbeefb49410c372c74e8784f0df0ce9
| 30.365854 | 150 | 0.635365 | 4.075674 | false | false | false | false |
wakim/esl-pod-client
|
app/src/main/java/br/com/wakim/eslpodclient/android/service/PlayerService.kt
|
1
|
20185
|
package br.com.wakim.eslpodclient.android.service
import android.app.PendingIntent
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.drawable.BitmapDrawable
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.AsyncTask
import android.os.IBinder
import android.support.annotation.DrawableRes
import android.support.annotation.StringRes
import android.support.v4.app.NotificationCompat
import android.support.v4.app.NotificationManagerCompat
import android.support.v4.content.ContextCompat
import android.support.v4.media.session.MediaButtonReceiver
import android.support.v4.media.session.MediaControllerCompat
import android.support.v4.media.session.MediaSessionCompat
import android.view.KeyEvent
import br.com.wakim.eslpodclient.Application
import br.com.wakim.eslpodclient.R
import br.com.wakim.eslpodclient.android.notification.NotificationActivity
import br.com.wakim.eslpodclient.dagger.AppComponent
import br.com.wakim.eslpodclient.data.interactor.PodcastInteractor
import br.com.wakim.eslpodclient.data.interactor.StorageInteractor
import br.com.wakim.eslpodclient.data.model.DownloadStatus
import br.com.wakim.eslpodclient.data.model.PodcastItem
import br.com.wakim.eslpodclient.util.extensions.getFileNameWithExtension
import br.com.wakim.eslpodclient.util.extensions.ofIOToMainThread
import com.danikula.videocache.CacheListener
import com.danikula.videocache.HttpProxyCacheServer
import rx.Subscription
import java.io.File
import java.lang.ref.WeakReference
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class PlayerService : Service() {
companion object {
const val ID = 42
const val TAG = "PlayerService Session"
const val CONTENT_INTENT_ACTION = "CONTENT_INTENT"
}
val localBinder = PlayerLocalBinder(this)
val proxy: HttpProxyCacheServer by lazy {
val cacheServer = HttpProxyCacheServer.Builder(this)
.cacheDirectory(storageInteractor.getBaseDir())
.fileNameGenerator { url ->
val filename = url.getFileNameWithExtension()
storageInteractor.prepareFile(filename)
storageInteractor.prepareFile("$filename.download")
filename
}
.maxCacheFilesCount(Integer.MAX_VALUE)
.build()
cacheServer
}
internal var mediaPlayer : MediaPlayer? = null
get() {
if (released || field == null) {
val mp = MediaPlayer()
mp.setAudioStreamType(AudioManager.STREAM_MUSIC)
mp.setOnBufferingUpdateListener { mediaPlayer, buffer ->
if (isPlaying() && !usingCache) {
callback?.onCacheProgress(((buffer.toFloat() * getDuration()) / 100F).toInt())
}
}
mp.setOnPreparedListener {
initalized = true
preparing = false
play()
}
mp.setOnCompletionListener {
mp.stop()
mp.reset()
}
released = false
field = mp
}
return field
}
val mediaSessionCallback = object : MediaSessionCompat.Callback() {
override fun onPlay() {
play()
}
override fun onSkipToNext() {
skipToNext()
}
override fun onSkipToPrevious() {
skipToPrevious()
}
override fun onPause() {
pause()
}
override fun onStop() {
stop()
}
override fun onSeekTo(pos: Long) {
seek(pos.toInt())
}
}
val audioFocusChangeListener = AudioManager.OnAudioFocusChangeListener { focusChange ->
when (focusChange) {
AudioManager.AUDIOFOCUS_GAIN -> play()
else -> pause()
}
}
val noisyReceiver = object : SmartReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
pause()
}
}
@Inject
lateinit var audioManager: AudioManager
@Inject
lateinit var storageInteractor: StorageInteractor
@Inject
lateinit var podcastInteractor: PodcastInteractor
@Inject
lateinit var notificationManagerCompat: NotificationManagerCompat
@Inject
lateinit var playlistManager: PlaylistManager
private var session: MediaSessionCompat? = null
private var controller: MediaControllerCompat? = null
var podcastItem: PodcastItem? = null
private set
private var downloadStatus: DownloadStatus? = null
private var initialPosition: Int = 0
private var task: DurationUpdatesTask? = null
private var downloadStatusSubscription: Subscription? = null
var callback: PlayerCallback? = null
set(value) {
field = value
startTaskIfNeeded()
}
val cacheListener = CacheListener { cacheFile: File, url: String, percentsAvailable: Int ->
val decimalPercent = percentsAvailable.toFloat() / 100F
callback?.onSeekAvailable(false)
if (isPlaying()) {
callback?.onCacheProgress((decimalPercent * mediaPlayer!!.duration.toFloat()).toInt())
}
if (percentsAvailable == 100) {
storageInteractor.deleteFile("${podcastItem!!.mp3Url}.download")
storageInteractor.getDownloadStatus(podcastItem!!)
.ofIOToMainThread()
.subscribe()
callback?.onStreamTypeResolved(PodcastItem.LOCAL)
}
}
var initalized = false
private set
private var released = false
private var preparing = false
private var stopped = false
private var usingCache = false
override fun onCreate() {
super.onCreate()
(applicationContext.getSystemService(AppComponent::class.java.simpleName) as AppComponent?)?.inject(this)
session = session ?: initMediaSession()
}
override fun onBind(p0: Intent?): IBinder? {
return localBinder
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
intent?.let {
MediaButtonReceiver.handleIntent(session, intent)
handleIntent(it)
}
return super.onStartCommand(intent, flags, startId)
}
fun handleIntent(intent : Intent) {
val action = intent.action
if (CONTENT_INTENT_ACTION == action) {
openNotificationActivity()
} else if (Intent.ACTION_MEDIA_BUTTON != action) {
return
}
val event = intent.getParcelableExtra<KeyEvent>(Intent.EXTRA_KEY_EVENT)
controller?.let {
when (event?.keyCode) {
KeyEvent.KEYCODE_MEDIA_PLAY -> it.transportControls.play()
KeyEvent.KEYCODE_MEDIA_PAUSE -> it.transportControls.pause()
KeyEvent.KEYCODE_MEDIA_STOP -> it.transportControls.stop()
KeyEvent.KEYCODE_ESCAPE -> dispose()
KeyEvent.KEYCODE_MEDIA_NEXT -> it.transportControls.skipToNext()
KeyEvent.KEYCODE_MEDIA_PREVIOUS -> it.transportControls.skipToPrevious()
}
}
}
private fun openNotificationActivity() {
val intent = Intent(this, NotificationActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
if (isPlaying()) {
notifyPlaying()
} else {
notifyStopped()
}
}
private fun initMediaSession() : MediaSessionCompat {
val session = MediaSessionCompat(this, TAG)
val flags = MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS or
MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS
controller = MediaControllerCompat(this, session.sessionToken)
session.setFlags(flags)
session.setCallback(mediaSessionCallback)
return session
}
fun play(podcastItem: PodcastItem, position: Int) {
if (!((Application.INSTANCE?.connected) ?: false)) {
callback?.onConnectivityError()
return
}
if (isPlaying() && podcastItem == this.podcastItem) {
return
}
if (initalized || preparing) {
reset()
}
if (this.podcastItem != null && storageInteractor.shouldCache()) {
proxy.shutdownClient(this.podcastItem!!.mp3Url)
}
this.podcastItem = podcastItem
this.initialPosition = position
play()
}
fun reset() {
if (!initalized && !preparing) {
return
}
if (isPlaying()) {
pause()
}
mediaPlayer!!.reset()
initialPosition = 0
preparing = false
initalized = false
}
private fun play() {
if (stopped) {
startService(Intent(this, PlayerService::class.java))
stopped = false
}
if (isPlaying()) {
return
}
if (!initalized) {
prepareMediaPlayer()
preparing = true
return
}
if (!requestAudioFocus()) {
callback?.onAudioFocusFailed()
return
}
session?.isActive = true
registerNoisyReceiver()
startAndSeek()
startTaskIfNeeded()
setupSessionState(true)
callback?.let {
it.onDurationChanged(mediaPlayer!!.duration)
it.onPlayerStarted()
}
notifyPlaying()
callback?.onCacheProgress(if (downloadStatus?.status == DownloadStatus.DOWNLOADED) getDuration().toInt() else 0)
}
fun notifyPlaying() {
notify(podcastItem!!.title, generateAction(R.drawable.ic_pause_white_36dp, R.string.pause, KeyEvent.KEYCODE_MEDIA_PAUSE))
}
private fun setupSessionState(playing: Boolean) {
session?.isActive = playing
}
private fun prepareMediaPlayer() {
callback?.onPlayerPreparing()
podcastItem?.let {
downloadStatusSubscription?.unsubscribe()
downloadStatusSubscription =
storageInteractor.getDownloadStatus(it)
.zipWith(podcastInteractor.getLastSeekPos(it.remoteId)) {
downloadStatus, lastSeekPos -> downloadStatus to lastSeekPos
}
.ofIOToMainThread()
.subscribe { pair ->
prepare(pair.first, it)
initialPosition = pair.second ?: initialPosition
}
}
}
private fun prepare(downloadStatus: DownloadStatus, podcastItem: PodcastItem) {
val url: String
this.downloadStatus = downloadStatus
usingCache = false
if (downloadStatus.status == DownloadStatus.DOWNLOADED) {
url = downloadStatus.localPath!!
} else {
proxy.unregisterCacheListener(cacheListener)
if (storageInteractor.shouldCache()) {
url = proxy.getProxyUrl(podcastItem.mp3Url)
proxy.registerCacheListener(cacheListener, podcastItem.mp3Url)
usingCache = true
} else {
url = podcastItem.mp3Url
}
}
callback?.onStreamTypeResolved(getStreamType())
callback?.onSeekAvailable(true)
mediaPlayer!!.setDataSource(url)
mediaPlayer!!.prepareAsync()
}
private fun startAndSeek() {
mediaPlayer!!.start()
mediaPlayer!!.seekTo(initialPosition)
}
private fun startTaskIfNeeded() {
task?.cancel(true)
if (!isPlaying()) {
return
}
callback?.let {
task = DurationUpdatesTask(this).execute() as DurationUpdatesTask
}
}
private fun registerNoisyReceiver() {
if (noisyReceiver.registered) {
return
}
registerReceiver(noisyReceiver, IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY))
noisyReceiver.registered = true
}
private fun unregisterNoisyReceiver() {
if (!noisyReceiver.registered) {
return
}
unregisterReceiver(noisyReceiver)
noisyReceiver.registered = false
}
private fun requestAudioFocus() : Boolean {
val result = audioManager.requestAudioFocus(audioFocusChangeListener,
AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN)
return result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED
}
fun skipToNext() {
val nextItem = playlistManager.nextOrNull(podcastItem!!)
nextItem?.let {
play(it, 0)
callback?.onSkippedToNext(it)
}
}
fun skipToPrevious() {
val previousItem = playlistManager.previousOrNull(podcastItem!!)
previousItem?.let {
play(it, 0)
callback?.onSkippedToPrevious(it)
}
}
fun dispose() {
release()
stopSelf()
stopped = true
}
fun stop() {
innerStop()
notifyStopped()
}
fun notifyStopped() {
podcastItem?.let {
notify(it.title, generateAction(R.drawable.ic_play_arrow_white_36dp, R.string.play, KeyEvent.KEYCODE_MEDIA_PLAY))
}
}
private fun innerStop() {
if (isPlaying()) {
downloadStatusSubscription?.unsubscribe()
initialPosition = 0
mediaPlayer!!.stop()
reset()
session?.isActive = false
unregisterNoisyReceiver()
callback?.onPlayerStopped()
task?.cancel(true)
}
if (podcastItem != null) {
podcastInteractor.insertLastSeekPos(podcastItem!!.remoteId, 0)
}
}
fun pause() {
if (isPlaying()) {
initialPosition = mediaPlayer!!.currentPosition
podcastInteractor.insertLastSeekPos(podcastItem!!.remoteId, initialPosition)
mediaPlayer!!.pause()
reset()
session?.isActive = false
unregisterNoisyReceiver()
callback?.onPlayerPaused()
task?.cancel(true)
notifyStopped()
}
}
fun seek(pos : Int) {
initialPosition = pos
podcastInteractor.insertLastSeekPos(podcastItem!!.remoteId, pos)
if (isPlaying()) {
mediaPlayer!!.seekTo(pos)
}
callback?.onPositionChanged(pos)
}
private fun whenFromPosition() : Long {
var now = System.currentTimeMillis()
if (isPlaying())
now -= mediaPlayer!!.currentPosition
return now
}
fun isPlaying() = initalized && mediaPlayer!!.isPlaying
@PodcastItem.StreamType
fun getStreamType(): Long {
if (downloadStatus?.status == DownloadStatus.DOWNLOADED) {
return PodcastItem.LOCAL
} else if (storageInteractor.shouldCache()) {
return PodcastItem.CACHING
}
return PodcastItem.REMOTE
}
fun getDuration() : Float {
if (isPlaying()) {
return mediaPlayer!!.duration.toFloat()
}
return 0F
}
override fun onDestroy() {
release()
}
private fun release() {
if (isPlaying()) {
innerStop()
}
if (!released) {
mediaPlayer!!.reset()
mediaPlayer!!.release()
initalized = false
preparing = false
audioManager.abandonAudioFocus(audioFocusChangeListener)
proxy.shutdown()
session?.release()
}
released = true
notificationManagerCompat.cancel(ID)
}
private fun notify(mediaTitle: String, action: NotificationCompat.Action) {
val builder = android.support.v7.app.NotificationCompat.Builder(this)
val style = android.support.v7.app.NotificationCompat.MediaStyle()
val stopIntent = getActionIntent(KeyEvent.KEYCODE_ESCAPE)
style .setMediaSession(session!!.sessionToken)
.setShowActionsInCompactView(0, 1, 2, 3)
.setCancelButtonIntent(stopIntent)
.setShowCancelButton(true)
builder.mStyle = style
builder
.setUsesChronometer(isPlaying())
.setWhen(whenFromPosition())
.setContentIntent(generatePendingIntent())
.setDeleteIntent(stopIntent)
.setContentTitle(mediaTitle)
.setAutoCancel(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setLargeIcon((ContextCompat.getDrawable(this, R.mipmap.ic_launcher) as BitmapDrawable).bitmap)
.setSmallIcon(R.mipmap.ic_launcher)
.addAction(generateAction(R.drawable.ic_skip_previous_white_36dp, R.string.previous, KeyEvent.KEYCODE_MEDIA_PREVIOUS))
.addAction(action)
.addAction(generateAction(R.drawable.ic_stop_white_36dp, R.string.stop, KeyEvent.KEYCODE_MEDIA_STOP))
.addAction(generateAction(R.drawable.ic_skip_next_white_36dp, R.string.next, KeyEvent.KEYCODE_MEDIA_NEXT))
val notification = builder.build()
notificationManagerCompat.notify(ID, notification)
}
private fun generatePendingIntent(): PendingIntent {
val intent = Intent(this, PlayerService::class.java)
intent.action = CONTENT_INTENT_ACTION
return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
private fun generateAction(@DrawableRes icon : Int, @StringRes titleResId : Int, intentAction : Int) : NotificationCompat.Action =
NotificationCompat.Action.Builder(icon, getString(titleResId), getActionIntent(intentAction)).build()
private fun getActionIntent(intentAction : Int) : PendingIntent {
val intent = Intent(Intent.ACTION_MEDIA_BUTTON)
intent.`package` = packageName
intent.putExtra(Intent.EXTRA_KEY_EVENT, KeyEvent(KeyEvent.ACTION_DOWN, intentAction))
return PendingIntent.getService(this, intentAction, intent, 0)
}
}
class PlayerLocalBinder : TypedBinder<PlayerService> {
lateinit var reference : WeakReference<PlayerService>
override val service: PlayerService?
get() = reference.get()
constructor(playerService: PlayerService) : super() {
reference = WeakReference(playerService)
}
}
class DurationUpdatesTask(var service: PlayerService) : AsyncTask<Void , Int, Void>() {
val interval = TimeUnit.SECONDS.toMillis(1)
override fun doInBackground(vararg p0: Void): Void? {
while (!isCancelled) {
publishProgress(service.mediaPlayer!!.currentPosition)
try {
Thread.sleep(interval)
} catch (ignored: InterruptedException) {
break
}
}
return null
}
override fun onProgressUpdate(vararg values: Int?) {
values[0]?.let {
service.callback?.onPositionChanged(it)
}
}
}
interface PlayerCallback {
fun onDurationChanged(duration : Int)
fun onPositionChanged(position : Int)
fun onAudioFocusFailed()
fun onCacheProgress(position: Int)
fun onSeekAvailable(available: Boolean)
fun onPlayerPreparing()
fun onPlayerStarted()
fun onPlayerPaused()
fun onPlayerStopped()
fun onStreamTypeResolved(@PodcastItem.StreamType streamType: Long)
fun onSkippedToPrevious(podcastItem: PodcastItem)
fun onSkippedToNext(podcastItem: PodcastItem)
fun onConnectivityError()
}
abstract class SmartReceiver : BroadcastReceiver() {
var registered = false
}
|
apache-2.0
|
234d8ed4787e6de2786ee0da29e344e1
| 27.075104 | 134 | 0.612187 | 5.255142 | false | false | false | false |
google/fhir-app-examples
|
buildSrc/src/main/kotlin/Plugins.kt
|
1
|
1563
|
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
object Plugins {
object BuildPlugins {
const val androidLib = "com.android.library"
const val application = "com.android.application"
const val kotlinAndroid = "kotlin-android"
const val kotlinKapt = "kotlin-kapt"
const val mavenPublish = "maven-publish"
const val javaLibrary = "java-library"
const val kotlin = "kotlin"
const val navSafeArgs = "androidx.navigation.safeargs.kotlin"
const val spotless = "com.diffplug.spotless"
}
// classpath plugins
const val androidGradlePlugin = "com.android.tools.build:gradle:${Versions.androidGradlePlugin}"
const val kotlinGradlePlugin =
"org.jetbrains.kotlin:kotlin-gradle-plugin:${Dependencies.Versions.Kotlin.stdlib}"
const val navSafeArgsGradlePlugin =
"androidx.navigation:navigation-safe-args-gradle-plugin:${Dependencies.Versions.Androidx.navigation}"
object Versions {
const val androidGradlePlugin = "7.0.2"
const val buildTools = "30.0.2"
}
}
|
apache-2.0
|
014d56245dcee52c1b74060b01608376
| 36.214286 | 105 | 0.733845 | 4.113158 | false | false | false | false |
nfrankel/kaadin
|
kaadin-core/src/test/kotlin/ch/frankel/kaadin/interaction/MenuBarTest.kt
|
1
|
3380
|
/*
* Copyright 2016 Nicolas Fränkel
*
* 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 ch.frankel.kaadin.interaction
import ch.frankel.kaadin.horizontalLayout
import ch.frankel.kaadin.menuBar
import ch.frankel.kaadin.menuItem
import ch.frankel.kaadin.select
import com.vaadin.server.FontAwesome.*
import com.vaadin.ui.*
import org.assertj.core.api.Assertions.assertThat
import org.testng.annotations.Test
class MenuBarTest {
@Test
fun `menu bar should be added to layout`() {
val layout = horizontalLayout {
menuBar()
}
assertThat(layout.componentCount).isEqualTo(1)
val component = layout.getComponent(0)
assertThat(component).isNotNull.isInstanceOf(MenuBar::class.java)
}
@Test(dependsOnMethods = ["menu bar should be added to layout"])
fun `menu bar should be configurable`() {
val icon = AMAZON
val layout = horizontalLayout {
menuBar {
this.icon = icon
}
}
val menuBar = layout.getComponent(0) as MenuBar
assertThat(menuBar.icon).isNotNull.isSameAs(icon)
}
@Test(dependsOnMethods = ["menu bar should be added to layout"])
fun `menu items should be added to menu bar`() {
val size = 3
val layout = horizontalLayout {
menuBar {
repeat(size + 1) {
menuItem("Hello World", onClick = { })
}
}
}
val menuBar = layout.getComponent(0) as MenuBar
assertThat(menuBar.items).isNotNull.isNotEmpty.hasSize(size + 1)
}
@Test(dependsOnMethods = ["menu items should be added to menu bar"])
fun `menu items should be configurable`() {
val icon = AMAZON
val layout = horizontalLayout {
menuBar {
menuItem("Hello World", onClick = { }) {
this.icon = icon
}
}
}
val menuBar = layout.getComponent(0) as MenuBar
assertThat(menuBar.items[0].icon).isNotNull.isSameAs(icon)
}
@Test(dependsOnMethods = ["menu items should be added to menu bar"])
fun `menu items should display text and react on click`() {
val size = 3
val caption = "Hello World"
val clicked = mutableListOf(false, false, false, false)
val range = IntRange(0, size)
val layout = horizontalLayout {
menuBar {
range.forEach { i ->
menuItem("$caption $i", onClick = { clicked[i] = true })
}
}
}
val menuBar = layout.getComponent(0) as MenuBar
range.forEach {
val item = menuBar.items[it]
assertThat(item.text).isEqualTo("$caption $it")
item.select()
assertThat(clicked[it]).isTrue()
}
}
}
|
apache-2.0
|
a1713ed4e0c2c8354ca95213229e8dce
| 32.465347 | 76 | 0.607576 | 4.597279 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.