repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
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
juankysoriano/rainbow
demo/src/main/java/com/juankysoriano/rainbow/demo/sketch/rainbow/portrait/RainbowMessyLinePaiting.kt
1
8394
package com.juankysoriano.rainbow.demo.sketch.rainbow.portrait import android.graphics.Color.* import android.view.ViewGroup import com.juankysoriano.rainbow.core.Rainbow import com.juankysoriano.rainbow.core.drawing.Modes import com.juankysoriano.rainbow.core.drawing.RainbowDrawer import com.juankysoriano.rainbow.core.graphics.RainbowImage import com.juankysoriano.rainbow.core.matrix.RVector import com.juankysoriano.rainbow.utils.RainbowMath.* import kotlin.math.floor private const val STEPS = 800 class RainbowMessyLinePaiting(viewGroup: ViewGroup) : Rainbow(viewGroup) { private lateinit var originalImage: RainbowImage private lateinit var thresholdImage: RainbowImage private lateinit var paint: Paint override fun onSketchSetup() { with(rainbowDrawer) { background(255) smooth() loadImage(com.juankysoriano.rainbow.demo.R.drawable.winnie, width, height, Modes.LoadMode.LOAD_CENTER_CROP, object : RainbowImage.LoadPictureListener { override fun onLoadSucceed(image: RainbowImage) { originalImage = image originalImage.loadPixels() thresholdImage = rainbowDrawer.createImage(width, height, Modes.Image.RGB) thresholdImage.set(0, 0, originalImage) thresholdImage.filter(Modes.Filter.THRESHOLD, 0.6f) paint = Paint(rainbowDrawer, originalImage, thresholdImage) paint.reset() } override fun onLoadFail() { //no-op } }) } } override fun onDrawingStep() { if (!::paint.isInitialized || stepCount() > width) { return } for (i in 0..STEPS) { paint.updateAndDisplay() } } class Paint(private val rainbowDrawer: RainbowDrawer, private val originalImage: RainbowImage, private val thresholdImage: RainbowImage) { var ppos = RVector() var pos = RVector() var vel = RVector() var force = RVector() var maxSpeed = 3f var perception = 5f var bound = 60 var boundForceFactor = 0.16f var noiseScale = 100f var noiseInfluence = 1 / 20f var dropRate = 0.0001f var dropRange = 40 var dropAlpha = 150f var drawAlpha = 60f var drawColor = rainbowDrawer.color(0f, 0f, 0f, drawAlpha) var count = 0 var maxCount = 100 var z = 0f fun updateAndDisplay() { update() show() z += 0.01f } fun update() { ppos = pos.copy() force.mult(0f) // Add pixels force val target = RVector() var count = 0 for (i in -floor(perception / 2f).toInt()..(perception / 2f).toInt()) { for (j in -floor(perception / 2f).toInt()..(perception / 2f).toInt()) { if (i == 0 && j == 0) { continue } val x = floor(pos.x + i) val y = floor(pos.y + j) if (x <= rainbowDrawer.width - 1 && x >= 0 && y < rainbowDrawer.height - 1 && y >= 0) { val c = get(x.toInt(), y.toInt()) var b = rainbowDrawer.brightness(c) b = 1 - b / 100f val p = RVector(i.toFloat(), j.toFloat()) p.normalize() val pCopy = p.copy() pCopy.mult(b) pCopy.div(p.mag()) target.add(pCopy) count++ } } } if (count != 0) { target.div(count.toFloat()) force.add(target) } var n = noise(pos.x / noiseScale, pos.y / noiseScale, z) n = map(n, 0f, 1f, 0f, 5f * TWO_PI) val p = RVector(cos(n), sin(n)) if (force.mag() < 0.01f) { p.mult(noiseInfluence * 5) } else { p.mult(noiseInfluence) } force.add(p) // Add bound force val boundForce = RVector() if (pos.x < bound) { boundForce.x = (bound - pos.x) / bound } if (pos.x > rainbowDrawer.width - bound) { boundForce.x = (pos.x - rainbowDrawer.width) / bound } if (pos.y < bound) { boundForce.y = (bound - pos.y) / bound } if (pos.y > rainbowDrawer.height - bound) { boundForce.y = (pos.y - rainbowDrawer.height) / bound } boundForce.mult(boundForceFactor) force.add(boundForce) vel.add(force) vel.mult(0.9999f) if (vel.mag() > maxSpeed) { vel.mult(maxSpeed / vel.mag()) } pos.add(vel) if (pos.x > rainbowDrawer.width || pos.x < 0 || pos.y > rainbowDrawer.height || pos.y < 0) { this.reset() } } fun reset() { count = 0 var hasFound = false while (!hasFound) { pos.x = random(rainbowDrawer.width).toFloat() pos.y = random(rainbowDrawer.height).toFloat() val c = get(floor(pos.x).toInt(), floor(pos.y).toInt()) val b = rainbowDrawer.brightness(c) if (b < 70) hasFound = true } val index = floor(pos.x).toInt() + rainbowDrawer.width * floor(pos.y).toInt() drawColor = originalImage.pixels[index] drawColor = rainbowDrawer.color(rainbowDrawer.brightness(drawColor), drawAlpha) ppos = pos.copy() vel.mult(0f) } fun show() { count++ if (count > maxCount) { this.reset() } rainbowDrawer.stroke(drawColor) val brightness = rainbowDrawer.brightness(drawColor) var drawWeight = 0.5f if (brightness < 35) { drawWeight = 1.5f } rainbowDrawer.strokeWeight(drawWeight) if (force.mag() > 0.1f && random(1f) < dropRate) { drawColor = rainbowDrawer.color(brightness, dropAlpha) rainbowDrawer.stroke(drawColor) val boldWeight = 0f + random(3f, 12f) rainbowDrawer.strokeWeight(boldWeight) drawColor = rainbowDrawer.color(brightness, drawAlpha) } rainbowDrawer.line(ppos.x, ppos.y, pos.x, pos.y) this.fadeLineFromImg(ppos.x, ppos.y, pos.x, pos.y) } private fun fadeLineFromImg(x1: Float, y1: Float, x2: Float, y2: Float) { val xOffset = floor(abs(x1 - x2)) val yOffset = floor(abs(y1 - y2)) val step = if (xOffset < yOffset) { yOffset } else { xOffset } for (i in 0..step.toInt()) { val x = floor(x1 + (x2 - x1) * i / step) val y = floor(y1 + (y2 - y1) * i / step) var originColor = get(x.toInt(), y.toInt()) val r = min(255, red(originColor) + 50) val g = min(255, green(originColor) + 50) val b = min(255, blue(originColor) + 50) originColor = rainbowDrawer.color(r, g, b, rainbowDrawer.brightness(originColor).toInt()) set(x.toInt(), y.toInt(), originColor) } } private fun get(x: Int, y: Int): Int { val index = (y * rainbowDrawer.width + x) return thresholdImage.pixels[index] } private fun set(x: Int, y: Int, color: Int) { val index = (y * rainbowDrawer.width + x) thresholdImage.pixels[index] = color } private fun RVector.copy(): RVector { return RVector(x, y) } } }
lgpl-3.0
c102a2b9817779f600f457209f457518
33.829876
142
0.48761
4.47203
false
false
false
false
faceofcat/Tesla-Powered-Thingies
src/main/kotlin/net/ndrei/teslapoweredthingies/machines/portablemultitank/MultiTankEntity.kt
1
2458
package net.ndrei.teslapoweredthingies.machines.portablemultitank import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer import net.minecraft.item.EnumDyeColor import net.minecraft.nbt.NBTTagCompound import net.minecraft.tileentity.TileEntity import net.minecraft.world.World import net.minecraftforge.fluids.FluidStack import net.minecraftforge.fluids.IFluidTank import net.ndrei.teslacorelib.gui.FluidTankPiece import net.ndrei.teslacorelib.tileentities.SidedTileEntity import net.ndrei.teslapoweredthingies.render.bakery.SelfRenderingTESR /** * Created by CF on 2017-07-16. */ class MultiTankEntity : SidedTileEntity(MultiTankEntity::class.java.name.hashCode()) { private lateinit var tanks: MutableList<IFluidTank> override fun initializeInventories() { super.initializeInventories() this.tanks = mutableListOf() arrayOf(EnumDyeColor.BLUE, EnumDyeColor.GREEN, EnumDyeColor.ORANGE, EnumDyeColor.RED).forEachIndexed { index, it -> this.tanks.add(this.addSimpleFluidTank(TANK_CAPACITY, "Tank $index", it, 20 + FluidTankPiece.WIDTH * index, 24)) } } override fun supportsAddons() = false override fun canBePaused() = false override val allowRedstoneControl: Boolean get() = false override fun setWorld(worldIn: World?) { super.setWorld(worldIn) this.getWorld().markBlockRangeForRenderUpdate(this.getPos(), this.getPos()) } override fun getRenderers(): MutableList<TileEntitySpecialRenderer<TileEntity>> { return super.getRenderers().also { it.add(SelfRenderingTESR) } } fun getFluid(tankIndex: Int): FluidStack? = this.tanks[tankIndex].fluid override fun readFromNBT(compound: NBTTagCompound) { val initialFluids = this.tanks.map { it.fluid } super.readFromNBT(compound) val finalFluids = this.tanks.map { it.fluid } if (this.hasWorld () && this.getWorld().isRemote && (0..3).any { if (initialFluids[it] == null) (finalFluids[it] != null) else !initialFluids[it]!!.isFluidStackIdentical(finalFluids[it]) }) { this.getWorld().markBlockRangeForRenderUpdate(this.pos, this.pos) } } override fun innerUpdate() { // TODO: maybe blow up if the liquid is too hot or something? :S } companion object { const val TANK_CAPACITY = 6000 } }
mit
30ecf741a72c70cf8ec8a7c2c2fb18f0
34.128571
123
0.696094
4.46098
false
false
false
false
android/android-studio-poet
aspoet/src/main/kotlin/com/google/androidstudiopoet/generators/ModuleBuildBazelGenerator.kt
1
1603
/* 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 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.androidstudiopoet.generators import com.google.androidstudiopoet.models.ModuleBuildBazelBlueprint import com.google.androidstudiopoet.models.ModuleDependency import com.google.androidstudiopoet.writers.FileWriter class ModuleBuildBazelGenerator(private val fileWriter: FileWriter) { fun generate(blueprint: ModuleBuildBazelBlueprint) { val deps: Set<String> = blueprint.dependencies.map { when (it) { is ModuleDependency -> "\"//${it.name}\"" else -> "" } }.toSet() val depsString = """ deps = [ ${deps.joinToString(separator = ",\n ") { it }} ],""" val ruleClass = "java_library" val targetName = blueprint.targetName val ruleDefinition = """$ruleClass( name = "$targetName", srcs = glob(["src/main/java/**/*.java"]), visibility = ["//visibility:public"],${if (deps.isNotEmpty()) depsString else ""} )""" fileWriter.writeToFile(ruleDefinition, blueprint.path) } }
apache-2.0
9f6e7996ceaf2c1f69d3f9d5a63f33f4
34.622222
85
0.68559
4.541076
false
false
false
false
cy6erGn0m/RxKotlin
src/examples/kotlin/rx/lang/kotlin/examples/examples.kt
1
3008
package rx.lang.kotlin.examples import rx.Observable import rx.lang.kotlin.observable import rx.lang.kotlin.onError import rx.lang.kotlin.plusAssign import rx.lang.kotlin.toObservable import rx.lang.kotlin.zip import rx.lang.kotlin.combineLatest import rx.subscriptions.CompositeSubscription import java.net.URL import java.util.* import kotlin.concurrent.thread fun main(args: Array<String>) { val subscrition = CompositeSubscription() val printArticle = { art: String -> println("--- Article ---\n${art.substring(0, 125)}") } val printIt = { it: String -> println(it) } subscrition += asyncObservable().subscribe(printIt) subscrition += syncObservable().subscribe(printIt) subscrition.clear() simpleComposition() asyncWiki("Tiger", "Elephant").subscribe(printArticle) asyncWikiWithErrorHandling("Tiger", "Elephant").subscribe(printArticle) { e -> println("--- Error ---\n${e.message}") } combineLatest(listOfObservables()) zip(listOfObservables()) } private fun URL.toScannerObservable() = observable<String> { s -> this.openStream().use { stream -> Scanner(stream).useDelimiter("\\A").toObservable().subscribe(s) } } public fun syncObservable(): Observable<String> = observable { subscriber -> (0..75).toObservable() .map { "Sync value_$it" } .subscribe(subscriber) } public fun asyncObservable(): Observable<String> = observable { subscriber -> thread { (0..75).toObservable() .map { "Async value_$it" } .subscribe(subscriber) } } public fun asyncWiki(vararg articleNames: String): Observable<String> = observable { subscriber -> thread { articleNames.toObservable() .flatMap { name -> URL("http://en.wikipedia.org/wiki/$name").toScannerObservable().first() } .subscribe(subscriber) } } public fun asyncWikiWithErrorHandling(vararg articleNames: String): Observable<String> = observable { subscriber -> thread { articleNames.toObservable() .flatMap { name -> URL("http://en.wikipedia.org/wiki/$name").toScannerObservable().first() } .onError { e -> subscriber.onError(e) } .subscribe(subscriber) } } public fun simpleComposition() { asyncObservable().skip(10).take(5) .map { s -> "${s}_xform" } .subscribe { s -> println("onNext => $s") } } public fun listOfObservables(): List<Observable<String>> = listOf(syncObservable(), syncObservable()) public fun combineLatest(observables: List<Observable<String>>) { observables.combineLatest { it.reduce { one, two -> one + two } }.subscribe { println(it) } } public fun zip(observables: List<Observable<String>>) { observables.zip { it.reduce { one, two -> one + two } }.subscribe { println(it) } }
apache-2.0
3b45fbac4d1e733f3e04bc9bcbb1d9eb
29.09
112
0.625332
4.260623
false
false
false
false
rmaz/buck
test/com/facebook/buck/jvm/kotlin/testdata/kotlin_library_description/com/example/ap/kotlinap/AnnotationProcessorKotlin.kt
3
1648
package com.example.ap.kotlinap import com.google.auto.service.AutoService import java.io.File import java.io.OutputStreamWriter import java.nio.charset.StandardCharsets import java.nio.file.Files import javax.annotation.processing.* import javax.lang.model.SourceVersion import javax.lang.model.element.TypeElement import com.example.ap.kotlinannotation.KotlinAnnotation import com.squareup.kotlinpoet.FileSpec import com.squareup.kotlinpoet.TypeSpec @AutoService(Processor::class) class AnnotationProcessorKotlin : AbstractProcessor() { override fun getSupportedAnnotationTypes(): MutableSet<String> { return mutableSetOf(KotlinAnnotation::class.java.name) } override fun getSupportedSourceVersion(): SourceVersion { return SourceVersion.latest() } override fun process(annotations: MutableSet<out TypeElement>, roundEnv: RoundEnvironment): Boolean { roundEnv.getElementsAnnotatedWith(KotlinAnnotation::class.java) .forEach { val className = it.simpleName.toString() val pkg = processingEnv.elementUtils.getPackageOf(it).toString() generateClass(className, pkg) } return true } private fun generateClass(name: String, pkg: String) { val genDir = processingEnv.options["kapt.kotlin.generated"] val fileName = "${name}_" val file = FileSpec .builder(pkg, fileName) .addType(TypeSpec .classBuilder(fileName) .build() ).build() file.writeTo(File(genDir)) } }
apache-2.0
dc8f0af8a4a26c30191c53ba0c7a5051
33.333333
105
0.672937
5.070769
false
false
false
false
GeoffreyMetais/vlc-android
application/television/src/main/java/org/videolan/television/ui/MediaItemDetailsFragment.kt
1
21643
/***************************************************************************** * MediaItemDetailsFragment.java * * Copyright © 2014-2019 VLC authors, VideoLAN and VideoLabs * Author: Geoffrey Métais * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. */ package org.videolan.television.ui import android.annotation.TargetApi import android.content.Intent import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Parcelable import android.text.TextUtils import android.widget.Toast import androidx.core.content.ContextCompat import androidx.fragment.app.activityViewModels import androidx.leanback.app.BackgroundManager import androidx.leanback.app.DetailsSupportFragment import androidx.leanback.widget.* import androidx.lifecycle.Observer import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProviders import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.* import org.videolan.libvlc.util.AndroidUtil import org.videolan.medialibrary.MLServiceLocator import org.videolan.medialibrary.interfaces.media.MediaWrapper import org.videolan.moviepedia.database.models.MediaImage import org.videolan.moviepedia.database.models.MediaImageType import org.videolan.moviepedia.database.models.MediaMetadata import org.videolan.moviepedia.database.models.Person import org.videolan.moviepedia.repository.MediaMetadataRepository import org.videolan.moviepedia.repository.MediaPersonRepository import org.videolan.moviepedia.viewmodel.MediaMetadataFull import org.videolan.moviepedia.viewmodel.MediaMetadataModel import org.videolan.resources.ACTION_REMOTE_STOP import org.videolan.tools.HttpImageLoader import org.videolan.vlc.BuildConfig import org.videolan.vlc.R import org.videolan.vlc.gui.helpers.AudioUtil import org.videolan.vlc.gui.helpers.UiTools import org.videolan.vlc.gui.video.VideoPlayerActivity import org.videolan.vlc.media.MediaUtils import org.videolan.vlc.repository.BrowserFavRepository import org.videolan.vlc.util.FileUtils import org.videolan.vlc.util.getScreenWidth import org.videolan.vlc.gui.helpers.UiTools.addToPlaylist private const val TAG = "MediaItemDetailsFragment" private const val ID_PLAY = 1 private const val ID_NEXT_EPISODE = 2 private const val ID_LISTEN = 3 private const val ID_FAVORITE_ADD = 4 private const val ID_FAVORITE_DELETE = 5 private const val ID_BROWSE = 6 private const val ID_DL_SUBS = 7 private const val ID_PLAY_FROM_START = 8 private const val ID_PLAYLIST = 9 private const val ID_GET_INFO = 10 private const val ID_FAVORITE = 11 @ExperimentalCoroutinesApi @ObsoleteCoroutinesApi @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) class MediaItemDetailsFragment : DetailsSupportFragment(), CoroutineScope by MainScope(), OnItemViewClickedListener { private lateinit var detailsDescriptionPresenter: DetailsDescriptionPresenter private lateinit var backgroundManager: BackgroundManager private lateinit var rowsAdapter: ArrayObjectAdapter private lateinit var browserFavRepository: BrowserFavRepository private lateinit var mediaMetadataRepository: MediaMetadataRepository private lateinit var mediaPersonRepository: MediaPersonRepository private lateinit var mediaMetadataModel: MediaMetadataModel private lateinit var detailsOverview: DetailsOverviewRow private lateinit var arrayObjectAdapterPosters: ArrayObjectAdapter private var mediaStarted: Boolean = false private val viewModel: MediaItemDetailsModel by activityViewModels() private val actionsAdapter = SparseArrayObjectAdapter() private val imageDiffCallback = object : DiffCallback<MediaImage>() { override fun areItemsTheSame(oldItem: MediaImage, newItem: MediaImage) = oldItem.url == newItem.url override fun areContentsTheSame(oldItem: MediaImage, newItem: MediaImage) = oldItem.url == newItem.url } private val personsDiffCallback = object : DiffCallback<Person>() { override fun areItemsTheSame(oldItem: Person, newItem: Person) = oldItem.moviepediaId == newItem.moviepediaId override fun areContentsTheSame(oldItem: Person, newItem: Person) = oldItem.moviepediaId == newItem.moviepediaId && oldItem.image == newItem.image && oldItem.name == newItem.name } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) backgroundManager = BackgroundManager.getInstance(requireActivity()) backgroundManager.isAutoReleaseOnStop = false browserFavRepository = BrowserFavRepository.getInstance(requireContext()) viewModel.mediaStarted = false detailsDescriptionPresenter = org.videolan.television.ui.DetailsDescriptionPresenter() arrayObjectAdapterPosters = ArrayObjectAdapter(org.videolan.television.ui.MediaImageCardPresenter(requireActivity(), MediaImageType.POSTER)) val extras = requireActivity().intent.extras ?: savedInstanceState ?: return viewModel.mediaItemDetails = extras.getParcelable("item") ?: return val hasMedia = extras.containsKey("media") val media = (extras.getParcelable<Parcelable>("media") ?: MLServiceLocator.getAbstractMediaWrapper(AndroidUtil.LocationToUri(viewModel.mediaItemDetails.location))) as MediaWrapper viewModel.media = media if (!hasMedia) viewModel.media.setDisplayTitle(viewModel.mediaItemDetails.title) title = viewModel.media.title mediaMetadataRepository = MediaMetadataRepository.getInstance(requireContext()) mediaPersonRepository = MediaPersonRepository.getInstance(requireContext()) mediaStarted = false buildDetails() mediaMetadataModel = ViewModelProviders.of(this, MediaMetadataModel.Factory(requireActivity(), mlId = media.id)).get(media.uri.path ?: "", MediaMetadataModel::class.java) mediaMetadataModel.updateLiveData.observe(this, Observer { updateMetadata(it) }) mediaMetadataModel.nextEpisode.observe(this, Observer { if (it != null) { actionsAdapter.set(ID_NEXT_EPISODE, Action(ID_NEXT_EPISODE.toLong(), getString(R.string.next_episode))) actionsAdapter.notifyArrayItemRangeChanged(0, actionsAdapter.size()) } }) onItemViewClickedListener = this } override fun onResume() { super.onResume() // buildDetails() if (!backgroundManager.isAttached) backgroundManager.attachToView(view) } override fun onPause() { backgroundManager.release() super.onPause() if (viewModel.mediaStarted) { context?.sendBroadcast(Intent(ACTION_REMOTE_STOP)) } } override fun onSaveInstanceState(outState: Bundle) { outState.putParcelable("item", viewModel.mediaItemDetails) outState.putParcelable("media", viewModel.media) super.onSaveInstanceState(outState) } override fun onItemClicked(itemViewHolder: Presenter.ViewHolder?, item: Any?, rowViewHolder: RowPresenter.ViewHolder?, row: Row?) { when (item) { is MediaImage -> { mediaMetadataModel.updateMetadataImage(item) } } } private fun loadBackdrop(url: String? = null) { lifecycleScope.launchWhenStarted { when { !url.isNullOrEmpty() -> HttpImageLoader.downloadBitmap(url) viewModel.media.type == MediaWrapper.TYPE_AUDIO || viewModel.media.type == MediaWrapper.TYPE_VIDEO -> { withContext(Dispatchers.IO) { AudioUtil.readCoverBitmap(viewModel.mediaItemDetails.artworkUrl, 512)?.let { UiTools.blurBitmap(it) } } } else -> null }?.let { backgroundManager.setBitmap(it) } } } private fun updateMetadata(mediaMetadataFull: MediaMetadataFull?) { var backdropLoaded = false mediaMetadataFull?.let { mediaMetadata -> detailsDescriptionPresenter.metadata = mediaMetadata.metadata mediaMetadata.metadata?.metadata?.let { loadBackdrop(it.currentBackdrop) backdropLoaded = true } lifecycleScope.launchWhenStarted { if (!mediaMetadata.metadata?.metadata?.currentPoster.isNullOrEmpty()) { detailsOverview.setImageBitmap(requireActivity(), HttpImageLoader.downloadBitmap(mediaMetadata.metadata?.metadata?.currentPoster!!)) } } title = mediaMetadata.metadata?.metadata?.title val items = ArrayList<Any>() items.add(detailsOverview) if (!mediaMetadata.writers.isNullOrEmpty()) { val arrayObjectAdapterWriters = ArrayObjectAdapter(PersonCardPresenter(requireActivity())) arrayObjectAdapterWriters.setItems(mediaMetadata.writers, personsDiffCallback) val headerWriters = HeaderItem(mediaMetadata.metadata?.metadata?.moviepediaId?.toLong(36) ?: 0, getString(R.string.written_by)) items.add(ListRow(headerWriters, arrayObjectAdapterWriters)) } if (!mediaMetadata.actors.isNullOrEmpty()) { val arrayObjectAdapterActors = ArrayObjectAdapter(PersonCardPresenter(requireActivity())) arrayObjectAdapterActors.setItems(mediaMetadata.actors, personsDiffCallback) val headerActors = HeaderItem(mediaMetadata.metadata?.metadata?.moviepediaId?.toLong(36) ?: 0, getString(R.string.casting)) items.add(ListRow(headerActors, arrayObjectAdapterActors)) } if (!mediaMetadata.directors.isNullOrEmpty()) { val arrayObjectAdapterDirectors = ArrayObjectAdapter(PersonCardPresenter(requireActivity())) arrayObjectAdapterDirectors.setItems(mediaMetadata.directors, personsDiffCallback) val headerDirectors = HeaderItem(mediaMetadata.metadata?.metadata?.moviepediaId?.toLong(36) ?: 0, getString(R.string.directed_by)) items.add(ListRow(headerDirectors, arrayObjectAdapterDirectors)) } if (!mediaMetadata.producers.isNullOrEmpty()) { val arrayObjectAdapterProducers = ArrayObjectAdapter(PersonCardPresenter(requireActivity())) arrayObjectAdapterProducers.setItems(mediaMetadata.producers, personsDiffCallback) val headerProducers = HeaderItem(mediaMetadata.metadata?.metadata?.moviepediaId?.toLong(36) ?: 0, getString(R.string.produced_by)) items.add(ListRow(headerProducers, arrayObjectAdapterProducers)) } if (!mediaMetadata.musicians.isNullOrEmpty()) { val arrayObjectAdapterMusicians = ArrayObjectAdapter(PersonCardPresenter(requireActivity())) arrayObjectAdapterMusicians.setItems(mediaMetadata.musicians, personsDiffCallback) val headerMusicians = HeaderItem(mediaMetadata.metadata?.metadata?.moviepediaId?.toLong(36) ?: 0, getString(R.string.music_by)) items.add(ListRow(headerMusicians, arrayObjectAdapterMusicians)) } mediaMetadata.metadata?.let { metadata -> if (metadata.images.any { it.imageType == MediaImageType.POSTER }) { arrayObjectAdapterPosters.setItems(metadata.images.filter { it.imageType == MediaImageType.POSTER }, imageDiffCallback) val headerPosters = HeaderItem(mediaMetadata.metadata?.metadata?.moviepediaId?.toLong(36) ?: 0, getString(R.string.posters)) items.add(ListRow(headerPosters, arrayObjectAdapterPosters)) } if (metadata.images.any { it.imageType == MediaImageType.BACKDROP }) { val arrayObjectAdapterBackdrops = ArrayObjectAdapter(org.videolan.television.ui.MediaImageCardPresenter(requireActivity(), MediaImageType.BACKDROP)) arrayObjectAdapterBackdrops.setItems(metadata.images.filter { it.imageType == MediaImageType.BACKDROP }, imageDiffCallback) val headerBackdrops = HeaderItem(mediaMetadata.metadata?.metadata?.moviepediaId?.toLong(36) ?: 0, getString(R.string.backdrops)) items.add(ListRow(headerBackdrops, arrayObjectAdapterBackdrops)) } } rowsAdapter.setItems(items, object : DiffCallback<Row>() { override fun areItemsTheSame(oldItem: Row, newItem: Row) = (oldItem is DetailsOverviewRow && newItem is DetailsOverviewRow && (oldItem.item == newItem.item)) || (oldItem is ListRow && newItem is ListRow && oldItem.contentDescription == newItem.contentDescription && oldItem.adapter.size() == newItem.adapter.size() && oldItem.id == newItem.id) override fun areContentsTheSame(oldItem: Row, newItem: Row): Boolean { if (oldItem is DetailsOverviewRow && newItem is DetailsOverviewRow) { return oldItem.item as org.videolan.television.ui.MediaItemDetails == newItem.item as org.videolan.television.ui.MediaItemDetails } return true } }) rowsAdapter.notifyItemRangeChanged(0, 1) } if (!backdropLoaded) loadBackdrop() } private fun buildDetails() { val selector = ClassPresenterSelector() // Attach your media item details presenter to the row presenter: val rowPresenter = FullWidthDetailsOverviewRowPresenter(detailsDescriptionPresenter) val videoPresenter = VideoDetailsPresenter(requireActivity(), requireActivity().getScreenWidth()) val activity = requireActivity() detailsOverview = DetailsOverviewRow(viewModel.mediaItemDetails) val actionAdd = Action(ID_FAVORITE_ADD.toLong(), getString(R.string.favorites_add)) val actionDelete = Action(ID_FAVORITE_DELETE.toLong(), getString(R.string.favorites_remove)) rowPresenter.backgroundColor = ContextCompat.getColor(activity, R.color.orange500) rowPresenter.onActionClickedListener = OnActionClickedListener { action -> when (action.id.toInt()) { ID_LISTEN -> { MediaUtils.openMedia(activity, viewModel.media) viewModel.mediaStarted = true } ID_PLAY -> { viewModel.mediaStarted = false TvUtil.playMedia(activity, viewModel.media) activity.finish() } ID_PLAYLIST -> requireActivity().addToPlaylist(arrayListOf(viewModel.media)) ID_FAVORITE_ADD -> { val uri = Uri.parse(viewModel.mediaItemDetails.location) val local = "file" == uri.scheme lifecycleScope.launch { if (local) browserFavRepository.addLocalFavItem(uri, viewModel.mediaItemDetails.title ?: "", viewModel.mediaItemDetails.artworkUrl) else browserFavRepository.addNetworkFavItem(uri, viewModel.mediaItemDetails.title ?: "", viewModel.mediaItemDetails.artworkUrl) } actionsAdapter.set(ID_FAVORITE, actionDelete) rowsAdapter.notifyArrayItemRangeChanged(0, rowsAdapter.size()) Toast.makeText(activity, R.string.favorite_added, Toast.LENGTH_SHORT).show() } ID_FAVORITE_DELETE -> { lifecycleScope.launch { browserFavRepository.deleteBrowserFav(Uri.parse(viewModel.mediaItemDetails.location)) } actionsAdapter.set(ID_FAVORITE, actionAdd) rowsAdapter.notifyArrayItemRangeChanged(0, rowsAdapter.size()) Toast.makeText(activity, R.string.favorite_removed, Toast.LENGTH_SHORT).show() } ID_BROWSE -> TvUtil.openMedia(activity, viewModel.media, null) ID_DL_SUBS -> MediaUtils.getSubs(requireActivity(), viewModel.media) ID_PLAY_FROM_START -> { viewModel.mediaStarted = false VideoPlayerActivity.start(requireActivity(), viewModel.media.uri, true) activity.finish() } ID_GET_INFO -> startActivity(Intent(requireActivity(), MediaScrapingTvActivity::class.java).apply { putExtra(MediaScrapingTvActivity.MEDIA, viewModel.media) }) ID_NEXT_EPISODE -> mediaMetadataModel.nextEpisode.value?.media?.let { TvUtil.showMediaDetail(requireActivity(), it) requireActivity().finish() } } } selector.addClassPresenter(DetailsOverviewRow::class.java, rowPresenter) selector.addClassPresenter(VideoDetailsOverviewRow::class.java, videoPresenter) selector.addClassPresenter(ListRow::class.java, ListRowPresenter()) rowsAdapter = ArrayObjectAdapter(selector) lifecycleScope.launchWhenStarted { val cover = if (viewModel.media.type == MediaWrapper.TYPE_AUDIO || viewModel.media.type == MediaWrapper.TYPE_VIDEO) withContext(Dispatchers.IO) { AudioUtil.readCoverBitmap(viewModel.mediaItemDetails.artworkUrl, 512) } else null val browserFavExists = browserFavRepository.browserFavExists(Uri.parse(viewModel.mediaItemDetails.location)) val isDir = viewModel.media.type == MediaWrapper.TYPE_DIR val canSave = isDir && withContext(Dispatchers.IO) { FileUtils.canSave(viewModel.media) } if (activity.isFinishing) return@launchWhenStarted val res = resources if (isDir) { detailsOverview.imageDrawable = ContextCompat.getDrawable(activity, if (TextUtils.equals(viewModel.media.uri.scheme, "file")) R.drawable.ic_menu_folder_big else R.drawable.ic_menu_network_big) detailsOverview.isImageScaleUpAllowed = true actionsAdapter.set(ID_BROWSE, Action(ID_BROWSE.toLong(), res.getString(R.string.browse_folder))) if (canSave) actionsAdapter.set(ID_FAVORITE, if (browserFavExists) actionDelete else actionAdd) } else if (viewModel.media.type == MediaWrapper.TYPE_AUDIO) { // Add images and action buttons to the details view if (cover == null) { detailsOverview.imageDrawable = ContextCompat.getDrawable(activity, R.drawable.ic_default_cone) } else { detailsOverview.setImageBitmap(context, cover) } actionsAdapter.set(ID_PLAY, Action(ID_PLAY.toLong(), res.getString(R.string.play))) actionsAdapter.set(ID_LISTEN, Action(ID_LISTEN.toLong(), res.getString(R.string.listen))) actionsAdapter.set(ID_PLAYLIST, Action(ID_PLAYLIST.toLong(), res.getString(R.string.add_to_playlist))) } else if (viewModel.media.type == MediaWrapper.TYPE_VIDEO) { // Add images and action buttons to the details view if (cover == null) { detailsOverview.imageDrawable = ContextCompat.getDrawable(activity, R.drawable.ic_default_cone) } else { detailsOverview.setImageBitmap(context, cover) } actionsAdapter.set(ID_PLAY, Action(ID_PLAY.toLong(), res.getString(R.string.play))) actionsAdapter.set(ID_PLAY_FROM_START, Action(ID_PLAY_FROM_START.toLong(), res.getString(R.string.play_from_start))) if (FileUtils.canWrite(viewModel.media.uri)) actionsAdapter.set(ID_DL_SUBS, Action(ID_DL_SUBS.toLong(), res.getString(R.string.download_subtitles))) actionsAdapter.set(ID_PLAYLIST, Action(ID_PLAYLIST.toLong(), res.getString(R.string.add_to_playlist))) //todo reenable entry point when ready if (BuildConfig.DEBUG) actionsAdapter.set(ID_GET_INFO, Action(ID_GET_INFO.toLong(), res.getString(R.string.find_metadata))) } adapter = rowsAdapter detailsOverview.actionsAdapter = actionsAdapter // updateMetadata(mediaMetadataModel.updateLiveData.value) } } } class MediaItemDetailsModel : ViewModel() { lateinit var mediaItemDetails: org.videolan.television.ui.MediaItemDetails lateinit var media: MediaWrapper var mediaStarted = false } class VideoDetailsOverviewRow(val item: MediaMetadata) : DetailsOverviewRow(item)
gpl-2.0
b43ec737ffcb5b5123a747d414f297a2
53.238095
359
0.673259
5.406195
false
false
false
false
dafi/photoshelf
tumblr-ui-core/src/main/java/com/ternaryop/photoshelf/tumblr/ui/core/adapter/photo/PhotoGroup.kt
1
1496
package com.ternaryop.photoshelf.tumblr.ui.core.adapter.photo import android.util.Range import com.ternaryop.photoshelf.tumblr.ui.core.adapter.PhotoShelfPost /** * Created by dave on 10/03/18. * Helper util to group photos by id */ object PhotoGroup { fun calcGroupIds(items: List<PhotoShelfPost>) { if (items.isEmpty()) { return } val count = items.size var groupId = 0 var last = items[0].firstTag items[0].groupId = groupId var i = 1 while (i < count) { // set same groupId for all identical tags while (i < count && items[i].firstTag.equals(last, ignoreCase = true)) { items[i++].groupId = groupId } if (i < count) { ++groupId items[i].groupId = groupId last = items[i].firstTag } i++ } } fun getRangeFromPosition(items: List<PhotoShelfPost>, position: Int, groupId: Int): Range<Int>? { if (position < 0) { return null } var min = position var max = position while (min > 0 && items[min - 1].groupId == groupId) { --min } val lastIndex = items.size - 1 while (max < lastIndex && items[max].groupId == groupId) { ++max } // group is empty return if (min == max) { null } else Range.create(min, max) } }
mit
65fd28d1981bb22c08f35c82cd686abf
25.714286
101
0.516711
4.23796
false
false
false
false
daugeldauge/NeePlayer
app/src/main/java/com/neeplayer/ui/now_playing/MusicService.kt
1
11023
package com.neeplayer.ui.now_playing import android.annotation.SuppressLint import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.* import android.graphics.Bitmap import android.media.AudioManager import android.os.Handler import android.os.IBinder import android.os.Looper import android.provider.MediaStore import android.support.v4.media.MediaMetadataCompat import android.support.v4.media.session.MediaSessionCompat import android.support.v4.media.session.PlaybackStateCompat import androidx.annotation.DrawableRes import androidx.core.app.NotificationCompat import androidx.media.app.NotificationCompat.MediaStyle import com.google.android.exoplayer2.C import com.google.android.exoplayer2.ExoPlaybackException import com.google.android.exoplayer2.Player import com.google.android.exoplayer2.SimpleExoPlayer import com.google.android.exoplayer2.audio.AudioAttributes import com.google.android.exoplayer2.ext.mediasession.MediaSessionConnector import com.google.android.exoplayer2.source.ProgressiveMediaSource import com.google.android.exoplayer2.upstream.ContentDataSource import com.google.android.exoplayer2.util.Log import com.google.android.exoplayer2.util.Log.LOG_LEVEL_ALL import com.bumptech.glide.Glide import com.google.android.exoplayer2.DefaultRenderersFactory import com.google.android.exoplayer2.DefaultRenderersFactory.EXTENSION_RENDERER_MODE_ON import com.google.android.exoplayer2.MediaItem import com.neeplayer.BuildConfig import com.neeplayer.R import com.neeplayer.model.Song import com.neeplayer.toast import com.neeplayer.ui.MainActivity import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.MainScope import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.koin.android.ext.android.inject class MusicService : Service(), NowPlayingView { private val handler = Handler(Looper.getMainLooper()) private val mainScope = MainScope() private val presenter by inject<NowPlayingPresenter>() private val mediaSourceFactory = ProgressiveMediaSource.Factory { ContentDataSource(this) } private val mediaSession by lazy { MediaSessionCompat( this, BuildConfig.APPLICATION_ID, ComponentName(this, MediaButtonEventsReceiver::class.java), PendingIntent.getBroadcast(this, 0, Intent(Intent.ACTION_MEDIA_BUTTON), PENDING_INTENT_FLAG_MUTABLE) ) } private var wasForeground = false private val player by lazy { SimpleExoPlayer.Builder( applicationContext, DefaultRenderersFactory(applicationContext).setExtensionRendererMode(EXTENSION_RENDERER_MODE_ON), ).build().apply { val audioAttributes = AudioAttributes.Builder() .setUsage(C.USAGE_MEDIA) .setContentType(C.CONTENT_TYPE_MUSIC) .build() setAudioAttributes(audioAttributes, /*handleAudioFocus=*/ true) addListener(object : Player.Listener { override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) { if (playbackState == Player.STATE_ENDED) { stopTicking() presenter.onNextClicked() } } override fun onPlayerError(error: ExoPlaybackException) { stopTicking() applicationContext.toast(R.string.media_player_error) } }) Log.setLogLevel(LOG_LEVEL_ALL) } } private var currentSong: Song? = null set(value) { if (value != field && value != null) { val songUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, value.id) player.setMediaSource(mediaSourceFactory.createMediaSource(MediaItem.fromUri(songUri))) player.prepare() field = value } } override fun onCreate() { super.onCreate() presenter.bind(mainScope, this) MediaSessionConnector(mediaSession).apply { setPlayer(player) } mediaSession.setCallback(mediaSessionCallback) mediaSession.isActive = true registerReceiver(headsetPlugReceiver, IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY)) } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { when (intent?.action) { PLAY_PREVIOUS_ACTION -> presenter.onPreviousClicked() PLAY_OR_PAUSE_ACTION -> presenter.onPlayPauseClicked() PLAY_NEXT_ACTION -> presenter.onNextClicked() } return super.onStartCommand(intent, flags, startId) } override fun onBind(intent: Intent?): IBinder? = null override fun render(song: Song, paused: Boolean) { currentSong = song player.playWhenReady = !paused if (paused) { stopTicking() } else { tick() } mainScope.launch { withContext(Dispatchers.IO) { updateInfo(song, paused) } } } override fun seek(progress: Int) { player.seekTo(progress.toLong()) } //endregion //endregion override fun onDestroy() { stopTicking() player.stop() player.release() mediaSession.release() unregisterReceiver(headsetPlugReceiver) wasForeground = false stopForeground(true) mainScope.cancel() presenter.onDestroy() } override fun onTaskRemoved(rootIntent: Intent?) { stopSelf() super.onTaskRemoved(rootIntent) } private fun updateInfo(song: Song, paused: Boolean) { val largeIconHeight = resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_height) val largeIconWidth = resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_width) val albumArt = try { Glide.with(this).asBitmap().load(song.album.art).submit(largeIconWidth, largeIconHeight).get() } catch (e: Exception) { null } mediaSession.setMetadata( MediaMetadataCompat.Builder() .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, song.album.artist.name) .putString(MediaMetadataCompat.METADATA_KEY_ALBUM, song.album.title) .putString(MediaMetadataCompat.METADATA_KEY_TITLE, song.title) .putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, albumArt) .build() ) mediaSession.setPlaybackState( PlaybackStateCompat.Builder() .setState(if (paused) PlaybackStateCompat.STATE_PAUSED else PlaybackStateCompat.STATE_PLAYING, PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN, 1f) .setActions(PlaybackStateCompat.ACTION_PLAY or PlaybackStateCompat.ACTION_PAUSE or PlaybackStateCompat.ACTION_PLAY_PAUSE or PlaybackStateCompat.ACTION_SKIP_TO_NEXT or PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS) .build() ) updateNotification(song, paused, albumArt) } //region Notifications private fun updateNotification(song: Song, paused: Boolean, albumArt: Bitmap?) { val intent = Intent(this, MainActivity::class.java) .setAction(MainActivity.OPEN_NOW_PLAYING_ACTION) .setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP) val contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE) val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(NotificationChannel(CHANNEL_ID, getString(R.string.music_notification_channel_description), NotificationManager.IMPORTANCE_LOW).apply { setSound(null, null) }) val mediaStyle = MediaStyle().setMediaSession(mediaSession.sessionToken) .setShowActionsInCompactView(0, 1, 2) val notification = NotificationCompat.Builder(this, CHANNEL_ID) .setCategory(NotificationCompat.CATEGORY_STATUS) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setTicker(song.title) .setContentTitle(song.title) .setContentText(song.album.artist.name) .setContentIntent(contentIntent) .setLargeIcon(albumArt) .setSmallIcon(R.drawable.ic_play_arrow_white) .addMediaAction(R.drawable.ic_fast_rewind_black_medium, PLAY_PREVIOUS_ACTION) .addMediaAction(if (paused) R.drawable.ic_play_arrow_black_medium else R.drawable.ic_pause_black_medium, PLAY_OR_PAUSE_ACTION) .addMediaAction(R.drawable.ic_fast_forward_black_medium, PLAY_NEXT_ACTION) .setStyle(mediaStyle) .build() when { !paused -> { wasForeground = true startForeground(NOTIFICATION_ID, notification) } wasForeground -> { stopForeground(false) notificationManager.notify(NOTIFICATION_ID, notification) } } } private fun NotificationCompat.Builder.addMediaAction(@DrawableRes drawableRes: Int, action: String): NotificationCompat.Builder { return addAction(drawableRes, action, createPendingIntent(action)) } private fun createPendingIntent(action: String): PendingIntent { val intent = Intent(this, MusicService::class.java).setAction(action) return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE) } //endregion private fun tick() { presenter.onSeek(player.currentPosition.toInt()) handler.postDelayed({ tick() }, TICK_PERIOD) } private fun stopTicking() { handler.removeCallbacksAndMessages(null) } private val mediaSessionCallback = object : MediaSessionCompat.Callback() { //TODO implement methods } private val headsetPlugReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { presenter.onPauseClicked() } } class MediaButtonEventsReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { //TODO handle events } } } private const val NOTIFICATION_ID = 42 private const val PLAY_PREVIOUS_ACTION = "PLAY_PREVIOUS" private const val PLAY_OR_PAUSE_ACTION = "PLAY_OR_PAUSE" private const val PLAY_NEXT_ACTION = "PLAY_NEXT" private const val TICK_PERIOD = 100L private const val CHANNEL_ID = "music_controls" @SuppressLint("InlinedApi") // const will be inlined private const val PENDING_INTENT_FLAG_MUTABLE = PendingIntent.FLAG_MUTABLE
mit
ceca9f80f36f98c702cadea7ffe233a5
36.75
227
0.683299
4.9144
false
false
false
false
PolymerLabs/arcs-live
particles/Native/Kotlin/src/wasm/arcs/imports.kt
2
2869
package arcs import kotlinx.wasm.jsinterop.* // ktlint-disable no-wildcard-imports /** * These are the method declarations for calling in WasmParticle.js */ // FIXME: replace with native CPP malloc copy @SymbolName("Konan_js_get_String_length") external fun getStringLength(arena: Int, stringIndex: Int): Int @SymbolName("Konan_js_get_String_at") external fun getStringCharCodeAt(arena: Int, stringIndex: Int, index: Int): Char @SymbolName("arcs_WasmParticle_setState") external fun setExternalState(arena: Int, index: Int, statePtr: Int, stateLen: Int) @SymbolName("arcs_WasmParticle_log") external fun logExternal(arena: Int, index: Int, msgPtr: Int, msgLen: Int) @SymbolName("arcs_WasmParticle_getState") external fun getExternalState(arena: Int, index: Int): JsValue @SymbolName("arcs_WasmParticle_updateVariable") external fun updateVariableExternal( arena: Int, index: Int, propNamePtr: Int, propNameLen: Int, stateStrPtr: Int, stateStrLen: Int ) @SymbolName("arcs_WasmParticle_getInstance") external fun getWasmParticleInstance(resultArena: Int): Int @SymbolName("arcs_WasmParticle_service") external fun invokeService( objArena: Int, objIndex: Int, resultArena: Int, stringPtr: Int, strLen: Int ): Int @SymbolName("arcs_WasmParticle_setEventHandler") external fun setEventHandler(arena: Int, index: Int, handlerPtr: Int, handlerLen: Int, func: Int) @SymbolName("knjs__Promise_then") public external fun knjs__Promise_then( arena: Int, index: Int, lambdaIndex: Int, lambdaResultArena: Int, resultArena: Int ): Int fun setEventHandler(obj: JsValue, property: String, lambda: KtFunction<Unit>) { val pointer = wrapFunction(lambda) setEventHandler( obj.arena, obj.index, stringPointer(property), stringLengthBytes(property), pointer ) } fun WasmParticle.setEventHandler(property: String, lambda: KtFunction<Unit>) { setEventHandler(this, property, lambda) } open class Promise(arena: Int, index: Int) : JsValue(arena, index) { constructor(jsValue: JsValue) : this(jsValue.arena, jsValue.index) fun <Rlambda> then(lambda: KtFunction<Rlambda>): Promise { val lambdaIndex = wrapFunction<Rlambda>(lambda) val wasmRetVal = knjs__Promise_then( this.arena, this.index, lambdaIndex, ArenaManager.currentArena, ArenaManager.currentArena ) return Promise(ArenaManager.currentArena, wasmRetVal) } } val JsValue.asPromise: Promise get() { return Promise(this.arena, this.index) } // UGLY: fix using internal KString.cpp functions val JsValue.asString: String get() { val len = getStringLength(this.arena, this.index) if (len > 0) { val chars: CharArray = CharArray(len) for (i in 0 until len) { chars.store(i, getStringCharCodeAt(this.arena, this.index, i)) } return String(chars) } return "" }
bsd-3-clause
495c2486aa759d5d65dd8d8ce663e30d
26.32381
97
0.726734
3.631646
false
false
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/lang/core/completion/RsKeywordCompletionProvider.kt
1
2082
package org.rust.lang.core.completion import com.intellij.codeInsight.completion.* import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.openapi.editor.EditorModificationUtil import com.intellij.util.ProcessingContext import org.rust.lang.core.completion.CompletionEngine.KEYWORD_PRIORITY import org.rust.lang.core.psi.RsFunction import org.rust.lang.core.psi.ext.parentOfType import org.rust.lang.core.psi.ext.returnType import org.rust.lang.core.types.ty.TyUnit class RsKeywordCompletionProvider( private vararg val keywords: String ) : CompletionProvider<CompletionParameters>() { override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext?, result: CompletionResultSet) { for (keyword in keywords) { var builder = LookupElementBuilder.create(keyword) builder = addInsertionHandler(keyword, builder, parameters) result.addElement(PrioritizedLookupElement.withPriority(builder, KEYWORD_PRIORITY)) } } } class AddSuffixInsertionHandler(val suffix: String) : InsertHandler<LookupElement> { override fun handleInsert(context: InsertionContext, item: LookupElement) { context.document.insertString(context.selectionEndOffset, suffix) EditorModificationUtil.moveCaretRelatively(context.editor, suffix.length) } } private val ALWAYS_NEEDS_SPACE = setOf("crate", "const", "enum", "extern", "fn", "impl", "let", "mod", "mut", "pub", "static", "struct", "trait", "type", "unsafe", "use") private fun addInsertionHandler(keyword: String, builder: LookupElementBuilder, parameters: CompletionParameters): LookupElementBuilder { val suffix = when (keyword) { in ALWAYS_NEEDS_SPACE -> " " "return" -> { val fn = parameters.position.parentOfType<RsFunction>() ?: return builder if (fn.returnType !is TyUnit) " " else ";" } else -> return builder } return builder.withInsertHandler(AddSuffixInsertionHandler(suffix)) }
mit
001969254fdf7ac1aca811fb2c67409e
42.375
137
0.739673
4.606195
false
false
false
false
Cox-Automotive/apollo-client-maven-plugin
apollo-client-maven-plugin/src/main/kotlin/com/coxautodev/java/graphql/client/maven/plugin/GraphQLClientMojo.kt
1
5960
package com.coxautodev.java.graphql.client.maven.plugin import com.apollographql.apollo.compiler.GraphQLCompiler import com.apollographql.apollo.compiler.NullableValueType import org.apache.maven.plugin.AbstractMojo import org.apache.maven.plugin.MojoExecutionException import org.apache.maven.plugins.annotations.LifecyclePhase import org.apache.maven.plugins.annotations.Mojo import org.apache.maven.plugins.annotations.Parameter import org.apache.maven.plugins.annotations.ResolutionScope import org.apache.maven.project.MavenProject import org.codehaus.plexus.util.FileUtils import org.reflections.Reflections import org.reflections.scanners.ResourcesScanner import org.reflections.util.ConfigurationBuilder import java.io.File import java.nio.file.Files import java.util.regex.Pattern import java.util.stream.Collectors /** * Generates classes for a graphql API */ @Mojo(name = "generate", requiresDependencyCollection = ResolutionScope.COMPILE, requiresDependencyResolution = ResolutionScope.COMPILE, defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true ) class GraphQLClientMojo: AbstractMojo() { @Parameter(property = "outputDirectory", defaultValue = "\${project.build.directory}/generated-sources/graphql-client") private var outputDirectory: File? = null @Parameter(property = "basePackage", defaultValue = "com.example.graphql.client") private var basePackage: String? = null @Parameter(property = "introspectionFile", defaultValue = "\${project.basedir}/src/main/graphql/schema.json") private var introspectionFile: File? = null @Parameter(property = "addSourceRoot", defaultValue = "true") private var addSourceRoot: Boolean? = null @Parameter(readonly = true, required = true, defaultValue = "\${project}") private var project: MavenProject? = null @Throws(MojoExecutionException::class) override fun execute() { val project = this.project!! val outputDirectory = this.outputDirectory!! val basePackage = this.basePackage!! val introspectionFile = this.introspectionFile!! val basePackageDirName = basePackage.replace('.', File.separatorChar) val sourceDirName = joinPath("src", "main", "graphql") val queryDir = File(project.basedir, sourceDirName) if(!queryDir.isDirectory) { throw IllegalArgumentException("'${queryDir.absolutePath}' must be a directory") } val queries = Files.walk(queryDir.toPath()) .filter { it.toFile().isFile && it.toFile().name.endsWith(".graphql") } .map { it.toFile().relativeTo(queryDir) } .collect(Collectors.toList()) if(queries.isEmpty()) { throw IllegalArgumentException("No queries found under '${queryDir.absolutePath}") } val baseTargetDir = File(project.build.directory, joinPath("graphql-schema", sourceDirName, basePackageDirName)) val schema = File(baseTargetDir, "schema.json") val nodeModules = File(project.build.directory, joinPath("apollo-codegen-node-modules", "node_modules")) nodeModules.deleteRecursively() nodeModules.mkdirs() val nodeModuleResources = Reflections(ConfigurationBuilder().setScanners(ResourcesScanner()) .setUrls(javaClass.getResource("/node_modules"))) .getResources(Pattern.compile(".*")) nodeModuleResources.map { "/$it" }.forEach { resource -> val path = resource.replaceFirst("/node_modules/", "").replace(Regex("/"), File.separator) val diskPath = File(nodeModules, path) diskPath.parentFile.mkdirs() FileUtils.copyURLToFile(javaClass.getResource(resource), diskPath) } val apolloCli = File(nodeModules, joinPath("apollo-codegen", "lib", "cli.js")) apolloCli.setExecutable(true) if(!introspectionFile.isFile) { throw IllegalArgumentException("Introspection JSON not found: ${introspectionFile.absolutePath}") } if(!apolloCli.isFile) { throw IllegalStateException("Apollo codegen cli not found: '${apolloCli.absolutePath}'") } schema.parentFile.mkdirs() queries.forEach { query -> val src = File(queryDir, query.path) val dest = File(baseTargetDir, query.path) dest.parentFile.mkdirs() src.copyTo(dest, overwrite = true) } // https://stackoverflow.com/a/25080297 // https://stackoverflow.com/questions/32827329/how-to-get-the-full-path-of-an-executable-in-java-if-launched-from-windows-envi val node = System.getenv("PATH")?.split(File.pathSeparator)?.map { File(it, "node") }?.find { it.isFile && it.canExecute() } ?: throw IllegalStateException("No 'node' executable found on PATH!") log.info("Found node executable: ${node.absolutePath}") val arguments = listOf("generate", *queries.map { File(baseTargetDir, it.path).absolutePath }.toTypedArray(), "--target", "json", "--schema", introspectionFile.absolutePath, "--output", schema.absolutePath) log.info("Running apollo cli (${apolloCli.absolutePath}) with arguments: ${arguments.joinToString(" ")}") val proc = ProcessBuilder(node.absolutePath, apolloCli.absolutePath, *arguments.toTypedArray()) .directory(nodeModules.parentFile) .inheritIO() .start() if(proc.waitFor() != 0) { throw IllegalStateException("Apollo codegen cli command failed") } val compiler = GraphQLCompiler() compiler.write(GraphQLCompiler.Arguments(schema, outputDirectory, mapOf(), NullableValueType.JAVA_OPTIONAL, true, true)) if(addSourceRoot == true) { project.addCompileSourceRoot(outputDirectory.absolutePath) } } private fun joinPath(vararg names: String): String = names.joinToString(File.separator) }
mit
ac5d3194caa2290954d6ae5a793fb52c
41.571429
214
0.690772
4.65625
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/platform/mcp/actions/SrgActionBase.kt
1
3616
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mcp.actions import com.demonwav.mcdev.platform.mcp.McpModuleType import com.demonwav.mcdev.platform.mcp.srg.McpSrgMap import com.demonwav.mcdev.platform.mixin.handlers.ShadowHandler import com.demonwav.mcdev.util.ActionData import com.demonwav.mcdev.util.getDataFromActionEvent import com.demonwav.mcdev.util.invokeLater import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.editor.Editor import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.wm.WindowManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiIdentifier import com.intellij.psi.PsiMember import com.intellij.psi.PsiReference import com.intellij.ui.LightColors import com.intellij.ui.awt.RelativePoint abstract class SrgActionBase : AnAction() { override fun actionPerformed(e: AnActionEvent) { val data = getDataFromActionEvent(e) ?: return showBalloon("Unknown failure", e) if (data.element !is PsiIdentifier) { showBalloon("Not a valid element", e) return } val mcpModule = data.instance.getModuleOfType(McpModuleType) ?: return showBalloon("No mappings found", e) mcpModule.srgManager?.srgMap?.onSuccess { srgMap -> var parent = data.element.parent ?: return@onSuccess showBalloon("Not a valid element", e) if (parent is PsiMember) { val shadowTarget = ShadowHandler.getInstance()?.findFirstShadowTargetForReference(parent)?.element if (shadowTarget != null) { parent = shadowTarget } } if (parent is PsiReference) { parent = parent.resolve() ?: return@onSuccess showBalloon("Not a valid element", e) } withSrgTarget(parent, srgMap, e, data) }?.onError { showBalloon(it.message ?: "No MCP data available", e) } ?: showBalloon("No mappings found", e) } abstract fun withSrgTarget(parent: PsiElement, srgMap: McpSrgMap, e: AnActionEvent, data: ActionData) protected fun showBalloon(message: String, e: AnActionEvent) { val balloon = JBPopupFactory.getInstance() .createHtmlTextBalloonBuilder(message, null, LightColors.YELLOW, null) .setHideOnAction(true) .setHideOnClickOutside(true) .setHideOnKeyOutside(true) .createBalloon() val project = e.project ?: return val statusBar = WindowManager.getInstance().getStatusBar(project) invokeLater { balloon.show(RelativePoint.getCenterOf(statusBar.component), Balloon.Position.atRight) } } protected fun showSuccessBalloon(editor: Editor, element: PsiElement, text: String) { val balloon = JBPopupFactory.getInstance() .createHtmlTextBalloonBuilder(text, null, LightColors.SLIGHTLY_GREEN, null) .setHideOnAction(true) .setHideOnClickOutside(true) .setHideOnKeyOutside(true) .createBalloon() invokeLater { balloon.show( RelativePoint( editor.contentComponent, editor.visualPositionToXY(editor.offsetToVisualPosition(element.textRange.endOffset)) ), Balloon.Position.atRight ) } } }
mit
918145c8edafa5c6677825cda4e2c17b
35.16
114
0.670354
4.821333
false
false
false
false
drakeet/MultiType
sample/src/main/kotlin/com/drakeet/multitype/sample/bilibili/HorizontalPostsHolderInflater.kt
1
2047
/* * Copyright (c) 2016-present. Drakeet Xu * * 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.drakeet.multitype.sample.bilibili import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearSnapHelper import androidx.recyclerview.widget.RecyclerView import com.drakeet.multitype.ViewHolderInflater import com.drakeet.multitype.sample.R /** * @author Drakeet Xu */ class HorizontalPostsHolderInflater : ViewHolderInflater<PostList, HorizontalPostsHolderInflater.ViewHolder>() { override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): ViewHolder { return ViewHolder(inflater.inflate(R.layout.item_horizontal_list, parent, false)) } override fun onBindViewHolder(holder: ViewHolder, item: PostList) { holder.setPosts(item.posts) } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val adapter: PostsAdapter = PostsAdapter() private val recyclerView: RecyclerView = itemView.findViewById(R.id.post_list) init { val layoutManager = LinearLayoutManager(itemView.context) layoutManager.orientation = LinearLayoutManager.HORIZONTAL recyclerView.layoutManager = layoutManager LinearSnapHelper().attachToRecyclerView(recyclerView) recyclerView.adapter = adapter } fun setPosts(posts: List<Post>) { adapter.setPosts(posts) adapter.notifyDataSetChanged() } } }
apache-2.0
8f61387f5e6594d8b4cb8dc9af4247cf
33.694915
112
0.766976
4.579418
false
false
false
false
ohmae/mmupnp
mmupnp/src/main/java/net/mm2d/upnp/internal/manager/DeviceHolder.kt
1
3273
/* * Copyright (c) 2019 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.upnp.internal.manager import net.mm2d.upnp.Device import net.mm2d.upnp.internal.thread.TaskExecutors import net.mm2d.upnp.internal.thread.ThreadCondition import java.util.concurrent.TimeUnit import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.withLock /** * A class holding [Device] found in [net.mm2d.upnp.ControlPoint]. * * Check the expiration date of Device, and notify the expired Device as Lost. * * @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected]) * * @constructor initialize * @param expireListener Listener to receive expired notifications */ internal class DeviceHolder( taskExecutors: TaskExecutors, private val expireListener: (Device) -> Unit ) : Runnable { private val threadCondition = ThreadCondition(taskExecutors.manager) private val lock = ReentrantLock() private val condition = lock.newCondition() private val deviceMap = mutableMapOf<String, Device>() val deviceList: List<Device> get() = lock.withLock { deviceMap.values.toList() } val size: Int get() = lock.withLock { deviceMap.size } fun start() { threadCondition.start(this) } fun stop() { threadCondition.stop() } fun add(device: Device) { lock.withLock { deviceMap[device.udn] = device condition.signalAll() } } operator fun get(udn: String): Device? = lock.withLock { deviceMap[udn] } fun remove(device: Device): Device? = lock.withLock { deviceMap.remove(device.udn) } fun remove(udn: String): Device? = lock.withLock { deviceMap.remove(udn) } fun clear(): Unit = lock.withLock { deviceMap.clear() } override fun run() { Thread.currentThread().let { it.name = it.name + "-device-holder" } lock.withLock { try { while (!threadCondition.isCanceled()) { while (deviceMap.isEmpty()) { condition.await() } expireDevice() waitNextExpireTime() } } catch (ignored: InterruptedException) { } } } private fun expireDevice() { val now = System.currentTimeMillis() deviceMap.values .filter { it.expireTime < now } .forEach { deviceMap.remove(it.udn) expireListener.invoke(it) } } @Throws(InterruptedException::class) private fun waitNextExpireTime() { if (deviceMap.isEmpty()) { return } val mostRecentExpireTime = deviceMap.values.map { it.expireTime }.minOrNull() ?: 0L val duration = mostRecentExpireTime - System.currentTimeMillis() + MARGIN_TIME val sleep = maxOf(duration, MARGIN_TIME) // avoid negative value condition.await(sleep, TimeUnit.MILLISECONDS) } companion object { private val MARGIN_TIME = TimeUnit.SECONDS.toMillis(10) } }
mit
5fa0ce39822e7919435f986b8b1d386b
26.369748
91
0.602702
4.486226
false
false
false
false
dewarder/Android-Kotlin-Commons
akommons/src/main/java/com/dewarder/akommons/content/preferences/PreferencesDelegates.kt
1
2349
/* * Copyright (C) 2017 Artem Hluhovskyi * * 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.dewarder.akommons.content.preferences import java.util.* import kotlin.properties.ReadWriteProperty object PreferencesDelegates { fun int( defaultValue: Int = 0, key: String? = null ): ReadWriteProperty<SharedPreferencesProvider, Int> = IntPreferencesProperty(defaultValue, key) fun float( defaultValue: Float = 0f, key: String? = null ): ReadWriteProperty<SharedPreferencesProvider, Float> = FloatPreferencesProperty(defaultValue, key) fun string( defaultValue: String = "", key: String? = null ): ReadWriteProperty<SharedPreferencesProvider, String> = StringPreferencesProperty(defaultValue, key) fun boolean( defaultValue: Boolean = false, key: String? = null ): ReadWriteProperty<SharedPreferencesProvider, Boolean> = BooleanPreferencesProperty(defaultValue, key) fun date( defaultValue: Long = 0, key: String? = null ): ReadWriteProperty<SharedPreferencesProvider, Date> = DatePreferencesProperty(defaultValue, key) fun calendar( defaultValue: Long = 0, key: String? = null ): ReadWriteProperty<SharedPreferencesProvider, Calendar> = CalendarPreferencesProperty(defaultValue, key) fun <T> custom( defaultValue: T, key: String? = null, mapperFrom: (String) -> T ): ReadWriteProperty<SharedPreferencesProvider, T> = CustomPreferencesProperty(defaultValue, key, mapperFrom) fun <T> custom( defaultValue: T, key: String? = null, mapperFrom: (String) -> T, mapperTo: (T) -> String ): ReadWriteProperty<SharedPreferencesProvider, T> = CustomPreferencesProperty(defaultValue, key, mapperFrom, mapperTo) }
apache-2.0
a908a3796f020fa124288a5218026c35
34.074627
123
0.700298
4.77439
false
false
false
false
ffc-nectec/FFC
ffc/src/main/kotlin/ffc/android/TextView.kt
1
3798
/* * Copyright (c) 2019 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. */ @file:Suppress("DEPRECATION") package ffc.android import android.graphics.drawable.Drawable import android.text.Editable import android.text.TextWatcher import android.widget.TextView fun TextView.getDouble(default: Double? = null): Double? { val text = text.toString() if (text.isBlank()) return default return text.toDouble() } @Deprecated("Consider replace with drawableStart to better support right-to-left Layout", ReplaceWith("drawableStart"), DeprecationLevel.WARNING) var TextView.drawableLeft: Drawable? get() = compoundDrawables[0] set(drawable) = setCompoundDrawablesWithIntrinsicBounds(drawable, drawableTop, drawableRight, drawableBottom) var TextView.drawableStart: Drawable? get() = compoundDrawablesRelative[0] set(drawable) = compoundDrawablesRelativeWithIntrinsicBounds(start = drawable) var TextView.drawableTop: Drawable? get() = compoundDrawablesRelative[1] set(drawable) = compoundDrawablesRelativeWithIntrinsicBounds(top = drawable) @Deprecated("Consider replace with drawableEnd to better support right-to-left Layout", ReplaceWith("drawableEnd"), DeprecationLevel.WARNING) var TextView.drawableRight: Drawable? get() = compoundDrawables[2] set(drawable) = setCompoundDrawablesWithIntrinsicBounds(drawableLeft, drawableTop, drawable, drawableBottom) var TextView.drawableEnd: Drawable? get() = compoundDrawablesRelative[2] set(drawable) = compoundDrawablesRelativeWithIntrinsicBounds(end = drawable) var TextView.drawableBottom: Drawable? get() = compoundDrawablesRelative[3] set(drawable) = compoundDrawablesRelativeWithIntrinsicBounds(bottom = drawable) private fun TextView.compoundDrawablesRelativeWithIntrinsicBounds( start: Drawable? = drawableStart, top: Drawable? = drawableTop, end: Drawable? = drawableEnd, bottom: Drawable? = drawableBottom ) { setCompoundDrawablesRelativeWithIntrinsicBounds(start, top, end, bottom) } class TextWatcherDsl : TextWatcher { private var afterChanged: ((Editable?) -> Unit)? = null private var beforeChanged: ((s: CharSequence?, start: Int, count: Int, after: Int) -> Unit)? = null private var onChanged: ((s: CharSequence?, start: Int, before: Int, count: Int) -> Unit)? = null override fun afterTextChanged(s: Editable?) { afterChanged?.invoke(s) } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { beforeChanged?.invoke(s, start, count, after) } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { onChanged?.invoke(s, start, before, count) } fun afterTextChanged(block: (s: Editable?) -> Unit) { afterChanged = block } fun beforeTextChanged(block: (s: CharSequence?, start: Int, count: Int, after: Int) -> Unit) { beforeChanged = block } fun onTextChanged(block: (s: CharSequence?, start: Int, before: Int, count: Int) -> Unit) { onChanged = block } } fun TextView.addTextWatcher(block: TextWatcherDsl.() -> Unit) { addTextChangedListener(TextWatcherDsl().apply(block)) }
apache-2.0
fb8d01f65055d8ecc358a05a1f5a767d
35.519231
113
0.731964
4.462985
false
false
false
false
doerfli/hacked
app/src/main/kotlin/li/doerf/hacked/ui/viewmodels/BreachedSitesViewModel.kt
1
2463
package li.doerf.hacked.ui.viewmodels import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import li.doerf.hacked.db.AppDatabase import li.doerf.hacked.db.daos.BreachedSiteDao import li.doerf.hacked.db.entities.BreachedSite class BreachedSitesViewModel(application: Application) : AndroidViewModel(application) { private val myBreachedSitesDao: BreachedSiteDao = AppDatabase.get(application).brachedSiteDao private var myBreachedSites: LiveData<List<BreachedSite>>? private var myBreachedSitesMostRecent: LiveData<List<BreachedSite>>? = null private val filterLiveData: MutableLiveData<Pair<Order, String>> = MutableLiveData(Pair(Order.NAME, "")) val breachesSites: LiveData<List<BreachedSite>>? get() { if (myBreachedSites == null) { myBreachedSites = myBreachedSitesDao.allLD } return myBreachedSites } fun setFilter(filter: String) { filterLiveData.value = Pair(Order.NAME, filter) } val breachesSitesMostRecent: LiveData<List<BreachedSite>>? get() { if (myBreachedSitesMostRecent == null) { myBreachedSitesMostRecent = myBreachedSitesDao.listMostRecent() } return myBreachedSitesMostRecent } fun orderByName() { filterLiveData.value = Pair(Order.NAME, "") } fun orderByCount() { filterLiveData.value = Pair(Order.COUNT, "") } fun orderByDate() { filterLiveData.value = Pair(Order.DATE, "") } private enum class Order { NAME, COUNT, DATE } init { myBreachedSites = Transformations.switchMap(filterLiveData ) { (o: Order, filter: String) -> when(o) { Order.NAME -> { if (filter.trim { it <= ' ' } == "") { return@switchMap myBreachedSitesDao.allLD } else { return@switchMap myBreachedSitesDao.getAllByName("%$filter%") } } Order.COUNT -> { return@switchMap myBreachedSitesDao.allByPwnCountLD } Order.DATE -> { return@switchMap myBreachedSitesDao.allByDateAddedLD } } } } }
apache-2.0
9319273163007008d0ebd3db02244d55
32.753425
108
0.614292
5.13125
false
false
false
false
phxql/unison-tray-icon
src/main/kotlin/de/mkammerer/unisontray/util/Process.kt
1
1328
package de.mkammerer.unisontray.util import org.slf4j.LoggerFactory import java.io.InputStreamReader import java.util.concurrent.atomic.AtomicReference object ProcessUtil { private val logger = LoggerFactory.getLogger(javaClass) fun startAndReadProcess(builder: ProcessBuilder): ProcessResult { builder.redirectErrorStream(true) val output = AtomicReference<String>() val exception = AtomicReference<Exception>() logger.debug("Starting process") val process = builder.start() val thread = Thread({ try { logger.debug("Reading process output") InputStreamReader(process.inputStream, Charsets.UTF_8).use { output.set(it.readText()) } } catch (e: Exception) { exception.set(e) } }, "process-capture") thread.start() logger.debug("Waiting for process exit") val exitCode = process.waitFor() thread.interrupt() thread.join() logger.debug("Process has exited with {}", exitCode) // Rethrow exception if one happened exception.get()?.let { throw it } return ProcessResult(output.get(), exitCode) } data class ProcessResult(val output: String, val exitCode: Int) }
lgpl-3.0
f09c5c9e52ae9d33ff45454597412787
30.642857
76
0.622741
4.936803
false
false
false
false
stripe/stripe-android
payments-core/src/main/java/com/stripe/android/payments/bankaccount/ui/CollectBankAccountActivity.kt
1
2406
package com.stripe.android.payments.bankaccount.ui import android.app.Activity import android.content.Intent import android.os.Bundle import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import com.stripe.android.payments.bankaccount.navigation.CollectBankAccountContract import com.stripe.android.payments.bankaccount.ui.CollectBankAccountViewEffect.FinishWithResult import com.stripe.android.payments.bankaccount.ui.CollectBankAccountViewEffect.OpenConnectionsFlow import com.stripe.android.payments.financialconnections.FinancialConnectionsPaymentsProxy /** * No-UI activity that will handle collect bank account logic. */ internal class CollectBankAccountActivity : AppCompatActivity() { private val starterArgs: CollectBankAccountContract.Args? by lazy { CollectBankAccountContract.Args.fromIntent(intent) } private lateinit var financialConnectionsPaymentsProxy: FinancialConnectionsPaymentsProxy private val viewModel: CollectBankAccountViewModel by viewModels { CollectBankAccountViewModel.Factory { requireNotNull(starterArgs) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) initConnectionsPaymentsProxy() lifecycleScope.launchWhenStarted { viewModel.viewEffect.collect { viewEffect -> when (viewEffect) { is OpenConnectionsFlow -> viewEffect.launch() is FinishWithResult -> viewEffect.launch() } } } } private fun initConnectionsPaymentsProxy() { financialConnectionsPaymentsProxy = FinancialConnectionsPaymentsProxy.create( activity = this, onComplete = viewModel::onConnectionsResult ) } private fun OpenConnectionsFlow.launch() { financialConnectionsPaymentsProxy.present( financialConnectionsSessionClientSecret = financialConnectionsSessionSecret, publishableKey = publishableKey, stripeAccountId = stripeAccountId ) } private fun FinishWithResult.launch() { setResult( Activity.RESULT_OK, Intent().putExtras( CollectBankAccountContract.Result(result).toBundle() ) ) finish() } }
mit
743caef093aec6ff1b1a446b029ba399
34.382353
98
0.713217
5.825666
false
false
false
false
codeka/wwmmo
server/src/main/kotlin/au/com/codeka/warworlds/server/LogImpl.kt
1
3457
package au.com.codeka.warworlds.server import au.com.codeka.warworlds.common.Log import org.joda.time.DateTime import java.io.File import java.io.PrintWriter import java.nio.file.Files /** * This class works with the Log class to provide a concrete implementation we can use in the * server. */ object LogImpl { private lateinit var config: Configuration.LoggingConfig fun setup(config: Configuration.LoggingConfig) { LogImpl.config = config Log.setImpl(LogImplImpl()) } val levelMap = arrayOf("ERROR", "WARNING", "INFO", "DEBUG") private class LogImplImpl : Log.LogImpl { private var lastOpenTime: DateTime? = null private var file: File? = null private var writer: PrintWriter? = null private val maxLevel: Int = levelMap.indexOf(config.maxLevel) override fun isLoggable(tag: String, level: Int): Boolean { return level <= maxLevel } override fun write(tag: String, level: Int, msg: String) { if (level > maxLevel) { return } val sb = StringBuilder() LogFormatter.DATE_TIME_FORMATTER.printTo(sb, DateTime.now()) sb.append(" ") sb.append(levelMap[level]) sb.append(" ") sb.append(tag) sb.append(": ") sb.append(msg) // First write to the console. val str = sb.toString() println(str) // Then to the log file. synchronized(LogImpl) { ensureOpen() with(writer!!) { println(str) flush() } } } private fun ensureOpen() { if (isFileTooOld()) { close() } if (file == null) { open() } } private fun open() { if (file == null) { file = File(config.fileName + ".log") } val f = file ?: return if (f.exists()) { backup() } f.parentFile.mkdirs() writer = PrintWriter(f, Charsets.UTF_8) } private fun close() { val w = writer ?: return w.close() writer = null } private fun backup() { val date = lastOpenTime ?: DateTime.now() val f = file ?: return var n = 1 var backupFile: File do { backupFile = File( String.format( config.fileName + "-%04d-%02d-%02d-%04d.log", date.year, date.monthOfYear, date.dayOfMonth, n)) n++ } while (backupFile.exists()) Files.move(f.toPath(), backupFile.toPath()) cleanup() } private fun isFileTooOld(): Boolean { val time = lastOpenTime ?: return false val now = DateTime.now() // It's a different day, it's too old. return !now.toDate().equals(time.toDate()) } /** When have too many log files, delete some of the older ones. */ private fun cleanup() { val f = file ?: return val existingFiles = ArrayList<File>() for (existing in f.parentFile.listFiles() ?: arrayOf()) { if (existing.isFile && existing.extension == "log") { existingFiles.add(existing) } } // Sort them from newest to oldest existingFiles.sortBy { file -> file.lastModified() } // Once we get above the limit for cumulative file size, start deleting. var totalSize = 0L for (existingFile in existingFiles) { totalSize += existingFile.length() if (totalSize > 10L * 1024L * 1024L) { existingFile.delete() } } } } }
mit
c7f251f9c44899cf5ff4a8990732269d
23.51773
93
0.578826
4.095972
false
true
false
false
TeamWizardry/LibrarianLib
modules/mosaic/src/main/kotlin/com/teamwizardry/librarianlib/mosaic/MosaicSprite.kt
1
3011
package com.teamwizardry.librarianlib.mosaic import net.minecraft.client.render.RenderLayer import net.minecraft.util.Identifier import java.awt.image.BufferedImage /** * This class represents a section of a [Mosaic] */ public class MosaicSprite internal constructor(private val mosaic: Mosaic, public val name: String) : Sprite { private lateinit var definition: SpriteDefinition override val texture: Identifier get() = mosaic.location override var width: Int = 0 private set override var height: Int = 0 private set override var uSize: Float = 0f private set override var vSize: Float = 0f private set override var pinLeft: Boolean = true private set override var pinTop: Boolean = true private set override var pinRight: Boolean = true private set override var pinBottom: Boolean = true private set override var minUCap: Float = 0f private set override var minVCap: Float = 0f private set override var maxUCap: Float = 0f private set override var maxVCap: Float = 0f private set override var frameCount: Int = 1 private set public var images: List<BufferedImage> = emptyList() private set init { loadDefinition() } internal fun loadDefinition() { definition = mosaic.getSpriteDefinition(name) pinLeft = definition.minUPin pinTop = definition.minVPin pinRight = definition.maxUPin pinBottom = definition.maxVPin minUCap = definition.minUCap / definition.size.xf minVCap = definition.minVCap / definition.size.yf maxUCap = definition.maxUCap / definition.size.xf maxVCap = definition.maxVCap / definition.size.yf frameCount = definition.frameUVs.size width = mosaic.logicalU(definition.size.x) height = mosaic.logicalV(definition.size.y) uSize = definition.texU(definition.size.x) vSize = definition.texV(definition.size.y) images = definition.frameImages } /** * The minimum U coordinate (0-1) */ override fun minU(animFrames: Int): Float { return definition.texU(definition.frameUVs[animFrames % frameCount].x) } /** * The minimum V coordinate (0-1) */ override fun minV(animFrames: Int): Float { return definition.texV(definition.frameUVs[animFrames % frameCount].y) } /** * The maximum U coordinate (0-1) */ override fun maxU(animFrames: Int): Float { return definition.texU(definition.frameUVs[animFrames % frameCount].x + definition.size.x) } /** * The maximum V coordinate (0-1) */ override fun maxV(animFrames: Int): Float { return definition.texV(definition.frameUVs[animFrames % frameCount].y + definition.size.y) } override fun toString(): String { return "Sprite(texture=${mosaic.location}, name=$name)" } }
lgpl-3.0
6625eae553ddf4b327d4a2cd03844294
26.372727
110
0.651279
4.414956
false
false
false
false
deva666/anko
anko/library/generated/sdk23/src/Layouts.kt
2
69586
@file:JvmName("Sdk23LayoutsKt") package org.jetbrains.anko import android.content.Context import android.util.AttributeSet import android.view.ViewGroup import android.widget.FrameLayout import android.appwidget.AppWidgetHostView import android.view.View import android.webkit.WebView import android.widget.AbsoluteLayout import android.widget.ActionMenuView import android.widget.Gallery import android.widget.GridLayout import android.widget.GridView import android.widget.AbsListView import android.widget.HorizontalScrollView import android.widget.ImageSwitcher import android.widget.LinearLayout import android.widget.RadioGroup import android.widget.RelativeLayout import android.widget.ScrollView import android.widget.TableLayout import android.widget.TableRow import android.widget.TextSwitcher import android.widget.Toolbar import android.app.ActionBar import android.widget.ViewAnimator import android.widget.ViewSwitcher open class _AppWidgetHostView(ctx: Context): AppWidgetHostView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _WebView(ctx: Context): WebView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: ViewGroup.LayoutParams.() -> Unit ): T { val layoutParams = ViewGroup.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = ViewGroup.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: ViewGroup.LayoutParams.() -> Unit ): T { val layoutParams = ViewGroup.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = ViewGroup.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: ViewGroup.LayoutParams.() -> Unit ): T { val layoutParams = ViewGroup.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = ViewGroup.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _AbsoluteLayout(ctx: Context): AbsoluteLayout(ctx) { inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, x: Int, y: Int, init: AbsoluteLayout.LayoutParams.() -> Unit ): T { val layoutParams = AbsoluteLayout.LayoutParams(width, height, x, y) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, x: Int, y: Int ): T { val layoutParams = AbsoluteLayout.LayoutParams(width, height, x, y) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: AbsoluteLayout.LayoutParams.() -> Unit ): T { val layoutParams = AbsoluteLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = AbsoluteLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: AbsoluteLayout.LayoutParams.() -> Unit ): T { val layoutParams = AbsoluteLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = AbsoluteLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ActionMenuView(ctx: Context): ActionMenuView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: ActionMenuView.LayoutParams.() -> Unit ): T { val layoutParams = ActionMenuView.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = ActionMenuView.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( other: ViewGroup.LayoutParams?, init: ActionMenuView.LayoutParams.() -> Unit ): T { val layoutParams = ActionMenuView.LayoutParams(other!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( other: ViewGroup.LayoutParams? ): T { val layoutParams = ActionMenuView.LayoutParams(other!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( other: ActionMenuView.LayoutParams?, init: ActionMenuView.LayoutParams.() -> Unit ): T { val layoutParams = ActionMenuView.LayoutParams(other!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( other: ActionMenuView.LayoutParams? ): T { val layoutParams = ActionMenuView.LayoutParams(other!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: ActionMenuView.LayoutParams.() -> Unit ): T { val layoutParams = ActionMenuView.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = ActionMenuView.LayoutParams(width, height) [email protected] = layoutParams return this } } open class _FrameLayout(ctx: Context): FrameLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _Gallery(ctx: Context): Gallery(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: Gallery.LayoutParams.() -> Unit ): T { val layoutParams = Gallery.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = Gallery.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: Gallery.LayoutParams.() -> Unit ): T { val layoutParams = Gallery.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = Gallery.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: Gallery.LayoutParams.() -> Unit ): T { val layoutParams = Gallery.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = Gallery.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _GridLayout(ctx: Context): GridLayout(ctx) { inline fun <T: View> T.lparams( rowSpec: GridLayout.Spec?, columnSpec: GridLayout.Spec?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(rowSpec!!, columnSpec!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( rowSpec: GridLayout.Spec?, columnSpec: GridLayout.Spec? ): T { val layoutParams = GridLayout.LayoutParams(rowSpec!!, columnSpec!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams() layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( ): T { val layoutParams = GridLayout.LayoutParams() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( params: ViewGroup.LayoutParams?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(params!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( params: ViewGroup.LayoutParams? ): T { val layoutParams = GridLayout.LayoutParams(params!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( params: ViewGroup.MarginLayoutParams?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(params!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( params: ViewGroup.MarginLayoutParams? ): T { val layoutParams = GridLayout.LayoutParams(params!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: GridLayout.LayoutParams?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: GridLayout.LayoutParams? ): T { val layoutParams = GridLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( context: Context?, attrs: AttributeSet?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(context!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( context: Context?, attrs: AttributeSet? ): T { val layoutParams = GridLayout.LayoutParams(context!!, attrs!!) [email protected] = layoutParams return this } } open class _GridView(ctx: Context): GridView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: AbsListView.LayoutParams.() -> Unit ): T { val layoutParams = AbsListView.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = AbsListView.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: AbsListView.LayoutParams.() -> Unit ): T { val layoutParams = AbsListView.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = AbsListView.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, viewType: Int, init: AbsListView.LayoutParams.() -> Unit ): T { val layoutParams = AbsListView.LayoutParams(width, height, viewType) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, viewType: Int ): T { val layoutParams = AbsListView.LayoutParams(width, height, viewType) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: AbsListView.LayoutParams.() -> Unit ): T { val layoutParams = AbsListView.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = AbsListView.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _HorizontalScrollView(ctx: Context): HorizontalScrollView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ImageSwitcher(ctx: Context): ImageSwitcher(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _LinearLayout(ctx: Context): LinearLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = LinearLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = LinearLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, weight: Float, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(width, height, weight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, weight: Float ): T { val layoutParams = LinearLayout.LayoutParams(width, height, weight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = LinearLayout.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = LinearLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: LinearLayout.LayoutParams?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: LinearLayout.LayoutParams? ): T { val layoutParams = LinearLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _RadioGroup(ctx: Context): RadioGroup(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = RadioGroup.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = RadioGroup.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(width, height, initWeight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float ): T { val layoutParams = RadioGroup.LayoutParams(width, height, initWeight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = RadioGroup.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = RadioGroup.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _RelativeLayout(ctx: Context): RelativeLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = RelativeLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = RelativeLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: RelativeLayout.LayoutParams?, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: RelativeLayout.LayoutParams? ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ScrollView(ctx: Context): ScrollView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _TableLayout(ctx: Context): TableLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = TableLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = TableLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(width, height, initWeight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float ): T { val layoutParams = TableLayout.LayoutParams(width, height, initWeight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams() layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( ): T { val layoutParams = TableLayout.LayoutParams() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = TableLayout.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = TableLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _TableRow(ctx: Context): TableRow(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = TableRow.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = TableRow.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(width, height, initWeight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float ): T { val layoutParams = TableRow.LayoutParams(width, height, initWeight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams() layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( ): T { val layoutParams = TableRow.LayoutParams() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( column: Int, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(column) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( column: Int ): T { val layoutParams = TableRow.LayoutParams(column) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = TableRow.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = TableRow.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _TextSwitcher(ctx: Context): TextSwitcher(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _Toolbar(ctx: Context): Toolbar(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = Toolbar.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = Toolbar.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = Toolbar.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( gravity: Int, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( gravity: Int ): T { val layoutParams = Toolbar.LayoutParams(gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: Toolbar.LayoutParams?, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: Toolbar.LayoutParams? ): T { val layoutParams = Toolbar.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ActionBar.LayoutParams?, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ActionBar.LayoutParams? ): T { val layoutParams = Toolbar.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = Toolbar.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: Toolbar.LayoutParams.() -> Unit ): T { val layoutParams = Toolbar.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = Toolbar.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ViewAnimator(ctx: Context): ViewAnimator(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ViewSwitcher(ctx: Context): ViewSwitcher(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: FrameLayout.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } }
apache-2.0
56749c729318a961a440eaaea4aa7fb1
30.745438
78
0.610381
4.868878
false
false
false
false
jacobped/IKS-TS-Bot
src/main/kotlin/app/Events.kt
1
2944
package app import com.github.theholywaffle.teamspeak3.api.event.ClientJoinEvent /** * Created by jacob on 2017-06-09 (YYYY-MM-DD). */ interface ISender { val uniqueId: String } interface ICommand { val sender: ISender val prefix: String val suffix: String } interface IMessage { val sender: ISender val message: String } interface IClientJoined { val clientId: Int val channelId: Int } interface IMoved { val channelIdMovedTo: Int val clientId: Int } interface IClient { //This might be missing relations to channel val id: Int // The clients current instance id. val uniqueId: String val databaseId: Int val nickName: String val channelGroupId: Int // val type: //The framework value is Int, which doesn't make any sense. val isInputMuted: Boolean val isOutputMuted: Boolean val isOutputOnlyMuted: Boolean val isUsingHardwareInput: Boolean val isUsingHardwareOutput: Boolean val isRecording: Boolean val isTalking: Boolean val isPrioritySpeaker: Boolean val isChannelCommander: Boolean val isAway: Boolean val awayMessage: String val amountOfServerGroups: Int val ServerGroups: MutableCollection<IServerGroup> val avatarId: String val talkPower: Int val country: String } interface IServerGroup { } enum class ClientType { query, user } class InheritedClient(event: ClientJoinEvent): IClient { override val uniqueId: String = event.uniqueClientIdentifier override val databaseId: Int = event.clientDatabaseId override val id: Int = event.clientId override val nickName: String = event.clientNickname override val channelGroupId: Int = event.clientChannelGroupId // val type: //The framework value is Int, which doesn't make any sense. override val isInputMuted: Boolean = event.isClientInputMuted override val isOutputMuted: Boolean = event.isClientOutputMuted override val isOutputOnlyMuted: Boolean = event.isClientOutputOnlyMuted override val isUsingHardwareInput: Boolean = event.isClientUsingHardwareInput override val isUsingHardwareOutput: Boolean = event.isClientUsingHardwareOutput override val isRecording: Boolean = event.isClientRecording override val isTalking: Boolean = event.isClientTalking override val isPrioritySpeaker: Boolean = event.isClientPrioritySpeaker override val isChannelCommander: Boolean = event.isClientChannelCommander override val isAway: Boolean = event.isClientAway override val awayMessage: String = event.clientAwayMessage override val amountOfServerGroups: Int = event.amountOfServerGroups override val ServerGroups: MutableCollection<IServerGroup> = arrayListOf() //TODO: Define and add Servergroups override val avatarId: String = event.clientFlagAvatarId override val talkPower: Int = event.clientTalkPower override val country: String = event.clientCountry }
mit
2dfb1b467b7decb4667dceb0e530da37
31.711111
114
0.755095
4.557276
false
false
false
false
Niky4000/UsefulUtils
projects/tutorials-master/tutorials-master/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringUnitTest.kt
1
2187
import org.apache.commons.lang3.RandomStringUtils import org.junit.Before import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import java.security.SecureRandom import java.util.concurrent.ThreadLocalRandom import kotlin.experimental.and import kotlin.streams.asSequence import kotlin.test.assertEquals const val STRING_LENGTH = 10 const val ALPHANUMERIC_REGEX = "[a-zA-Z0-9]+" class RandomStringUnitTest { private val charPool : List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9') @Test fun givenAStringLength_whenUsingJava_thenReturnAlphanumericString() { var randomString = ThreadLocalRandom.current() .ints(STRING_LENGTH.toLong(), 0, charPool.size) .asSequence() .map(charPool::get) .joinToString("") assert(randomString.matches(Regex(ALPHANUMERIC_REGEX))) assertEquals(STRING_LENGTH, randomString.length) } @Test fun givenAStringLength_whenUsingKotlin_thenReturnAlphanumericString() { var randomString = (1..STRING_LENGTH).map { i -> kotlin.random.Random.nextInt(0, charPool.size) } .map(charPool::get) .joinToString("") assert(randomString.matches(Regex(ALPHANUMERIC_REGEX))) assertEquals(STRING_LENGTH, randomString.length) } @Test fun givenAStringLength_whenUsingApacheCommon_thenReturnAlphanumericString() { var randomString = RandomStringUtils.randomAlphanumeric(STRING_LENGTH) assert(randomString.matches(Regex(ALPHANUMERIC_REGEX))) assertEquals(STRING_LENGTH, randomString.length) } @Test fun givenAStringLength_whenUsingRandomForBytes_thenReturnAlphanumericString() { val random = SecureRandom() val bytes = ByteArray(STRING_LENGTH) random.nextBytes(bytes) var randomString = (0..bytes.size - 1).map { i -> charPool.get((bytes[i] and 0xFF.toByte() and (charPool.size-1).toByte()).toInt()) }.joinToString("") assert(randomString.matches(Regex(ALPHANUMERIC_REGEX))) assertEquals(STRING_LENGTH, randomString.length) } }
gpl-3.0
5331698d8a9dd590ba2b299b9128db12
34.290323
105
0.686328
4.374
false
true
false
false
pyamsoft/power-manager
powermanager-service/src/main/java/com/pyamsoft/powermanager/service/job/ManageJobRunner.kt
1
16705
/* * Copyright 2017 Peter Kenji Yamanaka * * 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.pyamsoft.powermanager.service.job import android.support.annotation.CheckResult import com.evernote.android.job.util.support.PersistableBundleCompat import com.pyamsoft.powermanager.base.preference.AirplanePreferences import com.pyamsoft.powermanager.base.preference.BluetoothPreferences import com.pyamsoft.powermanager.base.preference.DataPreferences import com.pyamsoft.powermanager.base.preference.DataSaverPreferences import com.pyamsoft.powermanager.base.preference.DozePreferences import com.pyamsoft.powermanager.base.preference.PhonePreferences import com.pyamsoft.powermanager.base.preference.SyncPreferences import com.pyamsoft.powermanager.base.preference.WifiPreferences import com.pyamsoft.powermanager.job.JobQueuer import com.pyamsoft.powermanager.job.JobRunner import com.pyamsoft.powermanager.model.StateModifier import com.pyamsoft.powermanager.model.StateObserver import io.reactivex.Completable import io.reactivex.Scheduler import io.reactivex.disposables.CompositeDisposable import timber.log.Timber import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit.SECONDS internal abstract class ManageJobRunner(private val jobQueuer: JobQueuer, private val chargingObserver: StateObserver, private val wearableObserver: StateObserver, private val wifiModifier: StateModifier, private val dataModifier: StateModifier, private val bluetoothModifier: StateModifier, private val syncModifier: StateModifier, private val dozeModifier: StateModifier, private val airplaneModifier: StateModifier, private val dataSaverModifier: StateModifier, private val wifiPreferences: WifiPreferences, private val dataPreferences: DataPreferences, private val bluetoothPreferences: BluetoothPreferences, private val syncPreferences: SyncPreferences, private val airplanePreferences: AirplanePreferences, private val dozePreferences: DozePreferences, private val dataSaverPreferences: DataSaverPreferences, private val phonePreferences: PhonePreferences, private val phoneObserver: StateObserver, private val subScheduler: Scheduler) : JobRunner { private val composite = CompositeDisposable() private val wifiConditions = object : ManageConditions { override val tag: String get() = "Wifi" override val ignoreCharging: Boolean get() = wifiPreferences.ignoreChargingWifi override val ignoreWearable: Boolean get() = wifiPreferences.ignoreWearWifi override val managed: Boolean get() = wifiPreferences.wifiManaged override val original: Boolean get() = wifiPreferences.originalWifi override val periodic: Boolean get() = wifiPreferences.periodicWifi } private val dozeConditions = object : ManageConditions { override val tag: String get() = "Doze Mode" override val ignoreCharging: Boolean get() = dozePreferences.ignoreChargingDoze override val ignoreWearable: Boolean get() = dozePreferences.ignoreWearDoze override val managed: Boolean get() = dozePreferences.dozeManaged override val original: Boolean get() = dozePreferences.originalDoze override val periodic: Boolean get() = dozePreferences.periodicDoze } private val airplaneConditions = object : ManageConditions { override val tag: String get() = "Airplane Mode" override val managed: Boolean get() = airplanePreferences.airplaneManaged override val ignoreCharging: Boolean get() = airplanePreferences.ignoreChargingAirplane override val ignoreWearable: Boolean get() = airplanePreferences.ignoreWearAirplane override val original: Boolean get() = airplanePreferences.originalAirplane override val periodic: Boolean get() = airplanePreferences.periodicAirplane } private val dataConditions = object : ManageConditions { override val tag: String get() = "Data" override val ignoreCharging: Boolean get() = dataPreferences.ignoreChargingData override val ignoreWearable: Boolean get() = dataPreferences.ignoreWearData override val managed: Boolean get() = dataPreferences.dataManaged override val original: Boolean get() = dataPreferences.originalData override val periodic: Boolean get() = dataPreferences.periodicData } private val bluetoothConditions = object : ManageConditions { override val tag: String get() = "Bluetooth" override val ignoreCharging: Boolean get() = bluetoothPreferences.ignoreChargingBluetooth override val ignoreWearable: Boolean get() = bluetoothPreferences.ignoreWearBluetooth override val managed: Boolean get() = bluetoothPreferences.bluetoothManaged override val original: Boolean get() = bluetoothPreferences.originalBluetooth override val periodic: Boolean get() = bluetoothPreferences.periodicBluetooth } private val syncConditions = object : ManageConditions { override val tag: String get() = "Sync" override val ignoreCharging: Boolean get() = syncPreferences.ignoreChargingSync override val ignoreWearable: Boolean get() = syncPreferences.ignoreWearSync override val managed: Boolean get() = syncPreferences.syncManaged override val original: Boolean get() = syncPreferences.originalSync override val periodic: Boolean get() = syncPreferences.periodicSync } private val dataSaverConditions = object : ManageConditions { override val tag: String get() = "Data Saver" override val ignoreCharging: Boolean get() = dataSaverPreferences.ignoreChargingDataSaver override val ignoreWearable: Boolean get() = dataSaverPreferences.ignoreWearDataSaver override val managed: Boolean get() = dataSaverPreferences.dataSaverManaged override val original: Boolean get() = dataSaverPreferences.originalDataSaver override val periodic: Boolean get() = dataSaverPreferences.periodicDataSaver } @CheckResult private fun runJob(tag: String, screenOn: Boolean, firstRun: Boolean): Boolean { checkTag(tag) if (screenOn) { return runEnableJob(tag, firstRun) } else { return runDisableJob(tag, firstRun) } } private fun checkTag(tag: String) { if (tag != JobQueuer.ENABLE_TAG && tag == JobQueuer.ENABLE_TAG) { throw IllegalArgumentException("Illegal tag for JobRunner: " + tag) } } @CheckResult private fun runEnableJob(tag: String, firstRun: Boolean): Boolean { var didSomething = false val latch = CountDownLatch(6) didSomething = disable(firstRun, latch, isCharging = false, isWearableConnected = false, modifier = dozeModifier, conditions = dozeConditions) || didSomething if (isStopped) { Timber.w("%s: Stopped early", tag) return false } didSomething = disable(firstRun, latch, isCharging = false, isWearableConnected = false, modifier = airplaneModifier, conditions = airplaneConditions) || didSomething if (isStopped) { Timber.w("%s: Stopped early", tag) return false } didSomething = disable(firstRun, latch, isCharging = false, isWearableConnected = false, modifier = dataSaverModifier, conditions = dataSaverConditions) || didSomething if (isStopped) { Timber.w("%s: Stopped early", tag) return false } didSomething = enable(firstRun, latch, isCharging = false, isWearableConnected = false, modifier = wifiModifier, conditions = wifiConditions) || didSomething if (isStopped) { Timber.w("%s: Stopped early", tag) return false } didSomething = enable(firstRun, latch, isCharging = false, isWearableConnected = false, modifier = dataModifier, conditions = dataConditions) || didSomething if (isStopped) { Timber.w("%s: Stopped early", tag) return false } didSomething = enable(firstRun, latch, isCharging = false, isWearableConnected = false, modifier = bluetoothModifier, conditions = bluetoothConditions) || didSomething if (isStopped) { Timber.w("%s: Stopped early", tag) return false } didSomething = enable(firstRun, latch, isCharging = false, isWearableConnected = false, modifier = syncModifier, conditions = syncConditions) || didSomething if (isStopped) { Timber.w("%s: Stopped early", tag) return false } await(latch) return isJobRepeatRequired(didSomething) } private fun enable(firstRun: Boolean, latch: CountDownLatch, isCharging: Boolean, isWearableConnected: Boolean, modifier: StateModifier, conditions: ManageConditions): Boolean { if (isCharging && conditions.ignoreCharging) { Timber.w("Do not disable %s while device is charging", conditions.tag) latch.countDown() return false } else if (isWearableConnected && conditions.ignoreWearable) { Timber.w("Do not disable %s while wearable is connected", conditions.tag) latch.countDown() return false } else if (conditions.managed && conditions.original && (firstRun || conditions.periodic)) { composite.add(Completable.fromAction { modifier.set() }.subscribeOn(subScheduler).observeOn(subScheduler).doAfterTerminate { latch.countDown() }.subscribe({ Timber.d("ENABLE: %s", conditions.tag) }, { Timber.e(it, "Error enabling %s", conditions.tag) })) return true } else { Timber.w("Not managed: %s", conditions.tag) latch.countDown() return false } } private fun disable(firstRun: Boolean, latch: CountDownLatch, isCharging: Boolean, isWearableConnected: Boolean, modifier: StateModifier, conditions: ManageConditions): Boolean { if (isCharging && conditions.ignoreCharging) { Timber.w("Do not disable %s while device is charging", conditions.tag) latch.countDown() return false } else if (isWearableConnected && conditions.ignoreWearable) { Timber.w("Do not disable %s while wearable is connected", conditions.tag) latch.countDown() return false } else if (conditions.managed && conditions.original && (firstRun || conditions.periodic)) { composite.add(Completable.fromAction { modifier.unset() }.subscribeOn(subScheduler).observeOn(subScheduler).doAfterTerminate { latch.countDown() }.subscribe({ Timber.d("DISABLE: %s", conditions.tag) }, { Timber.e(it, "Error disabling %s", conditions.tag) })) return true } else { Timber.w("Not managed: %s", conditions.tag) latch.countDown() return false } } @CheckResult private fun runDisableJob(tag: String, firstRun: Boolean): Boolean { if (phonePreferences.isIgnoreDuringPhoneCall()) { if (!phoneObserver.unknown()) { if (phoneObserver.enabled()) { Timber.w("Do not manage, device is in a phone call.") return false } } } var didSomething = false val isCharging = chargingObserver.enabled() val isWearableConnected = wearableObserver.enabled() val latch = CountDownLatch(6) didSomething = disable(firstRun, latch, isCharging, isWearableConnected, modifier = wifiModifier, conditions = wifiConditions) || didSomething if (isStopped) { Timber.w("%s: Stopped early", tag) return false } didSomething = disable(firstRun, latch, isCharging, isWearableConnected, modifier = dataModifier, conditions = dataConditions) || didSomething if (isStopped) { Timber.w("%s: Stopped early", tag) return false } didSomething = disable(firstRun, latch, isCharging, isWearableConnected, modifier = bluetoothModifier, conditions = bluetoothConditions) || didSomething if (isStopped) { Timber.w("%s: Stopped early", tag) return false } didSomething = disable(firstRun, latch, isCharging, isWearableConnected, modifier = syncModifier, conditions = syncConditions) || didSomething if (isStopped) { Timber.w("%s: Stopped early", tag) return false } didSomething = enable(firstRun, latch, isCharging, isWearableConnected, modifier = airplaneModifier, conditions = airplaneConditions) || didSomething if (isStopped) { Timber.w("%s: Stopped early", tag) return false } didSomething = enable(firstRun, latch, isCharging, isWearableConnected, modifier = dozeModifier, conditions = dozeConditions) || didSomething if (isStopped) { Timber.w("%s: Stopped early", tag) return false } didSomething = enable(firstRun, latch, isCharging, isWearableConnected, modifier = dataSaverModifier, conditions = dataSaverConditions) || didSomething if (isStopped) { Timber.w("%s: Stopped early", tag) return false } await(latch) return isJobRepeatRequired(didSomething) } private fun await(latch: CountDownLatch) { Timber.d("Wait for Latch... (30 seconds)") try { latch.await(30L, SECONDS) } catch (e: InterruptedException) { Timber.e(e, "Timer was interrupted") } Timber.d("Job complete, clear composite") composite.clear() } @CheckResult private fun isJobRepeatRequired(didSomething: Boolean): Boolean { val repeatWifi = wifiPreferences.wifiManaged && wifiPreferences.periodicWifi val repeatData = dataPreferences.dataManaged && dataPreferences.periodicData val repeatBluetooth = bluetoothPreferences.bluetoothManaged && bluetoothPreferences.periodicBluetooth val repeatSync = syncPreferences.syncManaged && syncPreferences.periodicSync val repeatAirplane = airplanePreferences.airplaneManaged && airplanePreferences.periodicAirplane val repeatDoze = dozePreferences.dozeManaged && dozePreferences.periodicDoze val repeatDataSaver = dataSaverPreferences.dataSaverManaged && dataSaverPreferences.periodicDataSaver return didSomething && (repeatWifi || repeatData || repeatBluetooth || repeatSync || repeatAirplane || repeatDoze || repeatDataSaver) } private fun repeatIfRequired(tag: String, screenOn: Boolean, windowOnTime: Long, windowOffTime: Long) { val newDelayTime: Long // Switch them if (screenOn) { newDelayTime = windowOnTime } else { newDelayTime = windowOffTime } val newTag: String if (tag == JobQueuer.DISABLE_TAG) { newTag = JobQueuer.ENABLE_TAG } else { newTag = JobQueuer.DISABLE_TAG } val entry = ManageJobQueuerEntry(tag = newTag, firstRun = false, oneShot = false, screenOn = !screenOn, delay = newDelayTime, repeatingOffWindow = windowOffTime, repeatingOnWindow = windowOnTime) jobQueuer.queue(entry) } /** * Runs the Job. Called either by managed jobs or directly by the JobQueuer */ override fun run(tag: String, extras: PersistableBundleCompat) { val screenOn = extras.getBoolean( ManageJobQueuerEntry.KEY_SCREEN, true) val windowOnTime = extras.getLong( ManageJobQueuerEntry.KEY_ON_WINDOW, 0) val windowOffTime = extras.getLong( ManageJobQueuerEntry.KEY_OFF_WINDOW, 0) val oneshot = extras.getBoolean( ManageJobQueuerEntry.KEY_ONESHOT, false) val firstRun = extras.getBoolean( ManageJobQueuerEntry.KEY_FIRST_RUN, false) if (runJob(tag, screenOn, firstRun) && !oneshot) { repeatIfRequired(tag, screenOn, windowOnTime, windowOffTime) } } /** * Override in the actual ManagedJobs to call Job.isCancelled(); * If it is not a managed job it never isStopped, always run to completion */ @get:CheckResult internal abstract val isStopped: Boolean private interface ManageConditions { val tag: String @get:CheckResult get val ignoreCharging: Boolean @get:CheckResult get val ignoreWearable: Boolean @get:CheckResult get val managed: Boolean @get:CheckResult get val original: Boolean @get:CheckResult get val periodic: Boolean @get:CheckResult get } }
apache-2.0
b74851d84a532a14ce29120398bd480d
37.668981
137
0.715355
4.989546
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/timeline/meta/TimelineSelector.kt
1
5831
/* * Copyright (c) 2016 yvolk (Yuri Volkov), http://yurivolkov.com * * 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.andstatus.app.timeline.meta import android.content.Intent import android.os.Bundle import android.provider.BaseColumns import android.view.View import android.widget.AdapterView import android.widget.AdapterView.OnItemClickListener import android.widget.TextView import androidx.fragment.app.FragmentActivity import org.andstatus.app.ActivityRequestCode import org.andstatus.app.IntentExtra import org.andstatus.app.R import org.andstatus.app.account.MyAccount import org.andstatus.app.net.social.Actor import org.andstatus.app.origin.Origin import org.andstatus.app.util.TriState import org.andstatus.app.view.MySimpleAdapter import org.andstatus.app.view.SelectorDialog import java.util.* import java.util.stream.Collectors /** * @author [email protected] */ class TimelineSelector : SelectorDialog() { override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) val arguments = requireArguments() setTitle(R.string.dialog_title_select_timeline) val currentTimeline = myContext.timelines.fromId(arguments.getLong(IntentExtra.TIMELINE_ID.key, 0)) val currentMyAccount = myContext.accounts.fromAccountName( arguments.getString(IntentExtra.ACCOUNT_NAME.key)) val timelines = myContext.timelines.filter( true, TriState.fromBoolean(currentTimeline.isCombined), TimelineType.UNKNOWN, currentMyAccount.actor, Origin.EMPTY).collect(Collectors.toSet()) if (!currentTimeline.isCombined && currentMyAccount.isValid) { timelines.addAll(myContext.timelines.filter( true, TriState.fromBoolean(currentTimeline.isCombined), TimelineType.UNKNOWN, Actor.EMPTY, currentMyAccount.origin).collect(Collectors.toSet())) } if (timelines.isEmpty()) { returnSelectedTimeline(Timeline.EMPTY) return } else if (timelines.size == 1) { returnSelectedTimeline(timelines.iterator().next()) return } val viewItems: MutableList<ManageTimelinesViewItem> = ArrayList() for (timeline2 in timelines) { val viewItem = ManageTimelinesViewItem(myContext, timeline2, myContext.accounts.currentAccount, true) viewItems.add(viewItem) } viewItems.sortWith(ManageTimelinesViewItemComparator(R.id.displayedInSelector, sortDefault = true, isTotal = false)) removeDuplicates(viewItems) setListAdapter(newListAdapter(viewItems)) listView?.onItemClickListener = OnItemClickListener { _: AdapterView<*>?, view: View, _: Int, _: Long -> val timelineId = (view.findViewById<View?>(R.id.id) as TextView).text.toString().toLong() returnSelectedTimeline(myContext.timelines.fromId(timelineId)) } } private fun removeDuplicates(timelines: MutableList<ManageTimelinesViewItem>) { val unique: MutableMap<String?, ManageTimelinesViewItem?> = HashMap() var removeSomething = false for (viewItem in timelines) { val key: String = viewItem.timelineTitle.toString() if (unique.containsKey(key)) { removeSomething = true } else { unique[key] = viewItem } } if (removeSomething) { timelines.retainAll(unique.values) } } private fun newListAdapter(listData: MutableList<ManageTimelinesViewItem>): MySimpleAdapter { val list: MutableList<MutableMap<String, String>> = ArrayList() val syncText = getText(R.string.synced_abbreviated).toString() for (viewItem in listData) { val map: MutableMap<String, String> = HashMap() map[KEY_VISIBLE_NAME] = viewItem.timelineTitle.toString() map[KEY_SYNC_AUTO] = if (viewItem.timeline.isSyncedAutomatically()) syncText else "" map[BaseColumns._ID] = viewItem.timeline.getId().toString() list.add(map) } return MySimpleAdapter(activity ?: throw IllegalStateException("No activity"), list, R.layout.accountlist_item, arrayOf(KEY_VISIBLE_NAME, KEY_SYNC_AUTO, BaseColumns._ID), intArrayOf(R.id.visible_name, R.id.sync_auto, R.id.id), true) } private fun returnSelectedTimeline(timeline: Timeline) { returnSelected(Intent().putExtra(IntentExtra.TIMELINE_ID.key, timeline.getId())) } companion object { private val KEY_VISIBLE_NAME: String = "visible_name" private val KEY_SYNC_AUTO: String = "sync_auto" fun selectTimeline(activity: FragmentActivity, requestCode: ActivityRequestCode, timeline: Timeline, currentMyAccount: MyAccount) { val selector: SelectorDialog = TimelineSelector() selector.setRequestCode(requestCode) selector.arguments?.putLong(IntentExtra.TIMELINE_ID.key, timeline.getId()) selector.arguments?.putString(IntentExtra.ACCOUNT_NAME.key, currentMyAccount.getAccountName()) selector.show(activity) } } }
apache-2.0
8cceb6f769dc60445bd5bddabcd0edc6
44.554688
124
0.682902
4.79129
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/modules/classificator/characteristics/ClassificationCharacteristicsFragment.kt
2
4498
package ru.fantlab.android.ui.modules.classificator.characteristics import android.content.Context import android.os.Bundle import android.view.View import androidx.annotation.StringRes import androidx.recyclerview.widget.RecyclerView import kotlinx.android.synthetic.main.micro_grid_refresh_list.* import kotlinx.android.synthetic.main.state_layout.* import ru.fantlab.android.R import ru.fantlab.android.data.dao.model.Classificator import ru.fantlab.android.data.dao.model.ClassificatorModel import ru.fantlab.android.helper.BundleConstant import ru.fantlab.android.helper.Bundler import ru.fantlab.android.ui.adapter.viewholder.ClassificatorViewHolder import ru.fantlab.android.ui.base.BaseFragment import ru.fantlab.android.ui.modules.classificator.ClassificatorPagerMvp import ru.fantlab.android.ui.widgets.treeview.TreeNode import ru.fantlab.android.ui.widgets.treeview.TreeViewAdapter import java.util.* class ClassificationCharacteristicsFragment : BaseFragment<ClassificationCharacteristicsMvp.View, ClassificationCharacteristicsPresenter>(), ClassificationCharacteristicsMvp.View { private var pagerCallback: ClassificatorPagerMvp.View? = null var selectedItems = 0 override fun fragmentLayout() = R.layout.micro_grid_refresh_list override fun providePresenter() = ClassificationCharacteristicsPresenter() override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) { presenter.onFragmentCreated(arguments!!) } override fun onInitViews(classificators: ArrayList<ClassificatorModel>) { hideProgress() fastScroller.attachRecyclerView(recycler) refresh.setOnRefreshListener(this) val nodes = arrayListOf<TreeNode<*>>() classificators.forEach { val root = TreeNode(Classificator(it.name, it.descr, it.id)) nodes.add(root) work(it, root, false) } val adapter = TreeViewAdapter(nodes, Arrays.asList(ClassificatorViewHolder())) recycler.adapter = adapter adapter.setOnTreeNodeListener(object : TreeViewAdapter.OnTreeNodeListener { override fun onSelected(extra: Int, add: Boolean) { if (add) selectedItems++ else selectedItems-- onSetTabCount(selectedItems) pagerCallback?.onSelected(extra, add) } override fun onClick(node: TreeNode<*>, holder: RecyclerView.ViewHolder): Boolean { val viewHolder = holder as ClassificatorViewHolder.ViewHolder val state = viewHolder.checkbox.isChecked if (!node.isLeaf) { onToggle(!node.isExpand, holder) if (!state && !node.isExpand) { viewHolder.checkbox.isChecked = true } } else { viewHolder.checkbox.isChecked = !state } return false } override fun onToggle(isExpand: Boolean, holder: RecyclerView.ViewHolder) { val viewHolder = holder as ClassificatorViewHolder.ViewHolder val ivArrow = viewHolder.arrow val rotateDegree = if (isExpand) 90.0f else -90.0f ivArrow.animate().rotationBy(rotateDegree) .start() } }) } private fun work(it: ClassificatorModel, root: TreeNode<Classificator>, lastLevel: Boolean) { if (it.childs != null) { val counter = root.childList.size - 1 it.childs.forEach { val child = TreeNode(Classificator(it.name, it.descr, it.id)) if (lastLevel) { val childB = TreeNode(Classificator(it.name, it.descr, it.id)) root.childList[counter].addChild(childB) } else root.addChild(child) work(it, root, true) } } } override fun showProgress(@StringRes resId: Int, cancelable: Boolean) { refresh.isRefreshing = true stateLayout.showProgress() } override fun hideProgress() { refresh.isRefreshing = false stateLayout.hideProgress() } override fun showErrorMessage(msgRes: String?) { hideProgress() super.showErrorMessage(msgRes) } override fun showMessage(titleRes: Int, msgRes: Int) { hideProgress() super.showMessage(titleRes, msgRes) } override fun onClick(v: View?) { onRefresh() } override fun onRefresh() { hideProgress() } fun onSetTabCount(count: Int) { pagerCallback?.onSetBadge(1, count) } override fun onAttach(context: Context) { super.onAttach(context) if (context is ClassificatorPagerMvp.View) { pagerCallback = context } } override fun onDetach() { pagerCallback = null super.onDetach() } companion object { fun newInstance(workId: Int): ClassificationCharacteristicsFragment { val view = ClassificationCharacteristicsFragment() view.arguments = Bundler.start().put(BundleConstant.EXTRA, workId).end() return view } } }
gpl-3.0
64a398d41b9c4e5dd67c965b15f960e1
28.025806
96
0.753224
3.945614
false
false
false
false
hpedrorodrigues/GZMD
app/src/main/kotlin/com/hpedrorodrigues/gzmd/preferences/GizmodoPreferences.kt
1
1793
/* * Copyright 2016 Pedro Rodrigues * * 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.hpedrorodrigues.gzmd.preferences import android.content.Context import android.preference.PreferenceManager import javax.inject.Inject class GizmodoPreferences { private lateinit var context: Context @Inject constructor(context: Context) { this.context = context } private fun preferences() = PreferenceManager.getDefaultSharedPreferences(context) fun getInt(name: String, default: Int) = PreferenceManager .getDefaultSharedPreferences(context).getInt(name, default) fun getInt(name: String) = getInt(name, -1) fun putInt(name: String, value: Int) = preferences().edit().putInt(name, value).apply() fun getLong(name: String) = getLong(name, -1L) fun getLong(name: String, default: Long) = PreferenceManager .getDefaultSharedPreferences(context).getLong(name, default) fun putLong(name: String, value: Long) = preferences().edit().putLong(name, value).apply() fun getBoolean(name: String) = PreferenceManager .getDefaultSharedPreferences(context).getBoolean(name, false) fun putBoolean(name: String, value: Boolean) = preferences().edit().putBoolean(name, value).apply() }
apache-2.0
15731a08a56be72e16b47dd484fc6660
33.5
103
0.726715
4.460199
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/data/elementfilter/filters/HasKeyLike.kt
1
531
package de.westnordost.streetcomplete.data.elementfilter.filters import de.westnordost.osmapi.map.data.Element import de.westnordost.streetcomplete.data.elementfilter.quoteIfNecessary /** ~key(word)? */ class HasKeyLike(key: String) : ElementFilter { val key = key.toRegex() override fun toOverpassQLString() = "[" + "~" + "^(${key.pattern})$".quoteIfNecessary() + " ~ '.*']" override fun toString() = toOverpassQLString() override fun matches(obj: Element?) = obj?.tags?.keys?.find { it.matches(key) } != null }
gpl-3.0
d122d69ae6c9a74edc9b16f2e05bf497
39.923077
104
0.704331
3.992481
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xdm/main/uk/co/reecedunn/intellij/plugin/xdm/module/path/XdmModuleType.kt
1
1974
/* * Copyright (C) 2019-2021 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xdm.module.path enum class XdmModuleType(val extensions: Array<String>) { DotNet(arrayOf()), // Saxon DTD(arrayOf()), // EXPath Package Java(arrayOf()), // BaseX, eXist-db, Saxon NVDL(arrayOf()), // EXPath Package RelaxNG(arrayOf()), // EXPath Package RelaxNGCompact(arrayOf()), // EXPath Package Resource(arrayOf()), // EXPath Package Schematron(arrayOf()), // EXPath Package XMLSchema(arrayOf(".xsd")), // Schema Aware Feature, EXPath Package XPath(arrayOf()), // XSLT XProc(arrayOf()), // EXPath Package XQuery(arrayOf(".xq", ".xqm", ".xqy", ".xql", ".xqu", ".xquery")), // Module Feature, EXPath Package XSLT(arrayOf()); // MarkLogic, EXPath Package companion object { val JAVA: Array<XdmModuleType> = arrayOf(Java) val MODULE: Array<XdmModuleType> = arrayOf(XQuery, Java, DotNet) val MODULE_OR_SCHEMA: Array<XdmModuleType> = arrayOf(XQuery, XMLSchema, Java, DotNet) val NONE: Array<XdmModuleType> = arrayOf() val XPATH_OR_XQUERY: Array<XdmModuleType> = arrayOf(XPath, XQuery) val XQUERY: Array<XdmModuleType> = arrayOf(XQuery) val RESOURCE: Array<XdmModuleType> = arrayOf(Resource) val SCHEMA: Array<XdmModuleType> = arrayOf(XMLSchema) val STYLESHEET: Array<XdmModuleType> = arrayOf(XSLT) } }
apache-2.0
21d0f3b441e1d49116c86b52c451c393
43.863636
104
0.68541
4.1125
false
false
false
false
rhdunn/xquery-intellij-plugin
src/main/java/uk/co/reecedunn/intellij/plugin/xpath/codeInspection/ijvs/IJVS0004.kt
1
3274
/* * Copyright (C) 2016-2017 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xpath.codeInspection.ijvs import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.psi.PsiFile import com.intellij.psi.util.elementType import com.intellij.util.SmartList import uk.co.reecedunn.intellij.plugin.core.codeInspection.Inspection import uk.co.reecedunn.intellij.plugin.core.sequences.walkTree import uk.co.reecedunn.intellij.plugin.intellij.lang.Saxon import uk.co.reecedunn.intellij.plugin.intellij.lang.Version import uk.co.reecedunn.intellij.plugin.intellij.resources.XQueryPluginBundle import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathMapConstructorEntry import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryModule import uk.co.reecedunn.intellij.plugin.xquery.project.settings.XQueryProjectSettings import xqt.platform.intellij.xpath.XPathTokenProvider class IJVS0004 : Inspection("ijvs/IJVS0004.md", IJVS0004::class.java.classLoader) { private fun conformsTo(element: XPathMapConstructorEntry, productVersion: Version?): Boolean { val conformanceElement = element.separator if (conformanceElement === element.firstChild) { return true } val isSaxonExtension = productVersion?.kind === Saxon && productVersion.value >= 9.4 && productVersion.value <= 9.7 return conformanceElement.elementType === XPathTokenProvider.AssignEquals == isSaxonExtension } override fun checkFile(file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean): Array<ProblemDescriptor>? { if (file !is XQueryModule) return null val settings = XQueryProjectSettings.getInstance(file.getProject()) val productVersion: Version = settings.productVersion val descriptors = SmartList<ProblemDescriptor>() file.walkTree().filterIsInstance<XPathMapConstructorEntry>().forEach { element -> if (!conformsTo(element, productVersion)) { val context = element.separator val description = XQueryPluginBundle.message("inspection.XPST0003.map-constructor-entry.message") descriptors.add( manager.createProblemDescriptor( context, description, null as LocalQuickFix?, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly ) ) } } return descriptors.toTypedArray() } }
apache-2.0
de1d8cb9a38a5a18eb78ea3f0b42ac5d
45.771429
119
0.718082
4.886567
false
false
false
false
wix/react-native-navigation
lib/android/app/src/main/java/com/reactnativenavigation/viewcontrollers/stack/StackAnimator.kt
1
12236
package com.reactnativenavigation.viewcontrollers.stack import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.AnimatorSet import android.content.Context import androidx.annotation.RestrictTo import androidx.annotation.VisibleForTesting import androidx.core.animation.doOnEnd import com.reactnativenavigation.options.FadeAnimation import com.reactnativenavigation.options.Options import com.reactnativenavigation.options.StackAnimationOptions import com.reactnativenavigation.options.params.Bool import com.reactnativenavigation.utils.awaitRender import com.reactnativenavigation.utils.resetViewProperties import com.reactnativenavigation.viewcontrollers.common.BaseAnimator import com.reactnativenavigation.viewcontrollers.viewcontroller.ViewController import com.reactnativenavigation.views.element.TransitionAnimatorCreator import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import java.util.* open class StackAnimator @JvmOverloads constructor( context: Context, private val transitionAnimatorCreator: TransitionAnimatorCreator = TransitionAnimatorCreator() ) : BaseAnimator(context) { @VisibleForTesting val runningPushAnimations: MutableMap<ViewController<*>, AnimatorSet> = HashMap() @VisibleForTesting val runningPopAnimations: MutableMap<ViewController<*>, AnimatorSet> = HashMap() @VisibleForTesting val runningSetRootAnimations: MutableMap<ViewController<*>, AnimatorSet> = HashMap() fun cancelPushAnimations() = runningPushAnimations.values.forEach(Animator::cancel) open fun isChildInTransition(child: ViewController<*>?): Boolean { return runningPushAnimations.containsKey(child) || runningPopAnimations.containsKey(child) || runningSetRootAnimations.containsKey(child) } fun cancelAllAnimations() { runningPushAnimations.clear() runningPopAnimations.clear() runningSetRootAnimations.clear() } fun setRoot( appearing: ViewController<*>, disappearing: ViewController<*>, options: Options, additionalAnimations: List<Animator>, onAnimationEnd: Runnable ) { val set = createSetRootAnimator(appearing, onAnimationEnd) runningSetRootAnimations[appearing] = set val setRoot = options.animations.setStackRoot if (setRoot.waitForRender.isTrue) { appearing.view.alpha = 0f appearing.addOnAppearedListener { appearing.view.alpha = 1f animateSetRoot(set, setRoot, appearing, disappearing, additionalAnimations) } } else { animateSetRoot(set, setRoot, appearing, disappearing, additionalAnimations) } } fun push( appearing: ViewController<*>, disappearing: ViewController<*>, resolvedOptions: Options, additionalAnimations: List<Animator>, onAnimationEnd: Runnable ) { val set = createPushAnimator(appearing, onAnimationEnd) runningPushAnimations[appearing] = set if (resolvedOptions.animations.push.sharedElements.hasValue()) { pushWithElementTransition(appearing, disappearing, resolvedOptions, set) } else { pushWithoutElementTransitions(appearing, disappearing, resolvedOptions, set, additionalAnimations) } } open fun pop( appearing: ViewController<*>, disappearing: ViewController<*>, disappearingOptions: Options, additionalAnimations: List<Animator>, onAnimationEnd: Runnable ) { if (runningPushAnimations.containsKey(disappearing)) { runningPushAnimations[disappearing]!!.cancel() onAnimationEnd.run() } else { animatePop( appearing, disappearing, disappearingOptions, additionalAnimations, onAnimationEnd ) } } private fun animatePop( appearing: ViewController<*>, disappearing: ViewController<*>, disappearingOptions: Options, additionalAnimations: List<Animator>, onAnimationEnd: Runnable ) { GlobalScope.launch(Dispatchers.Main.immediate) { val set = createPopAnimator(disappearing, onAnimationEnd) if (disappearingOptions.animations.pop.sharedElements.hasValue()) { popWithElementTransitions(appearing, disappearing, disappearingOptions, set) } else { popWithoutElementTransitions(appearing, disappearing, disappearingOptions, set, additionalAnimations) } } } private suspend fun popWithElementTransitions(appearing: ViewController<*>, disappearing: ViewController<*>, resolvedOptions: Options, set: AnimatorSet) { val pop = resolvedOptions.animations.pop val fade = if (pop.content.exit.isFadeAnimation()) pop else FadeAnimation val transitionAnimators = transitionAnimatorCreator.create(pop, fade.content.exit, disappearing, appearing) set.playTogether(fade.content.exit.getAnimation(disappearing.view), transitionAnimators) transitionAnimators.listeners.forEach { listener: Animator.AnimatorListener -> set.addListener(listener) } transitionAnimators.removeAllListeners() set.start() } private fun popWithoutElementTransitions( appearing: ViewController<*>, disappearing: ViewController<*>, disappearingOptions: Options, set: AnimatorSet, additionalAnimations: List<Animator> ) { val pop = disappearingOptions.animations.pop val animators = mutableListOf(pop.content.exit.getAnimation(disappearing.view, getDefaultPopAnimation(disappearing.view))) animators.addAll(additionalAnimations) if (pop.content.enter.hasValue()) { animators.add(pop.content.enter.getAnimation(appearing.view)) } set.playTogether(animators.toList()) set.start() } private fun createPopAnimator(disappearing: ViewController<*>, onAnimationEnd: Runnable): AnimatorSet { val set = createAnimatorSet() runningPopAnimations[disappearing] = set set.addListener(object : AnimatorListenerAdapter() { private var cancelled = false override fun onAnimationCancel(animation: Animator) { if (!runningPopAnimations.contains(disappearing)) return cancelled = true runningPopAnimations.remove(disappearing) } override fun onAnimationEnd(animation: Animator) { if (!runningPopAnimations.contains(disappearing)) return runningPopAnimations.remove(disappearing) if (!cancelled) onAnimationEnd.run() } }) return set } private fun createPushAnimator(appearing: ViewController<*>, onAnimationEnd: Runnable): AnimatorSet { val set = createAnimatorSet() set.addListener(object : AnimatorListenerAdapter() { private var isCancelled = false override fun onAnimationCancel(animation: Animator) { if (!runningPushAnimations.contains(appearing)) return isCancelled = true runningPushAnimations.remove(appearing) onAnimationEnd.run() } override fun onAnimationEnd(animation: Animator) { if (!runningPushAnimations.contains(appearing)) return if (!isCancelled) { runningPushAnimations.remove(appearing) onAnimationEnd.run() } } }) return set } private fun createSetRootAnimator(appearing: ViewController<*>, onAnimationEnd: Runnable): AnimatorSet { val set = createAnimatorSet() set.addListener(object : AnimatorListenerAdapter() { private var isCancelled = false override fun onAnimationCancel(animation: Animator) { if (!runningSetRootAnimations.contains(appearing)) return isCancelled = true runningSetRootAnimations.remove(appearing) onAnimationEnd.run() } override fun onAnimationEnd(animation: Animator) { if (!runningSetRootAnimations.contains(appearing)) return if (!isCancelled) { runningSetRootAnimations.remove(appearing) onAnimationEnd.run() } } }) return set } private fun pushWithElementTransition( appearing: ViewController<*>, disappearing: ViewController<*>, options: Options, set: AnimatorSet ) = GlobalScope.launch(Dispatchers.Main.immediate) { appearing.setWaitForRender(Bool(true)) appearing.view.alpha = 0f appearing.awaitRender() val fade = if (options.animations.push.content.enter.isFadeAnimation()) options.animations.push.content.enter else FadeAnimation.content.enter val transitionAnimators = transitionAnimatorCreator.create(options.animations.push, fade, disappearing, appearing) set.playTogether(fade.getAnimation(appearing.view), transitionAnimators) transitionAnimators.listeners.forEach { listener: Animator.AnimatorListener -> set.addListener(listener) } transitionAnimators.removeAllListeners() set.start() } private fun pushWithoutElementTransitions( appearing: ViewController<*>, disappearing: ViewController<*>, resolvedOptions: Options, set: AnimatorSet, additionalAnimations: List<Animator> ) { val push = resolvedOptions.animations.push if (push.waitForRender.isTrue) { appearing.view.alpha = 0f appearing.addOnAppearedListener { appearing.view.alpha = 1f animatePushWithoutElementTransitions(set, push, appearing, disappearing, additionalAnimations) } } else { animatePushWithoutElementTransitions(set, push, appearing, disappearing, additionalAnimations) } } private fun animatePushWithoutElementTransitions( set: AnimatorSet, push: StackAnimationOptions, appearing: ViewController<*>, disappearing: ViewController<*>, additionalAnimations: List<Animator> ) { val animators = mutableListOf(push.content.enter.getAnimation(appearing.view, getDefaultPushAnimation(appearing.view))) animators.addAll(additionalAnimations) if (push.content.exit.hasValue()) { animators.add(push.content.exit.getAnimation(disappearing.view)) } set.playTogether(animators.toList()) set.doOnEnd { if (!disappearing.isDestroyed) disappearing.view.resetViewProperties() } set.start() } private fun animateSetRoot( set: AnimatorSet, setRoot: StackAnimationOptions, appearing: ViewController<*>, disappearing: ViewController<*>, additionalAnimations: List<Animator> ) { val animators = mutableListOf(setRoot.content.enter.getAnimation( appearing.view, getDefaultSetStackRootAnimation(appearing.view) )) animators.addAll(additionalAnimations) if (setRoot.content.exit.hasValue()) { animators.add(setRoot.content.exit.getAnimation(disappearing.view)) } set.playTogether(animators.toList()) set.start() } protected open fun createAnimatorSet(): AnimatorSet = AnimatorSet() @RestrictTo(RestrictTo.Scope.TESTS) fun endPushAnimation(view: ViewController<*>) { if (runningPushAnimations.containsKey(view)) { runningPushAnimations[view]!!.end() } } }
mit
5d3ea65876ea80462bb9510d03d7754a
39.786667
158
0.658794
6.051434
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepic/droid/code/highlight/themes/Presets.kt
2
6639
package org.stepic.droid.code.highlight.themes import org.stepic.droid.R import org.stepic.droid.base.App import org.stepic.droid.util.ColorUtil object Presets { val themes = arrayOf( CodeTheme( name = App.getAppContext().getString(R.string.light_theme_name), syntax = CodeSyntax( plain = ColorUtil.getColorArgb(R.color.light_theme_plain), string = ColorUtil.getColorArgb(R.color.light_theme_string), keyword = ColorUtil.getColorArgb(R.color.light_theme_keyword), comment = ColorUtil.getColorArgb(R.color.light_theme_comment), type = ColorUtil.getColorArgb(R.color.light_theme_type), literal = ColorUtil.getColorArgb(R.color.light_theme_literal), punctuation = ColorUtil.getColorArgb(R.color.light_theme_punctuation), attributeName = ColorUtil.getColorArgb(R.color.light_theme_attribute_name), attributeValue = ColorUtil.getColorArgb(R.color.light_theme_attribute_value) ), background = ColorUtil.getColorArgb(R.color.light_theme_background), lineNumberBackground = ColorUtil.getColorArgb(R.color.light_theme_line_number_background), lineNumberText = ColorUtil.getColorArgb(R.color.light_theme_line_number_text), selectedLineBackground = ColorUtil.getColorArgb(R.color.light_theme_selected_line_background), lineNumberStroke = ColorUtil.getColorArgb(R.color.light_theme_line_number_stroke), bracketsHighlight = ColorUtil.getColorArgb(R.color.light_theme_brackets_highlight) ), CodeTheme( name = App.getAppContext().getString(R.string.github_theme_name), syntax = CodeSyntax( plain = ColorUtil.getColorArgb(R.color.github_theme_plain), string = ColorUtil.getColorArgb(R.color.github_theme_string), comment = ColorUtil.getColorArgb(R.color.github_theme_comment), type = ColorUtil.getColorArgb(R.color.github_theme_type), literal = ColorUtil.getColorArgb(R.color.github_theme_literal), attributeName = ColorUtil.getColorArgb(R.color.github_theme_attribute_name), attributeValue = ColorUtil.getColorArgb(R.color.github_theme_attribute_value) ), background = ColorUtil.getColorArgb(R.color.github_theme_background), lineNumberBackground = ColorUtil.getColorArgb(R.color.github_theme_line_number_background), lineNumberText = ColorUtil.getColorArgb(R.color.github_theme_line_number_text), selectedLineBackground = ColorUtil.getColorArgb(R.color.github_theme_selected_line_background), lineNumberStroke = ColorUtil.getColorArgb(R.color.github_theme_line_number_stroke) ), CodeTheme( name = App.getAppContext().getString(R.string.tomorrow_night_theme_name), syntax = CodeSyntax( plain = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_plain), string = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_string), keyword = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_keyword), comment = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_comment), type = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_type), literal = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_literal), tag = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_tag), attributeName = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_attribute_name), attributeValue = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_attribute_value), declaration = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_declaration) ), background = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_background), lineNumberBackground = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_line_number_background), lineNumberText = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_line_number_text), selectedLineBackground = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_selected_line_background), lineNumberStroke = ColorUtil.getColorArgb(R.color.tomorrow_night_theme_line_number_stroke) ), CodeTheme( name = App.getAppContext().getString(R.string.tranquil_heart_theme_name), syntax = CodeSyntax( plain = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_plain), string = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_string), keyword = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_keyword), comment = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_comment), type = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_type), literal = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_literal), tag = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_tag), attributeName = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_attribute_name), attributeValue = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_attribute_value), declaration = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_declaration) ), background = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_background), lineNumberBackground = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_line_number_background), lineNumberText = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_line_number_text), selectedLineBackground = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_selected_line_background), lineNumberStroke = ColorUtil.getColorArgb(R.color.tranquil_heart_theme_line_number_stroke) ) ) }
apache-2.0
e1b51dfebdabbf2c78ae8ded1a616b5a
75.321839
116
0.615454
4.817852
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/presentation/story_deeplink/StoryDeepLinkPresenter.kt
2
1415
package org.stepik.android.presentation.story_deeplink import io.reactivex.Scheduler import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.subscribeBy import org.stepic.droid.di.qualifiers.BackgroundScheduler import org.stepic.droid.di.qualifiers.MainScheduler import org.stepik.android.domain.story_deeplink.interactor.StoryDeepLinkInteractor import ru.nobird.android.presentation.base.PresenterBase import javax.inject.Inject class StoryDeepLinkPresenter @Inject constructor( private val storyDeepLinkInteractor: StoryDeepLinkInteractor, @BackgroundScheduler private val backgroundScheduler: Scheduler, @MainScheduler private val mainScheduler: Scheduler ) : PresenterBase<StoryDeepLinkView>() { private var state: StoryDeepLinkView.State = StoryDeepLinkView.State.Idle set(value) { field = value view?.setState(value) } fun onData(storyId: Long) { if (state != StoryDeepLinkView.State.Idle) return state = StoryDeepLinkView.State.Loading compositeDisposable += storyDeepLinkInteractor .getStoryTemplate(storyId) .observeOn(mainScheduler) .subscribeOn(backgroundScheduler) .subscribeBy( onSuccess = { state = StoryDeepLinkView.State.Success(it) }, onError = { state = StoryDeepLinkView.State.Error } ) } }
apache-2.0
f770c284c5a92b75d65558c25425cff7
33.536585
82
0.722968
5.089928
false
false
false
false
CzBiX/klog
src/main/kotlin/com/czbix/klog/http/HttpContextUtils.kt
1
3214
package com.czbix.klog.http import com.czbix.klog.common.Config import com.czbix.klog.database.dao.UserDao import com.czbix.klog.http.HttpContextKey.* import com.czbix.klog.http.SecureCookie.secureValue import com.czbix.klog.http.core.DefaultHttpPostRequestDecoder import com.czbix.klog.utils.now import io.netty.handler.codec.http.* import java.util.* import java.util.concurrent.TimeUnit inline fun <reified T> HttpContext.getWithType(key: HttpContextKey): T? { return get(key) as T? } inline fun <reified T : Any> HttpContext.getWithType(key: HttpContextKey, block: () -> T?): T? { val value = get(key) as T? return value ?: block()?.let { put(key, it) it } } val HttpContext.args: Map<String, String> get() { return getWithType(HANDLER_ARGS)!! } val HttpContext.request: HttpRequest get() { return getWithType(REQUEST)!! } val HttpContext.postData: DefaultHttpPostRequestDecoder get() { return DefaultHttpPostRequestDecoder(request) } val HttpContext.cookies: Map<String, Cookie> get() { return getWithType<Map<String, Cookie>>(COOKIES) { val cookiesHeader = request.headers().get(HttpHeaderNames.COOKIE)?.toString() if (cookiesHeader == null) return@getWithType mapOf() ServerCookieDecoder.decode(cookiesHeader).associateBy { it.name() } }!! } fun HttpContext.setCookie(name: String, value: String?, domain: String? = null, expiresDate: Date? = null, path: String = "/", expiresDays: Int? = null, httpOnly: Boolean = true, secureValue: Boolean = false) { var cookies = getWithType<MutableMap<String, Cookie>>(COOKIES_SET) if (cookies == null) { cookies = mutableMapOf() this[COOKIES_SET] = cookies } val cookie = DefaultCookie(name, value).let { if (secureValue) { it.secureValue = value } if (domain != null) { it.setDomain(domain) } var maxAge = if (expiresDays != null && expiresDate == null) { TimeUnit.DAYS.toSeconds(expiresDays.toLong()) } else if (expiresDate != null) { TimeUnit.MILLISECONDS.toSeconds(expiresDate.time - now()) } else 0 it.setMaxAge(maxAge) it.setPath(path) it.isHttpOnly = httpOnly if (Config.isCookieSecure()) { it.isSecure = true } return@let it } cookies[name] = cookie } var HttpContext.user: UserDao.User? get() { var user = getWithType<UserDao.User?>(USER) if (user == null) { val username = cookies["username"]?.secureValue if (username == null) { return null } user = UserDao.get(username) user?.let { this[USER] = it } } return user } set(value) { if (value == null) { remove(USER) setCookie("username", null, expiresDays = -365) } else { this[USER] = value setCookie("username", value.username, expiresDays = 365, secureValue = true) } }
apache-2.0
b84f6d5affce405038d7ca9b5fc494ae
28.486239
106
0.592719
4.174026
false
false
false
false
apollostack/apollo-android
apollo-gradle-plugin/src/test/kotlin/com/apollographql/apollo3/gradle/test/UpToDateTests.kt
1
4324
package com.apollographql.apollo3.gradle.test import com.apollographql.apollo3.gradle.util.TestUtils import com.apollographql.apollo3.gradle.util.TestUtils.withSimpleProject import com.apollographql.apollo3.gradle.util.generatedChild import com.apollographql.apollo3.gradle.util.replaceInText import org.gradle.testkit.runner.TaskOutcome import org.hamcrest.CoreMatchers.containsString import org.hamcrest.CoreMatchers.not import org.junit.Assert.assertEquals import org.junit.Assert.assertThat import org.junit.Assert.assertTrue import org.junit.Test import java.io.File class UpToDateTests { @Test fun `complete test`() { withSimpleProject { dir -> `builds successfully and generates expected outputs`(dir) `nothing changed, task up to date`(dir) `adding a custom scalar to the build script re-generates the CustomScalars`(dir) } } private fun `builds successfully and generates expected outputs`(dir: File) { val result = TestUtils.executeTask("generateApolloSources", dir) assertEquals(TaskOutcome.SUCCESS, result.task(":generateApolloSources")!!.outcome) // Java classes generated successfully assertTrue(dir.generatedChild("service/com/example/DroidDetailsQuery.kt").isFile) assertTrue(dir.generatedChild("service/com/example/FilmsQuery.kt").isFile) assertTrue(dir.generatedChild("service/com/example/fragment/SpeciesInformation.kt").isFile) // verify that the custom type generated was Any because no customScalarsMapping was specified TestUtils.assertFileContains(dir, "service/com/example/type/Types.kt", "\"kotlin.Any\"") } fun `nothing changed, task up to date`(dir: File) { val result = TestUtils.executeTask("generateApolloSources", dir) assertEquals(TaskOutcome.UP_TO_DATE, result.task(":generateApolloSources")!!.outcome) // Java classes generated successfully assertTrue(dir.generatedChild("service/com/example/DroidDetailsQuery.kt").isFile) assertTrue(dir.generatedChild("service/com/example/FilmsQuery.kt").isFile) assertTrue(dir.generatedChild("service/com/example/fragment/SpeciesInformation.kt").isFile) } fun `adding a custom scalar to the build script re-generates the CustomScalars`(dir: File) { val apolloBlock = """ apollo { customScalarsMapping = ["DateTime": "java.util.Date"] } """.trimIndent() File(dir, "build.gradle").appendText(apolloBlock) val result = TestUtils.executeTask("generateApolloSources", dir) // modifying the customScalarsMapping should cause the task to be out of date // and the task should run again assertEquals(TaskOutcome.SUCCESS, result.task(":generateApolloSources")!!.outcome) TestUtils.assertFileContains(dir, "service/com/example/type/Types.kt", "\"java.util.Date\"") val text = File(dir, "build.gradle").readText() File(dir, "build.gradle").writeText(text.replace(apolloBlock, "")) } @Test fun `change graphql file rebuilds the sources`() { withSimpleProject { dir -> var result = TestUtils.executeTask("generateApolloSources", dir, "-i") assertEquals(TaskOutcome.SUCCESS, result.task(":generateApolloSources")!!.outcome) assertThat(dir.generatedChild("service/com/example/DroidDetailsQuery.kt").readText(), containsString("classification")) File(dir, "src/main/graphql/com/example/DroidDetails.graphql").replaceInText("classification", "") result = TestUtils.executeTask("generateApolloSources", dir, "-i") assertEquals(TaskOutcome.SUCCESS, result.task(":generateApolloSources")!!.outcome) assertThat(dir.generatedChild("service/com/example/DroidDetailsQuery.kt").readText(), not(containsString("classification"))) } } @Test fun `change schema file rebuilds the sources`() { withSimpleProject { dir -> var result = TestUtils.executeTask("generateApolloSources", dir, "-i") assertEquals(TaskOutcome.SUCCESS, result.task(":generateApolloSources")!!.outcome) val schemaFile = File(dir, "src/main/graphql/com/example/schema.json") schemaFile.replaceInText("The ID of an object", "The ID of an object (modified)") result = TestUtils.executeTask("generateApolloSources", dir, "-i") assertEquals(TaskOutcome.SUCCESS, result.task(":generateApolloSources")!!.outcome) } } }
mit
bfc91294fd40552a69aa0efe1b5a0818
39.792453
130
0.741212
4.508863
false
true
false
false
garmax1/material-flashlight
app/src/main/java/co/garmax/materialflashlight/ui/main/MainViewModel.kt
1
2475
package co.garmax.materialflashlight.ui.main import androidx.lifecycle.ViewModel import co.garmax.materialflashlight.extensions.liveDataOf import co.garmax.materialflashlight.features.LightManager import co.garmax.materialflashlight.features.modes.ModeBase import co.garmax.materialflashlight.features.modes.ModeFactory import co.garmax.materialflashlight.features.modules.ModuleBase import co.garmax.materialflashlight.features.modules.ModuleFactory import co.garmax.materialflashlight.repositories.SettingsRepository import co.garmax.materialflashlight.utils.PostExecutionThread import io.reactivex.disposables.Disposable class MainViewModel( postExecutionThread: PostExecutionThread, private val lightManager: LightManager, private val settingsRepository: SettingsRepository, private val modeFactory: ModeFactory, private val moduleFactory: ModuleFactory ) : ViewModel() { val liveDataLightToggle = liveDataOf<Boolean>() var isAutoTurnedOn: Boolean get() = settingsRepository.isAutoTurnedOn set(value) { settingsRepository.isAutoTurnedOn = value } var isKeepScreenOn: Boolean get() = settingsRepository.isKeepScreenOn set(value) { settingsRepository.isKeepScreenOn = value } val isLightTurnedOn get() = lightManager.isTurnedOn val lightMode get() = settingsRepository.mode val lightModule get() = settingsRepository.module val strobeOnPeriod get() = settingsRepository.strobeOnPeriod val strobeOffPeriod get() = settingsRepository.strobeOffPeriod private var disposableLightToggle: Disposable? = null init { disposableLightToggle = lightManager .toggleStateStream .observeOn(postExecutionThread.scheduler) .subscribe { liveDataLightToggle.value = it } } fun setMode(mode: ModeBase.Mode) { settingsRepository.mode = mode lightManager.setMode(modeFactory.getMode(mode)) } fun setModule(module: ModuleBase.Module) { settingsRepository.module = module lightManager.setModule(moduleFactory.getModule(module)) } fun setStrobePeriod(timeOn: Int, timeOff: Int) { settingsRepository.strobeOnPeriod = timeOn settingsRepository.strobeOffPeriod = timeOff lightManager.setStrobePeriod(timeOn, timeOff) } override fun onCleared() { super.onCleared() disposableLightToggle?.dispose() } }
apache-2.0
321bc0c08649948bcebf4919787f7ea4
32.013333
67
0.742626
5.243644
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/presentation/more/settings/screen/ClearDatabaseScreen.kt
1
11285
package eu.kanade.presentation.more.settings.screen import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.FlipToBack import androidx.compose.material.icons.outlined.SelectAll import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.Checkbox import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import cafe.adriel.voyager.core.model.StateScreenModel import cafe.adriel.voyager.core.model.coroutineScope import cafe.adriel.voyager.core.model.rememberScreenModel import cafe.adriel.voyager.core.screen.Screen import cafe.adriel.voyager.navigator.LocalNavigator import cafe.adriel.voyager.navigator.currentOrThrow import eu.kanade.domain.source.interactor.GetSourcesWithNonLibraryManga import eu.kanade.domain.source.model.Source import eu.kanade.domain.source.model.SourceWithCount import eu.kanade.presentation.browse.components.SourceIcon import eu.kanade.presentation.components.AppBar import eu.kanade.presentation.components.AppBarActions import eu.kanade.presentation.components.Divider import eu.kanade.presentation.components.EmptyScreen import eu.kanade.presentation.components.FastScrollLazyColumn import eu.kanade.presentation.components.LoadingScreen import eu.kanade.presentation.components.Scaffold import eu.kanade.presentation.util.selectedBackground import eu.kanade.tachiyomi.Database import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.util.lang.launchIO import eu.kanade.tachiyomi.util.system.toast import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.update import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get class ClearDatabaseScreen : Screen { @Composable override fun Content() { val context = LocalContext.current val navigator = LocalNavigator.currentOrThrow val model = rememberScreenModel { ClearDatabaseScreenModel() } val state by model.state.collectAsState() when (val s = state) { is ClearDatabaseScreenModel.State.Loading -> LoadingScreen() is ClearDatabaseScreenModel.State.Ready -> { if (s.showConfirmation) { AlertDialog( onDismissRequest = model::hideConfirmation, confirmButton = { TextButton( onClick = { model.removeMangaBySourceId() model.clearSelection() model.hideConfirmation() context.toast(R.string.clear_database_completed) }, ) { Text(text = stringResource(android.R.string.ok)) } }, dismissButton = { TextButton(onClick = model::hideConfirmation) { Text(text = stringResource(android.R.string.cancel)) } }, text = { Text(text = stringResource(R.string.clear_database_confirmation)) }, ) } Scaffold( topBar = { scrollBehavior -> AppBar( title = stringResource(R.string.pref_clear_database), navigateUp = navigator::pop, actions = { if (s.items.isNotEmpty()) { AppBarActions( actions = listOf( AppBar.Action( title = stringResource(R.string.action_select_all), icon = Icons.Outlined.SelectAll, onClick = model::selectAll, ), AppBar.Action( title = stringResource(R.string.action_select_all), icon = Icons.Outlined.FlipToBack, onClick = model::invertSelection, ), ), ) } }, scrollBehavior = scrollBehavior, ) }, ) { contentPadding -> if (s.items.isEmpty()) { EmptyScreen( message = stringResource(R.string.database_clean), modifier = Modifier.padding(contentPadding), ) } else { Column( modifier = Modifier .padding(contentPadding) .fillMaxSize(), ) { FastScrollLazyColumn( modifier = Modifier.weight(1f), ) { items(s.items) { sourceWithCount -> ClearDatabaseItem( source = sourceWithCount.source, count = sourceWithCount.count, isSelected = s.selection.contains(sourceWithCount.id), onClickSelect = { model.toggleSelection(sourceWithCount.source) }, ) } } Divider() Button( modifier = Modifier .padding(horizontal = 16.dp, vertical = 8.dp) .fillMaxWidth(), onClick = model::showConfirmation, enabled = s.selection.isNotEmpty(), ) { Text( text = stringResource(R.string.action_delete), color = MaterialTheme.colorScheme.onPrimary, ) } } } } } } } @Composable private fun ClearDatabaseItem( source: Source, count: Long, isSelected: Boolean, onClickSelect: () -> Unit, ) { Row( modifier = Modifier .selectedBackground(isSelected) .clickable(onClick = onClickSelect) .padding(horizontal = 8.dp) .height(56.dp), verticalAlignment = Alignment.CenterVertically, ) { SourceIcon(source = source) Column( modifier = Modifier .padding(start = 8.dp) .weight(1f), ) { Text( text = source.visualName, style = MaterialTheme.typography.bodyMedium, ) Text(text = stringResource(R.string.clear_database_source_item_count, count)) } Checkbox( checked = isSelected, onCheckedChange = { onClickSelect() }, ) } } } private class ClearDatabaseScreenModel : StateScreenModel<ClearDatabaseScreenModel.State>(State.Loading) { private val getSourcesWithNonLibraryManga: GetSourcesWithNonLibraryManga = Injekt.get() private val database: Database = Injekt.get() init { coroutineScope.launchIO { getSourcesWithNonLibraryManga.subscribe() .collectLatest { list -> mutableState.update { old -> val items = list.sortedBy { it.name } when (old) { State.Loading -> State.Ready(items) is State.Ready -> old.copy(items = items) } } } } } fun removeMangaBySourceId() { val state = state.value as? State.Ready ?: return database.mangasQueries.deleteMangasNotInLibraryBySourceIds(state.selection) database.historyQueries.removeResettedHistory() } fun toggleSelection(source: Source) = mutableState.update { state -> if (state !is State.Ready) return@update state val mutableList = state.selection.toMutableList() if (mutableList.contains(source.id)) { mutableList.remove(source.id) } else { mutableList.add(source.id) } state.copy(selection = mutableList) } fun clearSelection() = mutableState.update { state -> if (state !is State.Ready) return@update state state.copy(selection = emptyList()) } fun selectAll() = mutableState.update { state -> if (state !is State.Ready) return@update state state.copy(selection = state.items.map { it.id }) } fun invertSelection() = mutableState.update { state -> if (state !is State.Ready) return@update state state.copy( selection = state.items .map { it.id } .filterNot { it in state.selection }, ) } fun showConfirmation() = mutableState.update { state -> if (state !is State.Ready) return@update state state.copy(showConfirmation = true) } fun hideConfirmation() = mutableState.update { state -> if (state !is State.Ready) return@update state state.copy(showConfirmation = false) } sealed class State { object Loading : State() data class Ready( val items: List<SourceWithCount>, val selection: List<Long> = emptyList(), val showConfirmation: Boolean = false, ) : State() } }
apache-2.0
44b04b8d229651078f34066f752bb0ec
40.336996
106
0.520868
5.838076
false
false
false
false
Heiner1/AndroidAPS
danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgSetBasalProfile.kt
1
1477
package info.nightscout.androidaps.danar.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danar.R import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification class MsgSetBasalProfile( injector: HasAndroidInjector, index: Byte, values: Array<Double> ) : MessageBase(injector) { // index 0-3 init { setCommand(0x3306) addParamByte(index) for (i in 0..23) { addParamInt((values[i] * 100).toInt()) } aapsLogger.debug(LTag.PUMPCOMM, "Set basal profile: $index") } override fun handleMessage(bytes: ByteArray) { val result = intFromBuff(bytes, 0, 1) if (result != 1) { failed = true aapsLogger.debug(LTag.PUMPCOMM, "Set basal profile result: $result FAILED!!!") val reportFail = Notification(Notification.PROFILE_SET_FAILED, rh.gs(R.string.profile_set_failed), Notification.URGENT) rxBus.send(EventNewNotification(reportFail)) } else { failed = false aapsLogger.debug(LTag.PUMPCOMM, "Set basal profile result: $result") val reportOK = Notification(Notification.PROFILE_SET_OK, rh.gs(R.string.profile_set_ok), Notification.INFO, 60) rxBus.send(EventNewNotification(reportOK)) } } }
agpl-3.0
75bf17252a1ffd0763fe4d2a25496203
36.897436
131
0.677048
4.244253
false
false
false
false
Heiner1/AndroidAPS
omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/OmnipodDashOverviewFragment.kt
1
34222
package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui import android.content.Intent import android.os.Bundle import android.os.Handler import android.os.HandlerThread import android.os.SystemClock import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import dagger.android.support.DaggerFragment import info.nightscout.androidaps.Constants import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.events.EventPreferenceChange import info.nightscout.androidaps.events.EventPumpStatusChanged import info.nightscout.androidaps.interfaces.BuildHelper import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.interfaces.PumpSync import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.plugins.pump.omnipod.common.databinding.OmnipodCommonOverviewButtonsBinding import info.nightscout.androidaps.plugins.pump.omnipod.common.databinding.OmnipodCommonOverviewPodInfoBinding import info.nightscout.androidaps.plugins.pump.omnipod.common.queue.command.CommandHandleTimeChange import info.nightscout.androidaps.plugins.pump.omnipod.common.queue.command.CommandResumeDelivery import info.nightscout.androidaps.plugins.pump.omnipod.common.queue.command.CommandSilenceAlerts import info.nightscout.androidaps.plugins.pump.omnipod.common.queue.command.CommandSuspendDelivery import info.nightscout.androidaps.plugins.pump.omnipod.dash.EventOmnipodDashPumpValuesChanged import info.nightscout.androidaps.plugins.pump.omnipod.dash.OmnipodDashPumpPlugin import info.nightscout.androidaps.plugins.pump.omnipod.dash.R import info.nightscout.androidaps.plugins.pump.omnipod.dash.databinding.OmnipodDashOverviewBinding import info.nightscout.androidaps.plugins.pump.omnipod.dash.databinding.OmnipodDashOverviewBluetoothStatusBinding import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.ActivationProgress import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodConstants import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.state.OmnipodDashPodStateManager import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.queue.events.EventQueueChanged import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.ui.UIRunnable import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import org.apache.commons.lang3.StringUtils import java.time.Duration import java.time.ZonedDateTime import java.util.* import java.util.concurrent.TimeUnit import javax.inject.Inject // TODO generify; see OmnipodErosOverviewFragment class OmnipodDashOverviewFragment : DaggerFragment() { @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var rh: ResourceHelper @Inject lateinit var rxBus: RxBus @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var omnipodDashPumpPlugin: OmnipodDashPumpPlugin @Inject lateinit var podStateManager: OmnipodDashPodStateManager @Inject lateinit var sp: SP @Inject lateinit var protectionCheck: ProtectionCheck @Inject lateinit var dateUtil: DateUtil @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var pumpSync: PumpSync @Inject lateinit var buildHelper: BuildHelper companion object { private const val REFRESH_INTERVAL_MILLIS = 15 * 1000L // 15 seconds private const val PLACEHOLDER = "-" private const val MAX_TIME_DEVIATION_MINUTES = 10L } private var disposables: CompositeDisposable = CompositeDisposable() private val handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper) private lateinit var refreshLoop: Runnable init { refreshLoop = Runnable { activity?.runOnUiThread { updateUi() } handler.postDelayed(refreshLoop, REFRESH_INTERVAL_MILLIS) } } private var _binding: OmnipodDashOverviewBinding? = null private var _bluetoothStatusBinding: OmnipodDashOverviewBluetoothStatusBinding? = null private var _podInfoBinding: OmnipodCommonOverviewPodInfoBinding? = null private var _buttonBinding: OmnipodCommonOverviewButtonsBinding? = null // These properties are only valid between onCreateView and onDestroyView. val binding get() = _binding!! private val bluetoothStatusBinding get() = _bluetoothStatusBinding!! private val podInfoBinding get() = _podInfoBinding!! private val buttonBinding get() = _buttonBinding!! override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = OmnipodDashOverviewBinding.inflate(inflater, container, false).also { _buttonBinding = OmnipodCommonOverviewButtonsBinding.bind(it.root) _podInfoBinding = OmnipodCommonOverviewPodInfoBinding.bind(it.root) _bluetoothStatusBinding = OmnipodDashOverviewBluetoothStatusBinding.bind(it.root) _binding = it }.root override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) buttonBinding.buttonPodManagement.setOnClickListener { activity?.let { activity -> protectionCheck.queryProtection( activity, ProtectionCheck.Protection.PREFERENCES, UIRunnable { startActivity(Intent(context, DashPodManagementActivity::class.java)) } ) } } buttonBinding.buttonResumeDelivery.setOnClickListener { disablePodActionButtons() commandQueue.customCommand( CommandResumeDelivery(), DisplayResultDialogCallback( rh.gs(R.string.omnipod_common_error_failed_to_resume_delivery), true ).messageOnSuccess(rh.gs(R.string.omnipod_common_confirmation_delivery_resumed)) ) } buttonBinding.buttonRefreshStatus.setOnClickListener { disablePodActionButtons() commandQueue.readStatus( rh.gs(R.string.requested_by_user), DisplayResultDialogCallback( rh.gs(R.string.omnipod_common_error_failed_to_refresh_status), false ) ) } buttonBinding.buttonSilenceAlerts.setOnClickListener { disablePodActionButtons() commandQueue.customCommand( CommandSilenceAlerts(), DisplayResultDialogCallback( rh.gs(R.string.omnipod_common_error_failed_to_silence_alerts), false ) .messageOnSuccess(rh.gs(R.string.omnipod_common_confirmation_silenced_alerts)) .actionOnSuccess { rxBus.send(EventDismissNotification(Notification.OMNIPOD_POD_ALERTS)) } ) } buttonBinding.buttonSuspendDelivery.setOnClickListener { disablePodActionButtons() commandQueue.customCommand( CommandSuspendDelivery(), DisplayResultDialogCallback( rh.gs(R.string.omnipod_common_error_failed_to_suspend_delivery), true ) .messageOnSuccess(rh.gs(R.string.omnipod_common_confirmation_suspended_delivery)) ) } buttonBinding.buttonSetTime.setOnClickListener { disablePodActionButtons() commandQueue.customCommand( CommandHandleTimeChange(true), DisplayResultDialogCallback(rh.gs(R.string.omnipod_common_error_failed_to_set_time), true) .messageOnSuccess(rh.gs(R.string.omnipod_common_confirmation_time_on_pod_updated)) ) } if (buildHelper.isEngineeringMode()) { bluetoothStatusBinding.deliveryStatus.visibility = View.VISIBLE bluetoothStatusBinding.connectionQuality.visibility = View.VISIBLE } podInfoBinding.omnipodCommonOverviewLotNumberLayout.visibility = View.GONE podInfoBinding.omnipodCommonOverviewPodUniqueIdLayout.visibility = View.GONE } override fun onResume() { super.onResume() handler.postDelayed(refreshLoop, REFRESH_INTERVAL_MILLIS) disposables += rxBus .toObservable(EventOmnipodDashPumpValuesChanged::class.java) .observeOn(aapsSchedulers.main) .subscribe( { updateOmnipodStatus() updatePodActionButtons() }, fabricPrivacy::logException ) disposables += rxBus .toObservable(EventQueueChanged::class.java) .observeOn(aapsSchedulers.main) .subscribe( { updateQueueStatus() updatePodActionButtons() }, fabricPrivacy::logException ) disposables += rxBus .toObservable(EventPreferenceChange::class.java) .observeOn(aapsSchedulers.main) .subscribe( { updatePodActionButtons() }, fabricPrivacy::logException ) disposables += rxBus .toObservable(EventPumpStatusChanged::class.java) .observeOn(aapsSchedulers.main) .delay(30, TimeUnit.MILLISECONDS, aapsSchedulers.main) .subscribe( { updateBluetoothConnectionStatus(it) }, fabricPrivacy::logException ) updateUi() } override fun onPause() { super.onPause() disposables.clear() handler.removeCallbacks(refreshLoop) } @Synchronized override fun onDestroyView() { super.onDestroyView() _binding = null _bluetoothStatusBinding = null _buttonBinding = null _podInfoBinding = null } private fun updateUi() { updateBluetoothStatus() updateOmnipodStatus() updatePodActionButtons() updateQueueStatus() } private fun updateBluetoothConnectionStatus(event: EventPumpStatusChanged) { val status = event.getStatus(rh) bluetoothStatusBinding.omnipodDashBluetoothStatus.text = status } private fun updateBluetoothStatus() { bluetoothStatusBinding.omnipodDashBluetoothAddress.text = podStateManager.bluetoothAddress ?: PLACEHOLDER val connectionSuccessPercentage = podStateManager.connectionSuccessRatio() * 100 val connectionAttempts = podStateManager.failedConnectionsAfterRetries + podStateManager.successfulConnectionAttemptsAfterRetries val successPercentageString = String.format("%.2f %%", connectionSuccessPercentage) val quality = "${podStateManager.successfulConnectionAttemptsAfterRetries}/$connectionAttempts :: $successPercentageString" bluetoothStatusBinding.omnipodDashBluetoothConnectionQuality.text = quality val connectionStatsColor = rh.gac( context, when { connectionSuccessPercentage < 70 && podStateManager.successfulConnectionAttemptsAfterRetries > 50 -> R.attr.warningColor connectionSuccessPercentage < 90 && podStateManager.successfulConnectionAttemptsAfterRetries > 50 -> R.attr.omniYellowColor else -> R.attr.defaultTextColor } ) bluetoothStatusBinding.omnipodDashBluetoothConnectionQuality.setTextColor(connectionStatsColor) bluetoothStatusBinding.omnipodDashDeliveryStatus.text = podStateManager.deliveryStatus?.let { podStateManager.deliveryStatus.toString() } ?: PLACEHOLDER } private fun updateOmnipodStatus() { updateLastConnection() updateLastBolus() updateTempBasal() updatePodStatus() val errors = ArrayList<String>() if (podStateManager.activationProgress.isBefore(ActivationProgress.SET_UNIQUE_ID)) { podInfoBinding.uniqueId.text = PLACEHOLDER podInfoBinding.podLot.text = PLACEHOLDER podInfoBinding.podSequenceNumber.text = PLACEHOLDER podInfoBinding.firmwareVersion.text = PLACEHOLDER podInfoBinding.timeOnPod.text = PLACEHOLDER podInfoBinding.podExpiryDate.text = PLACEHOLDER podInfoBinding.podExpiryDate.setTextColor(rh.gac(context, R.attr.defaultTextColor)) podInfoBinding.baseBasalRate.text = PLACEHOLDER podInfoBinding.totalDelivered.text = PLACEHOLDER podInfoBinding.reservoir.text = PLACEHOLDER podInfoBinding.reservoir.setTextColor(rh.gac(context, R.attr.defaultTextColor)) podInfoBinding.podActiveAlerts.text = PLACEHOLDER } else { podInfoBinding.uniqueId.text = podStateManager.uniqueId.toString() podInfoBinding.podLot.text = podStateManager.lotNumber.toString() podInfoBinding.podSequenceNumber.text = podStateManager.podSequenceNumber.toString() podInfoBinding.firmwareVersion.text = rh.gs( R.string.omnipod_dash_overview_firmware_version_value, podStateManager.firmwareVersion.toString(), podStateManager.bluetoothVersion.toString() ) val timeZone = podStateManager.timeZoneId?.let { timeZoneId -> podStateManager.timeZoneUpdated?.let { timeZoneUpdated -> val tz = TimeZone.getTimeZone(timeZoneId) val inDST = tz.inDaylightTime(Date(timeZoneUpdated)) val locale = resources.configuration.locales.get(0) tz.getDisplayName(inDST, TimeZone.SHORT, locale) } ?: PLACEHOLDER } ?: PLACEHOLDER podInfoBinding.timeOnPod.text = podStateManager.time?.let { rh.gs( R.string.omnipod_common_time_with_timezone, dateUtil.dateAndTimeString(it.toEpochSecond() * 1000), timeZone ) } ?: PLACEHOLDER val timeDeviationTooBig = podStateManager.timeDrift?.let { Duration.ofMinutes(MAX_TIME_DEVIATION_MINUTES).minus( it.abs() ).isNegative } ?: false podInfoBinding.timeOnPod.setTextColor( rh.gac( context, when { !podStateManager.sameTimeZone -> R.attr.omniMagentaColor timeDeviationTooBig -> R.attr.omniYellowColor else -> R.attr.defaultTextColor } ) ) // Update Pod expiry time val expiresAt = podStateManager.expiry podInfoBinding.podExpiryDate.text = expiresAt?.let { dateUtil.dateAndTimeString(it.toEpochSecond() * 1000) } ?: PLACEHOLDER podInfoBinding.podExpiryDate.setTextColor( rh.gac( context, when { expiresAt != null && ZonedDateTime.now().isAfter(expiresAt) -> R.attr.warningColor expiresAt != null && ZonedDateTime.now().isAfter(expiresAt.minusHours(4)) -> R.attr.omniYellowColor else -> R.attr.defaultTextColor } ) ) podStateManager.alarmType?.let { errors.add( rh.gs( R.string.omnipod_common_pod_status_pod_fault_description, it.value, it.toString() ) ) } // base basal rate podInfoBinding.baseBasalRate.text = if (podStateManager.basalProgram != null && !podStateManager.isSuspended) { rh.gs( R.string.pump_basebasalrate, omnipodDashPumpPlugin.model() .determineCorrectBasalSize(podStateManager.basalProgram!!.rateAt(System.currentTimeMillis())) ) } else { PLACEHOLDER } // total delivered podInfoBinding.totalDelivered.text = if (podStateManager.isActivationCompleted && podStateManager.pulsesDelivered != null) { rh.gs( R.string.omnipod_common_overview_total_delivered_value, (podStateManager.pulsesDelivered!! * PodConstants.POD_PULSE_BOLUS_UNITS) ) } else { PLACEHOLDER } // reservoir if (podStateManager.pulsesRemaining == null) { podInfoBinding.reservoir.text = rh.gs(R.string.omnipod_common_overview_reservoir_value_over50) podInfoBinding.reservoir.setTextColor(rh.gac(context, R.attr.defaultTextColor)) } else { // TODO // val lowReservoirThreshold = (omnipodAlertUtil.lowReservoirAlertUnits // ?: OmnipodConstants.DEFAULT_MAX_RESERVOIR_ALERT_THRESHOLD).toDouble() val lowReservoirThreshold: Short = PodConstants.DEFAULT_MAX_RESERVOIR_ALERT_THRESHOLD podInfoBinding.reservoir.text = rh.gs( R.string.omnipod_common_overview_reservoir_value, (podStateManager.pulsesRemaining!! * PodConstants.POD_PULSE_BOLUS_UNITS) ) podInfoBinding.reservoir.setTextColor( rh.gac( context, if (podStateManager.pulsesRemaining!! < lowReservoirThreshold) { R.attr.warningColor } else { R.attr.defaultTextColor } ) ) } podInfoBinding.podActiveAlerts.text = podStateManager.activeAlerts?.let { it -> it.joinToString(System.lineSeparator()) { t -> translatedActiveAlert(t) } } ?: PLACEHOLDER } if (errors.size == 0) { podInfoBinding.errors.text = PLACEHOLDER podInfoBinding.errors.setTextColor(rh.gac(context, R.attr.defaultTextColor)) } else { podInfoBinding.errors.text = StringUtils.join(errors, System.lineSeparator()) podInfoBinding.errors.setTextColor(rh.gac(context, R.attr.warningColor)) } } private fun translatedActiveAlert(alert: AlertType): String { val id = when (alert) { AlertType.LOW_RESERVOIR -> R.string.omnipod_common_alert_low_reservoir AlertType.EXPIRATION -> R.string.omnipod_common_alert_expiration_advisory AlertType.EXPIRATION_IMMINENT -> R.string.omnipod_common_alert_expiration AlertType.USER_SET_EXPIRATION -> R.string.omnipod_common_alert_expiration_advisory AlertType.AUTO_OFF -> R.string.omnipod_common_alert_shutdown_imminent AlertType.SUSPEND_IN_PROGRESS -> R.string.omnipod_common_alert_delivery_suspended AlertType.SUSPEND_ENDED -> R.string.omnipod_common_alert_delivery_suspended else -> R.string.omnipod_common_alert_unknown_alert } return rh.gs(id) } private fun updateLastConnection() { if (podStateManager.isUniqueIdSet) { podInfoBinding.lastConnection.text = readableDuration( Duration.ofMillis( System.currentTimeMillis() - podStateManager.lastUpdatedSystem, ) ) val lastConnectionColor = rh.gac( context, if (omnipodDashPumpPlugin.isUnreachableAlertTimeoutExceeded(getPumpUnreachableTimeout().toMillis())) { R.attr.warningColor } else { R.attr.defaultTextColor } ) podInfoBinding.lastConnection.setTextColor(lastConnectionColor) } else { podInfoBinding.lastConnection.setTextColor(rh.gac(context, R.attr.defaultTextColor)) podInfoBinding.lastConnection.text = PLACEHOLDER } } private fun updatePodStatus() { podInfoBinding.podStatus.text = if (podStateManager.activationProgress == ActivationProgress.NOT_STARTED) { rh.gs(R.string.omnipod_common_pod_status_no_active_pod) } else if (!podStateManager.isActivationCompleted) { if (!podStateManager.isUniqueIdSet) { rh.gs(R.string.omnipod_common_pod_status_waiting_for_activation) } else { if (podStateManager.activationProgress.isBefore(ActivationProgress.PRIME_COMPLETED)) { rh.gs(R.string.omnipod_common_pod_status_waiting_for_activation) } else { rh.gs(R.string.omnipod_common_pod_status_waiting_for_cannula_insertion) } } } else { if (podStateManager.podStatus!!.isRunning()) { if (podStateManager.isSuspended) { rh.gs(R.string.omnipod_common_pod_status_suspended) } else { rh.gs(R.string.omnipod_common_pod_status_running) } /* } else if (podStateManager.podStatus == PodProgressStatus.FAULT_EVENT_OCCURRED) { rh.gs(R.string.omnipod_common_pod_status_pod_fault) } else if (podStateManager.podStatus == PodProgressStatus.INACTIVE) { rh.gs(R.string.omnipod_common_pod_status_inactive) */ } else { podStateManager.podStatus.toString() } } val podStatusColor = rh.gac( context, when { !podStateManager.isActivationCompleted || podStateManager.isPodKaput || podStateManager.isSuspended -> R.attr.warningColor podStateManager.activeCommand != null -> R.attr.omniYellowColor else -> R.attr.defaultTextColor } ) podInfoBinding.podStatus.setTextColor(podStatusColor) } private fun updateLastBolus() { var textColorAttr = R.attr.defaultTextColor podStateManager.activeCommand?.let { val requestedBolus = it.requestedBolus if (requestedBolus != null) { var text = rh.gs( R.string.omnipod_common_overview_last_bolus_value, omnipodDashPumpPlugin.model().determineCorrectBolusSize(requestedBolus), rh.gs(R.string.insulin_unit_shortname), readableDuration(Duration.ofMillis(SystemClock.elapsedRealtime() - it.createdRealtime)) ) text += " (uncertain) " textColorAttr = R.attr.warningColor podInfoBinding.lastBolus.text = text podInfoBinding.lastBolus.setTextColor(rh.gac(context, textColorAttr)) return } } podInfoBinding.lastBolus.setTextColor(rh.gac(context, textColorAttr)) podStateManager.lastBolus?.let { // display requested units if delivery is in progress val bolusSize = it.deliveredUnits() ?: it.requestedUnits val text = rh.gs( R.string.omnipod_common_overview_last_bolus_value, omnipodDashPumpPlugin.model().determineCorrectBolusSize(bolusSize), rh.gs(R.string.insulin_unit_shortname), readableDuration(Duration.ofMillis(System.currentTimeMillis() - it.startTime)) ) if (!it.deliveryComplete) { textColorAttr = R.attr.omniYellowColor } podInfoBinding.lastBolus.text = text podInfoBinding.lastBolus.setTextColor(rh.gac(context, textColorAttr)) return } podInfoBinding.lastBolus.text = PLACEHOLDER } private fun updateTempBasal() { val tempBasal = podStateManager.tempBasal if (podStateManager.isActivationCompleted && podStateManager.tempBasalActive && tempBasal != null) { val startTime = tempBasal.startTime val rate = tempBasal.rate val duration = tempBasal.durationInMinutes val minutesRunning = Duration.ofMillis(System.currentTimeMillis() - startTime).toMinutes() podInfoBinding.tempBasal.text = rh.gs( R.string.omnipod_common_overview_temp_basal_value, rate, dateUtil.timeString(startTime), minutesRunning, duration ) } else { podInfoBinding.tempBasal.text = PLACEHOLDER } } private fun updateQueueStatus() { if (isQueueEmpty()) { podInfoBinding.queue.visibility = View.GONE } else { podInfoBinding.queue.visibility = View.VISIBLE podInfoBinding.queue.text = commandQueue.spannedStatus().toString() } } private fun updatePodActionButtons() { updateRefreshStatusButton() updateResumeDeliveryButton() updateSilenceAlertsButton() updateSuspendDeliveryButton() updateSetTimeButton() } private fun disablePodActionButtons() { buttonBinding.buttonSilenceAlerts.isEnabled = false buttonBinding.buttonResumeDelivery.isEnabled = false buttonBinding.buttonSuspendDelivery.isEnabled = false buttonBinding.buttonSetTime.isEnabled = false buttonBinding.buttonRefreshStatus.isEnabled = false } private fun updateRefreshStatusButton() { buttonBinding.buttonRefreshStatus.isEnabled = podStateManager.isUniqueIdSet && isQueueEmpty() } private fun updateResumeDeliveryButton() { if (podStateManager.isPodRunning && (podStateManager.isSuspended || commandQueue.isCustomCommandInQueue(CommandResumeDelivery::class.java)) ) { buttonBinding.buttonResumeDelivery.visibility = View.VISIBLE buttonBinding.buttonResumeDelivery.isEnabled = isQueueEmpty() } else { buttonBinding.buttonResumeDelivery.visibility = View.GONE } } private fun updateSilenceAlertsButton() { if (!isAutomaticallySilenceAlertsEnabled() && podStateManager.isPodRunning && ( podStateManager.activeAlerts!!.size > 0 || commandQueue.isCustomCommandInQueue(CommandSilenceAlerts::class.java) ) ) { buttonBinding.buttonSilenceAlerts.visibility = View.VISIBLE buttonBinding.buttonSilenceAlerts.isEnabled = isQueueEmpty() } else { buttonBinding.buttonSilenceAlerts.visibility = View.GONE } } private fun updateSuspendDeliveryButton() { // If the Pod is currently suspended, we show the Resume delivery button instead. // disable the 'suspendDelivery' button. buttonBinding.buttonSuspendDelivery.visibility = View.GONE } private fun updateSetTimeButton() { if (podStateManager.isActivationCompleted && !podStateManager.sameTimeZone) { buttonBinding.buttonSetTime.visibility = View.VISIBLE buttonBinding.buttonSetTime.isEnabled = !podStateManager.isSuspended && isQueueEmpty() } else { buttonBinding.buttonSetTime.visibility = View.GONE } } private fun isAutomaticallySilenceAlertsEnabled(): Boolean { return sp.getBoolean(R.string.omnipod_common_preferences_automatically_silence_alerts, false) } private fun displayErrorDialog(title: String, message: String, withSound: Boolean) { context?.let { ErrorHelperActivity.runAlarm(it, message, title, if (withSound) R.raw.boluserror else 0) } } private fun displayOkDialog(title: String, message: String) { context?.let { UIRunnable { OKDialog.show(it, title, message, null) }.run() } } private fun readableDuration(duration: Duration): String { val hours = duration.toHours().toInt() val minutes = duration.toMinutes().toInt() val seconds = duration.seconds when { seconds < 10 -> { return rh.gs(R.string.omnipod_common_moments_ago) } seconds < 60 -> { return rh.gs(R.string.omnipod_common_less_than_a_minute_ago) } seconds < 60 * 60 -> { // < 1 hour return rh.gs( R.string.omnipod_common_time_ago, rh.gq(R.plurals.omnipod_common_minutes, minutes, minutes) ) } seconds < 24 * 60 * 60 -> { // < 1 day val minutesLeft = minutes % 60 if (minutesLeft > 0) return rh.gs( R.string.omnipod_common_time_ago, rh.gs( R.string.omnipod_common_composite_time, rh.gq(R.plurals.omnipod_common_hours, hours, hours), rh.gq(R.plurals.omnipod_common_minutes, minutesLeft, minutesLeft) ) ) return rh.gs( R.string.omnipod_common_time_ago, rh.gq(R.plurals.omnipod_common_hours, hours, hours) ) } else -> { val days = hours / 24 val hoursLeft = hours % 24 if (hoursLeft > 0) return rh.gs( R.string.omnipod_common_time_ago, rh.gs( R.string.omnipod_common_composite_time, rh.gq(R.plurals.omnipod_common_days, days, days), rh.gq(R.plurals.omnipod_common_hours, hoursLeft, hoursLeft) ) ) return rh.gs( R.string.omnipod_common_time_ago, rh.gq(R.plurals.omnipod_common_days, days, days) ) } } } private fun isQueueEmpty(): Boolean { return commandQueue.size() == 0 && commandQueue.performing() == null } // FIXME ideally we should just have access to LocalAlertUtils here private fun getPumpUnreachableTimeout(): Duration { return Duration.ofMinutes( sp.getInt( R.string.key_pump_unreachable_threshold_minutes, Constants.DEFAULT_PUMP_UNREACHABLE_THRESHOLD_MINUTES ).toLong() ) } inner class DisplayResultDialogCallback( private val errorMessagePrefix: String, private val withSoundOnError: Boolean ) : Callback() { private var messageOnSuccess: String? = null private var actionOnSuccess: Runnable? = null override fun run() { if (result.success) { val messageOnSuccess = this.messageOnSuccess if (messageOnSuccess != null) { displayOkDialog(rh.gs(R.string.omnipod_common_confirmation), messageOnSuccess) } actionOnSuccess?.run() } else { displayErrorDialog( rh.gs(R.string.omnipod_common_warning), rh.gs( R.string.omnipod_common_two_strings_concatenated_by_colon, errorMessagePrefix, result.comment ), withSoundOnError ) } } fun messageOnSuccess(message: String): DisplayResultDialogCallback { messageOnSuccess = message return this } fun actionOnSuccess(action: Runnable): DisplayResultDialogCallback { actionOnSuccess = action return this } } }
agpl-3.0
9fcd62b92fc6be31bc40e2cea3b5df78
41.724095
137
0.602712
5.636034
false
false
false
false
hurricup/intellij-community
python/educational-core/student/src/com/jetbrains/edu/learning/ui/StudyHint.kt
1
4367
package com.jetbrains.edu.learning.ui import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.actionSystem.Separator import com.intellij.openapi.project.Project import com.jetbrains.edu.learning.StudyTaskManager import com.jetbrains.edu.learning.StudyUtils import com.jetbrains.edu.learning.core.EduNames import com.jetbrains.edu.learning.courseFormat.AnswerPlaceholder class StudyHint(private val myPlaceholder: AnswerPlaceholder?, project: Project) { companion object { private val OUR_WARNING_MESSAGE = "Put the caret in the answer placeholder to get hint" private val HINTS_NOT_AVAILABLE = "There is no hint for this answer placeholder" } val studyToolWindow: StudyToolWindow private var myShownHintNumber = 0 private var isEditingMode = false private val newHintDefaultText = "Edit this hint" init { val taskManager = StudyTaskManager.getInstance(project) if (StudyUtils.hasJavaFx() && taskManager.shouldUseJavaFx()) { studyToolWindow = StudyJavaFxToolWindow() } else { studyToolWindow = StudySwingToolWindow() } studyToolWindow.init(project, false) if (myPlaceholder == null) { studyToolWindow.setText(OUR_WARNING_MESSAGE) studyToolWindow.setActionToolbar(DefaultActionGroup()) } val course = taskManager.course if (course != null) { val courseMode = course.courseMode val group = DefaultActionGroup() val hints = myPlaceholder?.hints if (hints != null) { if (courseMode == EduNames.STUDY) { if (hints.size > 1) { group.addAll(GoBackward(), GoForward()) } } else { group.addAll(GoBackward(), GoForward(), Separator.getInstance(), EditHint()) } studyToolWindow.setActionToolbar(group) setHintText(hints) } } } private fun setHintText(hints: List<String>) { if (!hints.isEmpty()) { studyToolWindow.setText(hints[myShownHintNumber]) } else { myShownHintNumber = -1 studyToolWindow.setText(HINTS_NOT_AVAILABLE) } } private inner class GoForward : AnAction("Next Hint", "Next Hint", AllIcons.Actions.Forward) { override fun actionPerformed(e: AnActionEvent) { studyToolWindow.setText(myPlaceholder!!.hints[++myShownHintNumber]) } override fun update(e: AnActionEvent) { e.presentation.isEnabled = !isEditingMode && myPlaceholder != null && myShownHintNumber + 1 < myPlaceholder.hints.size } } private inner class GoBackward : AnAction("Previous Hint", "Previous Hint", AllIcons.Actions.Back) { override fun actionPerformed(e: AnActionEvent) { studyToolWindow.setText(myPlaceholder!!.hints[--myShownHintNumber]) } override fun update(e: AnActionEvent) { e.presentation.isEnabled = !isEditingMode && myShownHintNumber - 1 >= 0 } } private inner class EditHint : AnAction("Edit Hint", "Edit Hint", AllIcons.Modules.Edit) { override fun actionPerformed(e: AnActionEvent?) { val dialog = CCCreateAnswerPlaceholderDialog(e!!.project!!, myPlaceholder!!) dialog.show() } override fun update(e: AnActionEvent) { e.presentation.isEnabled = myPlaceholder?.hints?.isEmpty() == false } } private inner class AddHint : AnAction("Add Hint", "Add Hint", AllIcons.General.Add) { override fun actionPerformed(e: AnActionEvent) { myPlaceholder!!.addHint(newHintDefaultText) myShownHintNumber++ studyToolWindow.setText(newHintDefaultText) } override fun update(e: AnActionEvent?) { e?.presentation?.isEnabled = !isEditingMode && myPlaceholder != null } } private inner class RemoveHint : AnAction("Remove Hint", "Remove Hint", AllIcons.General.Remove) { override fun actionPerformed(e: AnActionEvent) { myPlaceholder!!.removeHint(myShownHintNumber) myShownHintNumber += if (myShownHintNumber < myPlaceholder.hints.size) 0 else -1 setHintText(myPlaceholder.hints) } override fun update(e: AnActionEvent) { e.presentation.isEnabled = myPlaceholder != null && myPlaceholder.hints.size > 0 && !isEditingMode } } }
apache-2.0
138b1e4a4dbf967d6d4159bc73f1fdfc
31.834586
124
0.698191
4.650692
false
false
false
false
Adventech/sabbath-school-android-2
common/lessons-data/src/main/java/app/ss/lessons/data/repository/quarterly/LanguagesDataSource.kt
1
3088
/* * Copyright (c) 2022. Adventech <[email protected]> * * 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 app.ss.lessons.data.repository.quarterly import app.ss.lessons.data.api.SSQuarterliesApi import app.ss.lessons.data.repository.DataSource import app.ss.lessons.data.repository.DataSourceMediator import app.ss.lessons.data.repository.LocalDataSource import app.ss.models.Language import app.ss.storage.db.dao.LanguagesDao import app.ss.storage.db.entity.LanguageEntity import com.cryart.sabbathschool.core.extensions.connectivity.ConnectivityHelper import com.cryart.sabbathschool.core.extensions.coroutines.DispatcherProvider import com.cryart.sabbathschool.core.response.Resource import javax.inject.Inject import javax.inject.Singleton @Singleton internal class LanguagesDataSource @Inject constructor( dispatcherProvider: DispatcherProvider, connectivityHelper: ConnectivityHelper, private val languagesDao: LanguagesDao, private val quarterliesApi: SSQuarterliesApi ) : DataSourceMediator<Language, LanguagesDataSource.Request>( dispatcherProvider = dispatcherProvider, connectivityHelper = connectivityHelper ) { class Request override val cache: LocalDataSource<Language, Request> = object : LocalDataSource<Language, Request> { override suspend fun get(request: Request): Resource<List<Language>> { val data = languagesDao.get().map { Language(it.code, it.name) } return Resource.success(data) } override suspend fun update(data: List<Language>) { languagesDao.insertAll(data.map { LanguageEntity(it.code, it.name) }) } } override val network: DataSource<Language, Request> = object : DataSource<Language, Request> { override suspend fun get(request: Request): Resource<List<Language>> { val data = quarterliesApi.getLanguages().body()?.map { Language(it.code, it.name) } ?: emptyList() return Resource.success(data) } } }
mit
b40d1093ef6cedebbd6a29aa5511f8d0
41.888889
106
0.741256
4.568047
false
false
false
false
geeteshk/Hyper
app/src/main/java/io/geeteshk/hyper/git/GitTask.kt
1
3520
/* * Copyright 2016 Geetesh Kalakoti <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.geeteshk.hyper.git import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.os.AsyncTask import android.os.Build import android.view.View import androidx.core.app.NotificationCompat import io.geeteshk.hyper.R import org.eclipse.jgit.lib.BatchingProgressMonitor import java.io.File import java.lang.ref.WeakReference abstract class GitTask(var context: WeakReference<Context>, var rootView: WeakReference<View>, var repo: File, private var messages: Array<String>) : AsyncTask<String, String, Boolean>() { val progressMonitor = object : BatchingProgressMonitor() { override fun onUpdate(taskName: String?, workCurr: Int, workTotal: Int, percentDone: Int) { publishProgress(taskName, percentDone.toString(), workCurr.toString(), workTotal.toString()) } override fun onEndTask(taskName: String?, workCurr: Int, workTotal: Int, percentDone: Int) { publishProgress(taskName, workCurr.toString(), workTotal.toString()) } override fun onUpdate(taskName: String?, workCurr: Int) {} override fun onEndTask(taskName: String?, workCurr: Int) {} } var manager: NotificationManager = context.get()!!.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager var builder: NotificationCompat.Builder var id = 1 init { val id = "hyper_git_channel" if (Build.VERSION.SDK_INT >= 26) { val name = context.get()!!.getString(R.string.app_name) val description = context.get()!!.getString(R.string.git) val importance = NotificationManager.IMPORTANCE_HIGH val channel = NotificationChannel(id, name, importance) channel.description = description manager.createNotificationChannel(channel) } builder = NotificationCompat.Builder(context.get()!!, id) } override fun onPreExecute() { super.onPreExecute() builder.setContentTitle(messages[0]) .setSmallIcon(R.drawable.ic_git_small) .setAutoCancel(false) .setOngoing(true) } override fun onProgressUpdate(vararg values: String) { super.onProgressUpdate(*values) builder.setContentText(values[0]) .setProgress(Integer.valueOf(values[2]), Integer.valueOf(values[1]), false) builder.setStyle(NotificationCompat.BigTextStyle().bigText(values[0])) manager.notify(id, builder.build()) } override fun onPostExecute(aBoolean: Boolean?) { super.onPostExecute(aBoolean) builder.setContentText(messages[if (aBoolean!!) { 1 } else { 2 }]) builder.setProgress(0, 0, false) .setAutoCancel(true) .setOngoing(false) manager.notify(id, builder.build()) } }
apache-2.0
75b3303e9d90f4215fb4b6153ade442e
37.26087
124
0.682386
4.559585
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinParameterInfo.kt
3
13510
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.changeSignature import com.intellij.psi.PsiReference import com.intellij.refactoring.changeSignature.ParameterInfo import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.compareDescriptors import org.jetbrains.kotlin.idea.base.psi.copied import org.jetbrains.kotlin.idea.core.setDefaultValue import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.KotlinCallableDefinitionUsage import org.jetbrains.kotlin.idea.references.KtReference import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.references.resolveToDescriptors import org.jetbrains.kotlin.idea.util.isPrimaryConstructorOfDataClass import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.addRemoveModifier.setModifierList import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded import org.jetbrains.kotlin.renderer.render import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.components.isVararg import org.jetbrains.kotlin.resolve.descriptorUtil.isAnnotationConstructor import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver import org.jetbrains.kotlin.types.AbstractTypeChecker import org.jetbrains.kotlin.types.TypeCheckerState import org.jetbrains.kotlin.types.TypeConstructor import org.jetbrains.kotlin.types.checker.ClassicTypeSystemContext import org.jetbrains.kotlin.types.checker.createClassicTypeCheckerState import org.jetbrains.kotlin.types.isError import org.jetbrains.kotlin.types.model.TypeConstructorMarker class KotlinParameterInfo( val callableDescriptor: CallableDescriptor, val originalIndex: Int = -1, private var name: String, val originalTypeInfo: KotlinTypeInfo = KotlinTypeInfo(false), var defaultValueForCall: KtExpression? = null, var defaultValueAsDefaultParameter: Boolean = false, var valOrVar: KotlinValVar = defaultValOrVar(callableDescriptor), val modifierList: KtModifierList? = null, ) : ParameterInfo { private var _defaultValueForParameter: KtExpression? = null fun setDefaultValueForParameter(expression: KtExpression?) { _defaultValueForParameter = expression } val defaultValue: KtExpression? get() = defaultValueForCall?.takeIf { defaultValueAsDefaultParameter } ?: _defaultValueForParameter var currentTypeInfo: KotlinTypeInfo = originalTypeInfo val defaultValueParameterReferences: Map<PsiReference, DeclarationDescriptor> by lazy { collectDefaultValueParameterReferences(defaultValueForCall) } private fun collectDefaultValueParameterReferences(defaultValueForCall: KtExpression?): Map<PsiReference, DeclarationDescriptor> { val file = defaultValueForCall?.containingFile as? KtFile ?: return emptyMap() if (!file.isPhysical && file.analysisContext == null) return emptyMap() return CollectParameterRefsVisitor(callableDescriptor, defaultValueForCall).run() } override fun getOldIndex(): Int = originalIndex val isNewParameter: Boolean get() = originalIndex == -1 override fun getDefaultValue(): String? = null override fun getName(): String = name override fun setName(name: String?) { this.name = name ?: "" } override fun getTypeText(): String = currentTypeInfo.render() val isTypeChanged: Boolean get() = !currentTypeInfo.isEquivalentTo(originalTypeInfo) override fun isUseAnySingleVariable(): Boolean = false override fun setUseAnySingleVariable(b: Boolean) { throw UnsupportedOperationException() } fun renderType(parameterIndex: Int, inheritedCallable: KotlinCallableDefinitionUsage<*>): String { val defaultRendering = currentTypeInfo.render() val typeSubstitutor = inheritedCallable.typeSubstitutor ?: return defaultRendering val currentBaseFunction = inheritedCallable.baseFunction.currentCallableDescriptor ?: return defaultRendering val parameter = currentBaseFunction.valueParameters[parameterIndex] if (parameter.isVararg) return defaultRendering val parameterType = parameter.type if (parameterType.isError) return defaultRendering val originalType = inheritedCallable.originalCallableDescriptor.valueParameters.getOrNull(originalIndex)?.type val typeToRender = originalType?.takeIf { val checker = OverridingTypeCheckerContext.createChecker(inheritedCallable.originalCallableDescriptor, currentBaseFunction) AbstractTypeChecker.equalTypes(checker, originalType.unwrap(), parameterType.unwrap()) } ?: parameterType return typeToRender.renderTypeWithSubstitution(typeSubstitutor, defaultRendering, true) } fun getInheritedName(inheritedCallable: KotlinCallableDefinitionUsage<*>): String { val name = this.name.quoteIfNeeded() if (!inheritedCallable.isInherited) return name val baseFunction = inheritedCallable.baseFunction val baseFunctionDescriptor = baseFunction.originalCallableDescriptor val inheritedFunctionDescriptor = inheritedCallable.originalCallableDescriptor val inheritedParameterDescriptors = inheritedFunctionDescriptor.valueParameters if (originalIndex < 0 || originalIndex >= baseFunctionDescriptor.valueParameters.size || originalIndex >= inheritedParameterDescriptors.size ) return name val inheritedParamName = inheritedParameterDescriptors[originalIndex].name.render() val oldParamName = baseFunctionDescriptor.valueParameters[originalIndex].name.render() return when { oldParamName == inheritedParamName && inheritedFunctionDescriptor !is AnonymousFunctionDescriptor -> name else -> inheritedParamName } } fun requiresExplicitType(inheritedCallable: KotlinCallableDefinitionUsage<*>): Boolean { val inheritedFunctionDescriptor = inheritedCallable.originalCallableDescriptor if (inheritedFunctionDescriptor !is AnonymousFunctionDescriptor) return true if (originalIndex < 0) return !inheritedCallable.hasExpectedType val inheritedParameterDescriptor = inheritedFunctionDescriptor.valueParameters[originalIndex] val parameter = DescriptorToSourceUtils.descriptorToDeclaration(inheritedParameterDescriptor) as? KtParameter ?: return false return parameter.typeReference != null } private fun getOriginalParameter(inheritedCallable: KotlinCallableDefinitionUsage<*>): KtParameter? { return (inheritedCallable.declaration as? KtFunction)?.valueParameters?.getOrNull(originalIndex) } private fun buildNewParameter(inheritedCallable: KotlinCallableDefinitionUsage<*>, parameterIndex: Int): KtParameter { val psiFactory = KtPsiFactory(inheritedCallable.project) val buffer = StringBuilder() if (modifierList != null) { buffer.append(modifierList.text).append(' ') } if (valOrVar != KotlinValVar.None) { buffer.append(valOrVar).append(' ') } buffer.append(getInheritedName(inheritedCallable)) if (requiresExplicitType(inheritedCallable)) { buffer.append(": ").append(renderType(parameterIndex, inheritedCallable)) } if (!inheritedCallable.isInherited) { defaultValue?.let { buffer.append(" = ").append(it.text) } } return psiFactory.createParameter(buffer.toString()) } fun getDeclarationSignature(parameterIndex: Int, inheritedCallable: KotlinCallableDefinitionUsage<*>): KtParameter { val originalParameter = getOriginalParameter(inheritedCallable) ?: return buildNewParameter(inheritedCallable, parameterIndex) val psiFactory = KtPsiFactory(originalParameter) val newParameter = originalParameter.copied() modifierList?.let { newParameter.setModifierList(it) } if (valOrVar != newParameter.valOrVarKeyword.toValVar()) { newParameter.setValOrVar(valOrVar) } val newName = getInheritedName(inheritedCallable) if (newParameter.name != newName) { newParameter.setName(newName.quoteIfNeeded()) } if (newParameter.typeReference != null || requiresExplicitType(inheritedCallable)) { newParameter.typeReference = psiFactory.createType(renderType(parameterIndex, inheritedCallable)) } if (!inheritedCallable.isInherited) { defaultValue?.let { newParameter.setDefaultValue(it) } } return newParameter } private class CollectParameterRefsVisitor( private val callableDescriptor: CallableDescriptor, private val expressionToProcess: KtExpression ) : KtTreeVisitorVoid() { private val refs = LinkedHashMap<PsiReference, DeclarationDescriptor>() private val bindingContext = expressionToProcess.analyze(BodyResolveMode.PARTIAL) private val project = expressionToProcess.project fun run(): Map<PsiReference, DeclarationDescriptor> { expressionToProcess.accept(this) return refs } override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { val ref = expression.mainReference val descriptor = targetToCollect(expression, ref) ?: return refs[ref] = descriptor } private fun targetToCollect(expression: KtSimpleNameExpression, ref: KtReference): DeclarationDescriptor? { val descriptor = ref.resolveToDescriptors(bindingContext).singleOrNull() if (descriptor is ValueParameterDescriptor) { return takeIfOurParameter(descriptor) } if (descriptor is PropertyDescriptor && callableDescriptor is ConstructorDescriptor) { val parameter = DescriptorToSourceUtils.getSourceFromDescriptor(descriptor) if (parameter is KtParameter) { return takeIfOurParameter(bindingContext[BindingContext.VALUE_PARAMETER, parameter]) } } val resolvedCall = expression.getResolvedCall(bindingContext) ?: return null (resolvedCall.resultingDescriptor as? ReceiverParameterDescriptor)?.let { return if (takeIfOurReceiver(it.containingDeclaration) != null) it else null } takeIfOurReceiver(resolvedCall.extensionReceiver as? ImplicitReceiver)?.let { return it } takeIfOurReceiver(resolvedCall.dispatchReceiver as? ImplicitReceiver)?.let { return it } return null } private fun compareDescriptors(currentDescriptor: DeclarationDescriptor?, originalDescriptor: DeclarationDescriptor?): Boolean { return compareDescriptors(project, currentDescriptor, originalDescriptor) } private fun takeIfOurParameter(parameter: DeclarationDescriptor?): ValueParameterDescriptor? { return (parameter as? ValueParameterDescriptor) ?.takeIf { compareDescriptors(it.containingDeclaration, callableDescriptor) } } private fun takeIfOurReceiver(receiverDescriptor: DeclarationDescriptor?): DeclarationDescriptor? { return receiverDescriptor?.takeIf { compareDescriptors(it, callableDescriptor.extensionReceiverParameter?.containingDeclaration) || compareDescriptors(it, callableDescriptor.dispatchReceiverParameter?.containingDeclaration) } } private fun takeIfOurReceiver(receiver: ImplicitReceiver?): DeclarationDescriptor? { return takeIfOurReceiver(receiver?.declarationDescriptor) } } } private fun defaultValOrVar(callableDescriptor: CallableDescriptor): KotlinValVar = if (callableDescriptor.isAnnotationConstructor() || callableDescriptor.isPrimaryConstructorOfDataClass) KotlinValVar.Val else KotlinValVar.None private class OverridingTypeCheckerContext(private val matchingTypeConstructors: Map<TypeConstructorMarker, TypeConstructor>) : ClassicTypeSystemContext { override fun areEqualTypeConstructors(c1: TypeConstructorMarker, c2: TypeConstructorMarker): Boolean { return super.areEqualTypeConstructors(c1, c2) || run { val img1 = matchingTypeConstructors[c1] val img2 = matchingTypeConstructors[c2] img1 != null && img1 == c2 || img2 != null && img2 == c1 } } companion object { fun createChecker(superDescriptor: CallableDescriptor, subDescriptor: CallableDescriptor): TypeCheckerState { val context = OverridingTypeCheckerContext(subDescriptor.typeParameters.zip(superDescriptor.typeParameters).associate { it.first.typeConstructor to it.second.typeConstructor }) return createClassicTypeCheckerState(isErrorTypeEqualsToAnything = false, typeSystemContext = context) } } }
apache-2.0
fa4f0f772d04b421b8598b381977bdbb
45.267123
158
0.73997
6.202938
false
false
false
false
ingokegel/intellij-community
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/ui/NotebookEditorUiUtil.kt
9
4423
package org.jetbrains.plugins.notebooks.visualization.ui import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Inlay import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.editor.impl.EditorComponentImpl import com.intellij.openapi.editor.impl.EditorEmbeddedComponentManager import java.awt.event.ComponentAdapter import java.awt.event.ComponentEvent import java.awt.event.HierarchyEvent import java.lang.ref.WeakReference import javax.swing.JComponent import javax.swing.JPanel import javax.swing.JScrollPane import javax.swing.SwingUtilities import javax.swing.plaf.PanelUI /** * A workaround base class for panels with custom UI. Every look and feel change in the IDE (like theme, font family and size, etc.) * leads to call of the `updateUI()`. All default Swing implementations resets the UI to the default one. */ open class SteadyUIPanel(private val steadyUi: PanelUI) : JPanel() { init { // Required for correct UI initialization. It leaks in the super class anyway. @Suppress("LeakingThis") setUI(steadyUi) } override fun updateUI() { // Update the UI. Don't call super.updateUI() to prevent resetting to the default UI. // There's another way to set specific UI for specific components: by defining java.swing.plaf.ComponentUI#createUI and overriding // java.swing.JComponent#getUIClassID. This approach can't be used in our code since it requires UI classes to have empty constructors, // while in reality some additional data should be provided to UI instances in advance. setUI(steadyUi) } } fun EditorEx.addComponentInlay( component: JComponent, isRelatedToPrecedingText: Boolean, showAbove: Boolean, showWhenFolded: Boolean = true, priority: Int, offset: Int, ): Inlay<*> { val inlay = EditorEmbeddedComponentManager.getInstance().addComponent( this, component, EditorEmbeddedComponentManager.Properties( EditorEmbeddedComponentManager.ResizePolicy.none(), null, isRelatedToPrecedingText, showAbove, showWhenFolded, priority, offset, ) )!! updateUiOnParentResizeImpl(component.parent as JComponent, WeakReference(component)) return inlay } private fun updateUiOnParentResizeImpl(parent: JComponent, childRef: WeakReference<JComponent>) { val listener = object : ComponentAdapter() { override fun componentResized(e: ComponentEvent?) { val child = childRef.get() if (child != null) { child.updateUI() } else { parent.removeComponentListener(this) } } } parent.addComponentListener(listener) } /** * Seeks for an [EditorComponentImpl] in the component hierarchy, calls [updateHandler] initially and every time * the [component] is detached or attached to some component with the actual editor. */ fun registerEditorSizeWatcher( component: JComponent, updateHandler: () -> Unit, ) { var editorComponent: EditorComponentImpl? = null var scrollComponent: JScrollPane? = null updateHandler() // Holds strong reference to the editor. Incautious usage may cause editor leakage. val editorResizeListener = object : ComponentAdapter() { override fun componentResized(e: ComponentEvent): Unit = updateHandler() } component.addHierarchyListener { event -> if (event.changeFlags and HierarchyEvent.PARENT_CHANGED.toLong() != 0L) { val newEditor: EditorComponentImpl? = generateSequence(component.parent) { it.parent } .filterIsInstance<EditorComponentImpl>() .firstOrNull() if (editorComponent !== newEditor) { (scrollComponent ?: editorComponent)?.removeComponentListener(editorResizeListener) editorComponent = newEditor // if editor is located inside a scroll pane, we should listen to its size instead of editor component scrollComponent = generateSequence(editorComponent?.parent) { it.parent } .filterIsInstance<JScrollPane>() .firstOrNull() (scrollComponent ?: editorComponent)?.addComponentListener(editorResizeListener) updateHandler() } } } } val EditorEx.textEditingAreaWidth: Int get() = scrollingModel.visibleArea.width - scrollPane.verticalScrollBar.width fun JComponent.yOffsetFromEditor(editor: Editor): Int? = SwingUtilities.convertPoint(this, 0, 0, editor.contentComponent).y .takeIf { it >= 0 } ?.let { it + insets.top }
apache-2.0
f11ecff111ffb76aa2b09afd19d3325f
35.553719
139
0.739317
4.597713
false
false
false
false
GunoH/intellij-community
plugins/package-search/src/intellij/plugin/ui/toolwindow/models/PackageVersion.kt
2
3717
/******************************************************************************* * 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 import com.intellij.util.text.VersionComparatorUtil import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.util.versionTokenPriorityProvider import kotlinx.serialization.Serializable import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import org.jetbrains.packagesearch.api.v2.ApiStandardPackage import org.jetbrains.packagesearch.packageversionutils.PackageVersionUtils @Serializable sealed class PackageVersion : Comparable<PackageVersion> { abstract val versionName: String abstract val isStable: Boolean abstract val releasedAt: Long? @get:Nls abstract val displayName: String override fun compareTo(other: PackageVersion): Int = VersionComparatorUtil.compare(versionName, other.versionName, ::versionTokenPriorityProvider) @Serializable object Missing : PackageVersion() { override val versionName = "" override val isStable = true override val releasedAt: Long? = null @Nls override val displayName = PackageSearchBundle.message("packagesearch.ui.missingVersion") @NonNls override fun toString() = "[Missing version]" } @Serializable data class Named( override val versionName: String, override val isStable: Boolean, override val releasedAt: Long? ) : PackageVersion() { init { require(versionName.isNotBlank()) { "A Named version name cannot be blank." } } @Suppress("HardCodedStringLiteral") @Nls override val displayName = versionName @NonNls override fun toString() = versionName fun semanticVersionComponent(): SemVerComponent? { val groupValues = SEMVER_REGEX.find(versionName)?.groupValues ?: return null if (groupValues.size <= 1) return null val semanticVersion = groupValues[1].takeIf { it.isNotBlank() } ?: return null return SemVerComponent(semanticVersion, this) } data class SemVerComponent(val semanticVersion: String, val named: Named) companion object { private val SEMVER_REGEX = "^((?:\\d+\\.){0,3}\\d+)".toRegex(option = RegexOption.IGNORE_CASE) } } companion object { fun from(rawVersion: ApiStandardPackage.ApiStandardVersion): PackageVersion { if (rawVersion.version.isBlank()) return Missing return Named(versionName = rawVersion.version.trim(), isStable = rawVersion.stable, releasedAt = rawVersion.lastChanged) } fun from(rawVersion: String?): PackageVersion { if (rawVersion.isNullOrBlank()) return Missing return Named(rawVersion.trim(), isStable = PackageVersionUtils.evaluateStability(rawVersion), releasedAt = null) } } }
apache-2.0
f2f37324ec8727772334b79724d6d1ac
36.17
132
0.673931
5.27983
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/ReplaceBySourceAsTree.kt
1
41209
// 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.impl import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.impl.ReplaceBySourceAsTree.OperationsApplier import it.unimi.dsi.fastutil.Hash import it.unimi.dsi.fastutil.longs.Long2ObjectMap import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap import org.jetbrains.annotations.TestOnly import java.util.* /** * # Replace By Source ~~as tree~~ * * Replace By Source, or RBS for short. * * "As tree" is not a correct fact. It was previously processed as tree, before we committed to multiple parents. * So, this is still a directed graph. * * During the RBS, we collect a set of operations. After the set is collected, we apply them on a target storage. * Theoretically, it's possible to create a dry run, if needed. * Operations are supposed to be isolated and complete. That means that target storage doesn't become in inconsistent state at * any moment of the RBS. * * This RBS implementation doesn't have expected exception and should always succeed. * If this RBS doesn't have sense from the abstract point of view (for example, during the RBS we transfer some entity, * but we can't find a parent for this entity in the target store), we still get into some consistent state. As for the example, * this entity won't be transferred into the target storage. * * * # Implementation details * * The operations are collected in separate data structures: For adding, replacing and removing. * Relabel operation is also known as "Replace". * Add operations should be applied in order, while for other operations the order is not determined. * * During the RBS we maintain a separate state for each of processed entity to avoid processing the same entity twice. * Two separate states are presented: for target and ReplaceWith storages. * * # Debugging * * You can use [OperationsApplier.dumpOperations] for listing the operations on the storage. * * # Future improvements * * - Make type graphs. Separate graphs into independent parts (how is it called correctly?) * - Work on separate graph parts as on independent items */ internal class ReplaceBySourceAsTree : ReplaceBySourceOperation { private lateinit var targetStorage: MutableEntityStorageImpl private lateinit var replaceWithStorage: AbstractEntityStorage private lateinit var entityFilter: (EntitySource) -> Boolean internal val replaceOperations = ArrayList<RelabelElement>() internal val removeOperations = ArrayList<RemoveElement>() internal val addOperations = ArrayList<AddElement>() internal val targetState = Long2ObjectOpenHashMap<ReplaceState>() internal val replaceWithState = Long2ObjectOpenHashMap<ReplaceWithState>() @set:TestOnly internal var shuffleEntities: Long = -1L private val replaceWithProcessingCache = HashMap<Pair<EntityId?, Int>, Pair<DataCache, MutableList<ChildEntityId>>>() override fun replace( targetStorage: MutableEntityStorageImpl, replaceWithStorage: AbstractEntityStorage, entityFilter: (EntitySource) -> Boolean, ) { this.targetStorage = targetStorage this.replaceWithStorage = replaceWithStorage this.entityFilter = entityFilter // Process entities from the target storage val targetEntitiesToReplace = targetStorage.entitiesBySource(entityFilter) val targetEntities = targetEntitiesToReplace.values.flatMap { it.values }.flatten().toMutableList() if (shuffleEntities != -1L && targetEntities.size > 1) { targetEntities.shuffle(Random(shuffleEntities)) } for (targetEntityToReplace in targetEntities) { TargetProcessor().processEntity(targetEntityToReplace) } // Process entities from the replaceWith storage val replaceWithEntitiesToReplace = replaceWithStorage.entitiesBySource(entityFilter) val replaceWithEntities = replaceWithEntitiesToReplace.values.flatMap { it.values }.flatten().toMutableList() if (shuffleEntities != -1L && replaceWithEntities.size > 1) { replaceWithEntities.shuffle(Random(shuffleEntities)) } for (replaceWithEntityToReplace in replaceWithEntities) { ReplaceWithProcessor().processEntity(replaceWithEntityToReplace) } // This method can be used for debugging // OperationsApplier().dumpOperations() // Apply collected operations on the target storage OperationsApplier().apply() } // This class is just a wrapper to combine functions logically private inner class OperationsApplier { fun apply() { val replaceToTarget = HashMap<EntityId, EntityId>() for (addOperation in addOperations) { val parents = addOperation.parents?.mapTo(HashSet()) { when (it) { is ParentsRef.AddedElement -> replaceToTarget.getValue(it.replaceWithEntityId) is ParentsRef.TargetRef -> it.targetEntityId } } addElement(parents, addOperation.replaceWithSource, replaceToTarget) } for (operation in replaceOperations) { val targetEntity = targetStorage.entityDataByIdOrDie(operation.targetEntityId).createEntity(targetStorage) val replaceWithEntity = replaceWithStorage.entityDataByIdOrDie(operation.replaceWithEntityId).createEntity(replaceWithStorage) val parents = operation.parents?.mapTo(HashSet()) { val targetEntityId = when (it) { is ParentsRef.AddedElement -> replaceToTarget.getValue(it.replaceWithEntityId) is ParentsRef.TargetRef -> it.targetEntityId } targetStorage.entityDataByIdOrDie(targetEntityId).createEntity(targetStorage) } targetStorage.modifyEntity(WorkspaceEntity.Builder::class.java, targetEntity) { (this as ModifiableWorkspaceEntityBase<*, *>).relabel(replaceWithEntity, parents) } targetStorage.indexes.updateExternalMappingForEntityId(operation.replaceWithEntityId, operation.targetEntityId, replaceWithStorage.indexes) } for (removeOperation in removeOperations) { targetStorage.removeEntityByEntityId(removeOperation.targetEntityId) } } private fun addElement(parents: Set<EntityId>?, replaceWithDataSource: EntityId, replaceToTarget: HashMap<EntityId, EntityId>) { val targetParents = mutableListOf<WorkspaceEntity>() parents?.forEach { parent -> targetParents += targetStorage.entityDataByIdOrDie(parent).createEntity(targetStorage) } val modifiableEntity = replaceWithStorage.entityDataByIdOrDie(replaceWithDataSource).createDetachedEntity(targetParents) modifiableEntity as ModifiableWorkspaceEntityBase<out WorkspaceEntity, out WorkspaceEntityData<*>> // We actually bind parents in [createDetachedEntity], but we can't do it for external entities (that are defined in a separate module) // Here we bind them again, so I guess we can remove "parents binding" from [createDetachedEntity], but let's do it twice for now. // Actually, I hope to get rid of [createDetachedEntity] at some moment. targetParents.groupBy { it::class }.forEach { (_, ents) -> modifiableEntity.linkExternalEntity(ents.first().getEntityInterface().kotlin, false, ents) } targetStorage.addEntity(modifiableEntity) targetStorage.indexes.updateExternalMappingForEntityId(replaceWithDataSource, modifiableEntity.id, replaceWithStorage.indexes) replaceToTarget[replaceWithDataSource] = modifiableEntity.id } /** * First print the operations, then print the information about entities */ fun dumpOperations(): String { val targetEntities: MutableSet<EntityId> = mutableSetOf() val replaceWithEntities: MutableSet<EntityId> = mutableSetOf() return buildString { appendLine("---- New entities -------") for (addOperation in addOperations) { appendLine(infoOf(addOperation.replaceWithSource, replaceWithStorage, true)) replaceWithEntities += addOperation.replaceWithSource if (addOperation.parents == null) { appendLine("No parent entities") } else { appendLine("Parents:") addOperation.parents.forEach { parent -> when (parent) { is ParentsRef.AddedElement -> { appendLine(" - ${infoOf(parent.replaceWithEntityId, replaceWithStorage, true)} <--- New Added Entity") replaceWithEntities += parent.replaceWithEntityId } is ParentsRef.TargetRef -> { appendLine(" - ${infoOf(parent.targetEntityId, targetStorage, true)} <--- Existing Entity") targetEntities += parent.targetEntityId } } } } appendLine() } appendLine("---- No More New Entities -------") appendLine("---- Removes -------") removeOperations.map { it.targetEntityId }.forEach { entityId -> appendLine(infoOf(entityId, targetStorage, true)) targetEntities += entityId } appendLine("---- No More Removes -------") appendLine() appendLine("---- Replaces -------") replaceOperations.forEach { operation -> appendLine( infoOf(operation.targetEntityId, targetStorage, true) + " -> " + infoOf(operation.replaceWithEntityId, replaceWithStorage, true) + " | " + "Count of parents: ${operation.parents?.size}") targetEntities += operation.targetEntityId replaceWithEntities += operation.replaceWithEntityId } appendLine("---- No More Replaces -------") appendLine() appendLine("---- Entities -------") appendLine() appendLine("---- Target Storage -------") targetEntities.forEach { appendLine(infoOf(it, targetStorage, false)) appendLine() } appendLine() appendLine("---- Replace With Storage -------") replaceWithEntities.forEach { appendLine(infoOf(it, replaceWithStorage, false)) appendLine() } } } private fun infoOf(entityId: EntityId, store: AbstractEntityStorage, short: Boolean): String { val entityData = store.entityDataByIdOrDie(entityId) val entity = entityData.createEntity(store) return if (entity is WorkspaceEntityWithSymbolicId) entity.symbolicId.toString() else if (short) "$entity" else "$entity | $entityData" } } // This class is just a wrapper to combine functions logically private inner class ReplaceWithProcessor { fun processEntity(replaceWithEntity: WorkspaceEntity) { replaceWithEntity as WorkspaceEntityBase if (replaceWithState[replaceWithEntity.id] != null) return val trackToParents = TrackToParents(replaceWithEntity.id) buildRootTrack(trackToParents, replaceWithStorage) processEntity(trackToParents) } private fun processEntity(replaceWithTrack: TrackToParents): ParentsRef? { val replaceWithEntityId = replaceWithTrack.entity val replaceWithEntityState = replaceWithState[replaceWithEntityId] when (replaceWithEntityState) { ReplaceWithState.ElementMoved -> return ParentsRef.AddedElement(replaceWithEntityId) is ReplaceWithState.NoChange -> return ParentsRef.TargetRef(replaceWithEntityState.targetEntityId) ReplaceWithState.NoChangeTraceLost -> return null is ReplaceWithState.Relabel -> return ParentsRef.TargetRef(replaceWithEntityState.targetEntityId) null -> Unit } val replaceWithEntityData = replaceWithStorage.entityDataByIdOrDie(replaceWithEntityId) val replaceWithEntity = replaceWithEntityData.createEntity(replaceWithStorage) as WorkspaceEntityBase if (replaceWithTrack.parents.isEmpty()) { return findAndReplaceRootEntity(replaceWithEntity) } else { if (replaceWithEntity is WorkspaceEntityWithSymbolicId) { val targetEntity = targetStorage.resolve(replaceWithEntity.symbolicId) val parentsAssociation = replaceWithTrack.parents.mapNotNullTo(HashSet()) { processEntity(it) } return processExactEntity(targetEntity, replaceWithEntity, parentsAssociation) } else { val parentsAssociation = replaceWithTrack.parents.mapNotNullTo(HashSet()) { processEntity(it) } if (parentsAssociation.isNotEmpty()) { val targetEntityData = parentsAssociation.filterIsInstance<ParentsRef.TargetRef>().firstNotNullOfOrNull { parent -> findEntityInTargetStore(replaceWithEntityData, parent.targetEntityId, replaceWithEntityId.clazz) } val targetEntity = targetEntityData?.createEntity(targetStorage) as? WorkspaceEntityBase return processExactEntity(targetEntity, replaceWithEntity, parentsAssociation) } else { replaceWithEntityId.addState(ReplaceWithState.NoChangeTraceLost) return null } } } } private fun findAndReplaceRootEntity(replaceWithEntity: WorkspaceEntityBase): ParentsRef? { val replaceWithEntityId = replaceWithEntity.id val currentState = replaceWithState[replaceWithEntityId] // This was just checked before this call assert(currentState == null) val targetEntity = findRootEntityInStorage(replaceWithEntity, targetStorage, replaceWithStorage, targetState) val parents = null return processExactEntity(targetEntity, replaceWithEntity, parents) } private fun processExactEntity(targetEntity: WorkspaceEntity?, replaceWithEntity: WorkspaceEntityBase, parents: Set<ParentsRef>?): ParentsRef? { val replaceWithEntityId = replaceWithEntity.id if (targetEntity == null) { if (entityFilter(replaceWithEntity.entitySource)) { addSubtree(parents, replaceWithEntityId) return ParentsRef.AddedElement(replaceWithEntityId) } else { replaceWithEntityId.addState(ReplaceWithState.NoChangeTraceLost) return null } } else { val targetEntityId = (targetEntity as WorkspaceEntityBase).id val targetCurrentState = targetState[targetEntityId] when (targetCurrentState) { is ReplaceState.NoChange -> return ParentsRef.TargetRef(targetEntityId) is ReplaceState.Relabel -> return ParentsRef.TargetRef(targetEntityId) ReplaceState.Remove -> return null null -> Unit } when { entityFilter(targetEntity.entitySource) && entityFilter(replaceWithEntity.entitySource) -> { if (replaceWithEntity.entitySource !is DummyParentEntitySource) { replaceWorkspaceData(targetEntity.id, replaceWithEntity.id, parents) } else { doNothingOn(targetEntityId, replaceWithEntityId) } return ParentsRef.TargetRef(targetEntityId) } entityFilter(targetEntity.entitySource) && !entityFilter(replaceWithEntity.entitySource) -> { removeWorkspaceData(targetEntity.id, replaceWithEntity.id) return null } !entityFilter(targetEntity.entitySource) && entityFilter(replaceWithEntity.entitySource) -> { if (targetEntity is WorkspaceEntityWithSymbolicId) { if (replaceWithEntity.entitySource !is DummyParentEntitySource) { replaceWorkspaceData(targetEntityId, replaceWithEntityId, parents) } else { doNothingOn(targetEntityId, replaceWithEntityId) } return ParentsRef.TargetRef(targetEntityId) } else { addSubtree(parents, replaceWithEntityId) return ParentsRef.AddedElement(replaceWithEntityId) } } !entityFilter(targetEntity.entitySource) && !entityFilter(replaceWithEntity.entitySource) -> { doNothingOn(targetEntity.id, replaceWithEntityId) return ParentsRef.TargetRef(targetEntityId) } else -> error("Unexpected branch") } } } private fun findAndReplaceRootEntityInTargetStore(replaceWithRootEntity: WorkspaceEntityBase): ParentsRef? { val replaceRootEntityId = replaceWithRootEntity.id val replaceWithCurrentState = replaceWithState[replaceRootEntityId] when (replaceWithCurrentState) { is ReplaceWithState.NoChange -> return ParentsRef.TargetRef(replaceWithCurrentState.targetEntityId) ReplaceWithState.NoChangeTraceLost -> return null is ReplaceWithState.Relabel -> return ParentsRef.TargetRef(replaceWithCurrentState.targetEntityId) ReplaceWithState.ElementMoved -> TODO() null -> Unit } val targetEntity = findRootEntityInStorage(replaceWithRootEntity, targetStorage, replaceWithStorage, targetState) return processExactEntity(targetEntity, replaceWithRootEntity, null) } /** * This is a very similar thing as [findSameEntity]. But it finds an entity in the target storage (or the entity that will be added) */ fun findSameEntityInTargetStore(replaceWithTrack: TrackToParents): ParentsRef? { // Check if this entity was already processed val replaceWithCurrentState = replaceWithState[replaceWithTrack.entity] when (replaceWithCurrentState) { is ReplaceWithState.NoChange -> return ParentsRef.TargetRef(replaceWithCurrentState.targetEntityId) ReplaceWithState.NoChangeTraceLost -> return null is ReplaceWithState.Relabel -> return ParentsRef.TargetRef(replaceWithCurrentState.targetEntityId) ReplaceWithState.ElementMoved -> return ParentsRef.AddedElement(replaceWithTrack.entity) null -> Unit } val replaceWithEntityData = replaceWithStorage.entityDataByIdOrDie(replaceWithTrack.entity) if (replaceWithTrack.parents.isEmpty()) { val targetRootEntityId = findAndReplaceRootEntityInTargetStore( replaceWithEntityData.createEntity(replaceWithStorage) as WorkspaceEntityBase) return targetRootEntityId } else { val parentsAssociation = replaceWithTrack.parents.associateWith { findSameEntityInTargetStore(it) } val entriesList = parentsAssociation.entries.toList() val targetParents = mutableSetOf<EntityId>() var targetEntityData: WorkspaceEntityData<out WorkspaceEntity>? = null for (i in entriesList.indices) { val value = entriesList[i].value if (value is ParentsRef.TargetRef) { targetEntityData = findEntityInTargetStore(replaceWithEntityData, value.targetEntityId, replaceWithTrack.entity.clazz) if (targetEntityData != null) { targetParents += entriesList[i].key.entity break } } } if (targetEntityData == null) { for (entry in entriesList) { val value = entry.value if (value is ParentsRef.AddedElement) { return ParentsRef.AddedElement(replaceWithTrack.entity) } } } return targetEntityData?.createEntityId()?.let { ParentsRef.TargetRef(it) } } } private fun addSubtree(parents: Set<ParentsRef>?, replaceWithEntityId: EntityId) { val currentState = replaceWithState[replaceWithEntityId] when (currentState) { ReplaceWithState.ElementMoved -> return is ReplaceWithState.NoChange -> error("Unexpected state") ReplaceWithState.NoChangeTraceLost -> error("Unexpected state") is ReplaceWithState.Relabel -> error("Unexpected state") null -> Unit } addElementOperation(parents, replaceWithEntityId) replaceWithStorage.refs.getChildrenRefsOfParentBy(replaceWithEntityId.asParent()).values.flatten().forEach { val replaceWithChildEntityData = replaceWithStorage.entityDataByIdOrDie(it.id) if (!entityFilter(replaceWithChildEntityData.entitySource)) return@forEach val trackToParents = TrackToParents(it.id) buildRootTrack(trackToParents, replaceWithStorage) val sameEntity = findSameEntityInTargetStore(trackToParents) if (sameEntity is ParentsRef.TargetRef) { return@forEach } val otherParents = trackToParents.parents.mapNotNull { findSameEntityInTargetStore(it) } addSubtree((otherParents + ParentsRef.AddedElement(replaceWithEntityId)).toSet(), it.id) } } } // This class is just a wrapper to combine functions logically private inner class TargetProcessor { fun processEntity(targetEntityToReplace: WorkspaceEntity) { targetEntityToReplace as WorkspaceEntityBase val trackToParents = TrackToParents(targetEntityToReplace.id) buildRootTrack(trackToParents, targetStorage) // This method not only finds the same entity in the ReplaceWith storage, but also processes all entities it meets. // So, for processing an entity, it's enough to call this methos on the entity. findSameEntity(trackToParents) } /** * This method searched for the "associated" entity of [targetEntityTrack] in the repalceWith storage * Here, let's use "associated" termin to define what we're looking for. If the entity have a [SymbolicEntityId], * this is super simple. "associated" entity is just an entity from the different storage with the same SymbolicId. * * Things go complicated if there is no SymbolicId. In this case we build a track to the root entities in the graph, trying * to find same roots in the replaceWith storage and building a "track" to the entity in the replaceWith storage. This * traced entity is an "associated" entity for our current entity. * * This is a recursive algorithm * - Get all parents of the entity * - if there are NO parents: * - Try to find associated entity in replaceWith storage (by SymbolicId in most cases) * - if there are parents: * - Run this algorithm on all parents to find associated parents in the replaceWith storage * - Based on found parents in replaceWith storage, find an associated entity for our currenly searched entity */ private fun findSameEntity(targetEntityTrack: TrackToParents): EntityId? { // Check if this entity was already processed val targetEntityState = targetState[targetEntityTrack.entity] if (targetEntityState != null) { when (targetEntityState) { is ReplaceState.NoChange -> return targetEntityState.replaceWithEntityId is ReplaceState.Relabel -> return targetEntityState.replaceWithEntityId ReplaceState.Remove -> return null } } val targetEntityData = targetStorage.entityDataByIdOrDie(targetEntityTrack.entity) if (targetEntityTrack.parents.isEmpty()) { // If the entity doesn't have parents, it's a root entity for this subtree (subgraph?) return findAndReplaceRootEntity(targetEntityData) } else { val (targetParents, replaceWithEntity) = processParentsFromReplaceWithStorage(targetEntityTrack, targetEntityData) return processExactEntity(targetParents, targetEntityData, replaceWithEntity) } } private fun processExactEntity(targetParents: MutableSet<ParentsRef>?, targetEntityData: WorkspaceEntityData<out WorkspaceEntity>, replaceWithEntity: WorkspaceEntityBase?): EntityId? { // Here we check if any of the required parents is missing the our new parents val requiredParentMissing = if (targetParents != null) { val targetParentClazzes = targetParents.map { when (it) { is ParentsRef.AddedElement -> it.replaceWithEntityId.clazz is ParentsRef.TargetRef -> it.targetEntityId.clazz } } targetEntityData.getRequiredParents().any { it.toClassId() !in targetParentClazzes } } else false val targetEntity = targetEntityData.createEntity(targetStorage) as WorkspaceEntityBase if (replaceWithEntity == null || requiredParentMissing) { // Here we don't have an associated entity in the replaceWith storage. Decide if we remove our entity or just keep it when (entityFilter(targetEntity.entitySource)) { true -> { removeWorkspaceData(targetEntity.id, null) return null } false -> { doNothingOn(targetEntity.id, null) return null } } } else { when { entityFilter(targetEntity.entitySource) && entityFilter(replaceWithEntity.entitySource) -> { if (replaceWithEntity.entitySource !is DummyParentEntitySource) { replaceWorkspaceData(targetEntity.id, replaceWithEntity.id, targetParents) } else { doNothingOn(targetEntity.id, replaceWithEntity.id) } return replaceWithEntity.id } entityFilter(targetEntity.entitySource) && !entityFilter(replaceWithEntity.entitySource) -> { removeWorkspaceData(targetEntity.id, replaceWithEntity.id) return null } !entityFilter(targetEntity.entitySource) && entityFilter(replaceWithEntity.entitySource) -> { if (replaceWithEntity.entitySource !is DummyParentEntitySource) { replaceWorkspaceData(targetEntity.id, replaceWithEntity.id, targetParents) } else { doNothingOn(targetEntity.id, replaceWithEntity.id) } return replaceWithEntity.id } !entityFilter(targetEntity.entitySource) && !entityFilter(replaceWithEntity.entitySource) -> { doNothingOn(targetEntity.id, replaceWithEntity.id) return replaceWithEntity.id } else -> error("Unexpected branch") } } } /** * An interesting logic here. We've found associated parents for the target entity. * Now, among these parents we have to find a child, that will be similar to "our" entity in target storage. * * In addition, we're currently missing "new" parents in the replaceWith storage. * So, the return type is a set of parents (existing and new) and an "associated" entity in the replaceWith storage. */ private fun processParentsFromReplaceWithStorage( targetEntityTrack: TrackToParents, targetEntityData: WorkspaceEntityData<out WorkspaceEntity> ): Pair<MutableSet<ParentsRef>, WorkspaceEntityBase?> { // Our future set of parents val targetParents = mutableSetOf<ParentsRef>() val targetEntity = targetEntityData.createEntity(targetStorage) var replaceWithEntity: WorkspaceEntityBase? = null if (targetEntity is WorkspaceEntityWithSymbolicId) { replaceWithEntity = replaceWithStorage.resolve(targetEntity.symbolicId) as? WorkspaceEntityBase } else { // Here we're just traversing parents. If we find a parent that does have a child entity that is equal to our entity, stop and save // this "equaled" entity as our "associated" entity. // After that we're checking that other parents does have this child among their children. If not, we do not register this parent as // "new" parent for our entity. // // Another approach would be finding the "most common" child among of all parents. But currently we use this approach // because I think that it's "good enough" and the "most common child" may be not what we're looking for. // So, here we search for the first equal entity val parentsAssociation = targetEntityTrack.parents.associateWith { findSameEntity(it) } val entriesList = parentsAssociation.entries.toList() var index = 0 for (i in entriesList.indices) { index = i val (caching, replaceWithEntityIds) = replaceWithProcessingCache.getOrPut(entriesList[i].value to targetEntityTrack.entity.clazz) { val ids = LinkedList(childrenInReplaceWith(entriesList[i].value, targetEntityTrack.entity.clazz)) DataCache(ids.size, EntityDataStrategy()) to ids } replaceWithEntity = replaceWithEntityIds.removeSomeWithCaching(targetEntityData, caching, replaceWithStorage) ?.createEntity(replaceWithStorage) as? WorkspaceEntityBase if (replaceWithEntity != null) { assert(replaceWithState[replaceWithEntity.id] == null) targetParents += ParentsRef.TargetRef(entriesList[i].key.entity) break } } // Here we know our "associated" entity, so we just check what parents remain with it. entriesList.drop(index + 1).forEach { tailItem -> // Should we use cache as in above? val replaceWithEntityIds = childrenInReplaceWith(tailItem.value, targetEntityTrack.entity.clazz).toMutableList() val caching = DataCache(replaceWithEntityIds.size, EntityDataStrategy()) var replaceWithMyEntityData = replaceWithEntityIds.removeSomeWithCaching(targetEntityData, caching, replaceWithStorage) while (replaceWithMyEntityData != null && replaceWithEntity!!.id != replaceWithMyEntityData.createEntityId()) { replaceWithMyEntityData = replaceWithEntityIds.removeSomeWithCaching(targetEntityData, caching, replaceWithStorage) } if (replaceWithMyEntityData != null) { targetParents += ParentsRef.TargetRef(tailItem.key.entity) } } } // And here we get other parent' of the associated entity. // This is actually a complicated operation because it's not enough just to find parents in replaceWith storage. // We should also understand if this parent is a new entity or it already exists in the target storage. if (replaceWithEntity != null) { val replaceWithTrackToParents = TrackToParents(replaceWithEntity.id) buildRootTrack(replaceWithTrackToParents, replaceWithStorage) val alsoTargetParents = replaceWithTrackToParents.parents.map { ReplaceWithProcessor().findSameEntityInTargetStore(it) } targetParents.addAll(alsoTargetParents.filterNotNull()) } return Pair(targetParents, replaceWithEntity) } /** * Process root entity of the storage */ fun findAndReplaceRootEntity(targetEntityData: WorkspaceEntityData<out WorkspaceEntity>): EntityId? { val targetRootEntityId = targetEntityData.createEntityId() val currentTargetState = targetState[targetRootEntityId] assert(currentTargetState == null) { "This state was already checked before this function" } val replaceWithEntity = findRootEntityInStorage(targetEntityData.createEntity(targetStorage) as WorkspaceEntityBase, replaceWithStorage, targetStorage, replaceWithState) as? WorkspaceEntityBase return processExactEntity(null, targetEntityData, replaceWithEntity) } } private class EntityDataStrategy : Hash.Strategy<WorkspaceEntityData<out WorkspaceEntity>> { override fun equals(a: WorkspaceEntityData<out WorkspaceEntity>?, b: WorkspaceEntityData<out WorkspaceEntity>?): Boolean { if (a == null || b == null) { return false } return a.equalsByKey(b) } override fun hashCode(o: WorkspaceEntityData<out WorkspaceEntity>?): Int { return o?.hashCodeByKey() ?: 0 } } private fun MutableList<ChildEntityId>.removeSomeWithCaching(key: WorkspaceEntityData<out WorkspaceEntity>, cache: Object2ObjectOpenCustomHashMap<WorkspaceEntityData<out WorkspaceEntity>, List<WorkspaceEntityData<out WorkspaceEntity>>>, storage: AbstractEntityStorage): WorkspaceEntityData<out WorkspaceEntity>? { val foundInCache = cache.removeSome(key) if (foundInCache != null) return foundInCache val thisIterator = this.iterator() while (thisIterator.hasNext()) { val id = thisIterator.next() val value = storage.entityDataByIdOrDie(id.id) if (value.equalsByKey(key)) { thisIterator.remove() return value } thisIterator.remove() addValueToMap(cache, value) } return null } private fun <K, V> Object2ObjectOpenCustomHashMap<K, List<V>>.removeSome(key: K): V? { val existingValue = this[key] ?: return null return if (existingValue.size == 1) { this.remove(key) existingValue.single() } else { val firstElement = existingValue[0] this[key] = existingValue.drop(1) firstElement } } private fun addElementOperation(targetParentEntity: Set<ParentsRef>?, replaceWithEntity: EntityId) { addOperations += AddElement(targetParentEntity, replaceWithEntity) replaceWithEntity.addState(ReplaceWithState.ElementMoved) } private fun replaceWorkspaceData(targetEntityId: EntityId, replaceWithEntityId: EntityId, parents: Set<ParentsRef>?) { replaceOperations.add(RelabelElement(targetEntityId, replaceWithEntityId, parents)) targetEntityId.addState(ReplaceState.Relabel(replaceWithEntityId, parents)) replaceWithEntityId.addState(ReplaceWithState.Relabel(targetEntityId)) } private fun removeWorkspaceData(targetEntityId: EntityId, replaceWithEntityId: EntityId?) { removeOperations.add(RemoveElement(targetEntityId)) targetEntityId.addState(ReplaceState.Remove) replaceWithEntityId?.addState(ReplaceWithState.NoChangeTraceLost) } private fun doNothingOn(targetEntityId: EntityId, replaceWithEntityId: EntityId?) { targetEntityId.addState(ReplaceState.NoChange(replaceWithEntityId)) replaceWithEntityId?.addState(ReplaceWithState.NoChange(targetEntityId)) } private fun EntityId.addState(state: ReplaceState) { val currentState = targetState[this] require(currentState == null) { "Unexpected existing state for $this: $currentState" } targetState[this] = state } private fun EntityId.addState(state: ReplaceWithState) { val currentState = replaceWithState[this] require(currentState == null) replaceWithState[this] = state } private fun findEntityInTargetStore(replaceWithEntityData: WorkspaceEntityData<out WorkspaceEntity>, targetParentEntityId: EntityId, childClazz: Int): WorkspaceEntityData<out WorkspaceEntity>? { var targetEntityData1: WorkspaceEntityData<out WorkspaceEntity>? val targetEntityIds = childrenInTarget(targetParentEntityId, childClazz) val targetChildrenMap = makeEntityDataCollection(targetEntityIds, targetStorage) targetEntityData1 = targetChildrenMap.removeSome(replaceWithEntityData) while (targetEntityData1 != null && replaceWithState[targetEntityData1.createEntityId()] != null) { targetEntityData1 = targetChildrenMap.removeSome(replaceWithEntityData) } return targetEntityData1 } private fun makeEntityDataCollection(targetChildEntityIds: List<ChildEntityId>, storage: AbstractEntityStorage): Object2ObjectOpenCustomHashMap<WorkspaceEntityData<out WorkspaceEntity>, List<WorkspaceEntityData<out WorkspaceEntity>>> { val targetChildrenMap = Object2ObjectOpenCustomHashMap<WorkspaceEntityData<out WorkspaceEntity>, List<WorkspaceEntityData<out WorkspaceEntity>>>( targetChildEntityIds.size, EntityDataStrategy()) targetChildEntityIds.forEach { id -> val value = storage.entityDataByIdOrDie(id.id) addValueToMap(targetChildrenMap, value) } return targetChildrenMap } private fun addValueToMap(targetChildrenMap: Object2ObjectOpenCustomHashMap<WorkspaceEntityData<out WorkspaceEntity>, List<WorkspaceEntityData<out WorkspaceEntity>>>, value: WorkspaceEntityData<out WorkspaceEntity>) { val existingValue = targetChildrenMap[value] targetChildrenMap[value] = if (existingValue != null) existingValue + value else listOf(value) } private val targetChildrenCache = HashMap<EntityId, Map<ConnectionId, List<ChildEntityId>>>() private val replaceWithChildrenCache = HashMap<EntityId, Map<ConnectionId, List<ChildEntityId>>>() private fun childrenInReplaceWith(entityId: EntityId?, childClazz: Int): List<ChildEntityId> { return childrenInStorage(entityId, childClazz, replaceWithStorage, replaceWithChildrenCache) } private fun childrenInTarget(entityId: EntityId?, childClazz: Int): List<ChildEntityId> { return childrenInStorage(entityId, childClazz, targetStorage, targetChildrenCache) } companion object { /** * Build track from this entity to it's parents. There is no return value, we modify [track] variable. */ private fun buildRootTrack(track: TrackToParents, storage: AbstractEntityStorage) { val parents = storage.refs.getParentRefsOfChild(track.entity.asChild()) parents.values.forEach { parentEntityId -> val parentTrack = TrackToParents(parentEntityId.id) buildRootTrack(parentTrack, storage) track.parents += parentTrack parentTrack.child = track } } private fun childrenInStorage(entityId: EntityId?, childrenClass: Int, storage: AbstractEntityStorage, childrenCache: HashMap<EntityId, Map<ConnectionId, List<ChildEntityId>>>): List<ChildEntityId> { val targetEntityIds = if (entityId != null) { val targetChildren = childrenCache.getOrPut(entityId) { storage.refs.getChildrenRefsOfParentBy(entityId.asParent()) } val targetFoundChildren = targetChildren.filterKeys { sameClass(it.childClass, childrenClass, it.connectionType) } require(targetFoundChildren.size < 2) { "Got unexpected amount of children" } if (targetFoundChildren.isEmpty()) { emptyList() } else { val (_, targetChildEntityIds) = targetFoundChildren.entries.single() targetChildEntityIds } } else { emptyList() } return targetEntityIds } /** * Search entity from [oppositeStorage] in [goalStorage] */ private fun findRootEntityInStorage(rootEntity: WorkspaceEntityBase, goalStorage: AbstractEntityStorage, oppositeStorage: AbstractEntityStorage, goalState: Long2ObjectMap<out Any>): WorkspaceEntity? { return if (rootEntity is WorkspaceEntityWithSymbolicId) { val symbolicId = rootEntity.symbolicId goalStorage.resolve(symbolicId) } else { val oppositeEntityData = oppositeStorage.entityDataByIdOrDie(rootEntity.id) goalStorage.entities(rootEntity.id.clazz.findWorkspaceEntity()) .filter { val itId = (it as WorkspaceEntityBase).id if (goalState[itId] != null) return@filter false goalStorage.entityDataByIdOrDie(itId).equalsByKey(oppositeEntityData) && goalStorage.refs.getParentRefsOfChild(itId.asChild()) .isEmpty() } .firstOrNull() } } } } typealias DataCache = Object2ObjectOpenCustomHashMap<WorkspaceEntityData<out WorkspaceEntity>, List<WorkspaceEntityData<out WorkspaceEntity>>> internal data class RelabelElement(val targetEntityId: EntityId, val replaceWithEntityId: EntityId, val parents: Set<ParentsRef>?) internal data class RemoveElement(val targetEntityId: EntityId) internal data class AddElement(val parents: Set<ParentsRef>?, val replaceWithSource: EntityId) internal sealed interface ReplaceState { data class Relabel(val replaceWithEntityId: EntityId, val parents: Set<ParentsRef>? = null) : ReplaceState data class NoChange(val replaceWithEntityId: EntityId?) : ReplaceState object Remove : ReplaceState } internal sealed interface ReplaceWithState { object ElementMoved : ReplaceWithState data class NoChange(val targetEntityId: EntityId) : ReplaceWithState data class Relabel(val targetEntityId: EntityId) : ReplaceWithState object NoChangeTraceLost : ReplaceWithState } sealed interface ParentsRef { data class TargetRef(val targetEntityId: EntityId) : ParentsRef data class AddedElement(val replaceWithEntityId: EntityId) : ParentsRef } class TrackToParents( val entity: EntityId, var child: TrackToParents? = null, val parents: MutableList<TrackToParents> = ArrayList(), )
apache-2.0
5284508c6522f4baac404bfc2ad4b790
45.563842
194
0.697396
5.8
false
false
false
false
mvmike/min-cal-widget
app/src/main/kotlin/cat/mvmike/minimalcalendarwidget/domain/Format.kt
1
1901
// Copyright (c) 2016, Miquel Martí <[email protected]> // See LICENSE for licensing information package cat.mvmike.minimalcalendarwidget.domain import android.appwidget.AppWidgetManager import android.content.Context import android.content.res.Configuration.ORIENTATION_LANDSCAPE import android.os.Bundle private const val DEFAULT_MONTH_HEADER_LABEL_LENGTH = Int.MAX_VALUE private const val DEFAULT_DAY_HEADER_LABEL_LENGTH = 3 private const val DEFAULT_HEADER_TEXT_RELATIVE_SIZE = 1f private const val DEFAULT_DAY_CELL_TEXT_RELATIVE_SIZE = 1f data class Format( val width: Int ) { private val monthHeaderLabelLength: Int = when { width >= 180 -> DEFAULT_MONTH_HEADER_LABEL_LENGTH else -> 3 } private val dayHeaderLabelLength: Int = when { width >= 180 -> DEFAULT_DAY_HEADER_LABEL_LENGTH else -> 1 } val headerTextRelativeSize: Float = when { width >= 220 -> DEFAULT_HEADER_TEXT_RELATIVE_SIZE width >= 200 -> 0.9f else -> 0.8f } val dayCellTextRelativeSize: Float = when { width >= 260 -> 1.2f width >= 240 -> 1.1f width >= 220 -> DEFAULT_DAY_CELL_TEXT_RELATIVE_SIZE width >= 200 -> 0.9f else -> 0.8f } fun getMonthHeaderLabel(value: String) = value.take(monthHeaderLabelLength) fun getDayHeaderLabel(value: String) = value.take(dayHeaderLabelLength) } fun getFormat(context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int) = runCatching { appWidgetManager.getAppWidgetOptions(appWidgetId) .getWidth(context) ?.let { Format(it) } }.getOrNull() private fun Bundle.getWidth(context: Context) = when (context.resources.configuration.orientation) { ORIENTATION_LANDSCAPE -> getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT) else -> getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH) }.takeIf { it > 0 }
bsd-3-clause
6340dc1fe20b35279ec832cc221c56b3
32.928571
101
0.703158
4.03397
false
false
false
false
cfieber/orca
orca-kayenta/src/main/kotlin/com/netflix/spinnaker/orca/kayenta/pipeline/RunCanaryPipelineStage.kt
1
2738
/* * Copyright 2018 Netflix, 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.netflix.spinnaker.orca.kayenta.pipeline import com.netflix.spinnaker.orca.CancellableStage import com.netflix.spinnaker.orca.ext.withTask import com.netflix.spinnaker.orca.kayenta.KayentaService import com.netflix.spinnaker.orca.kayenta.tasks.MonitorKayentaCanaryTask import com.netflix.spinnaker.orca.kayenta.tasks.RunKayentaCanaryTask import com.netflix.spinnaker.orca.pipeline.StageDefinitionBuilder import com.netflix.spinnaker.orca.pipeline.TaskNode import com.netflix.spinnaker.orca.pipeline.model.Stage import org.slf4j.LoggerFactory import org.springframework.stereotype.Component import java.lang.String.format import java.util.Collections.emptyMap @Component class RunCanaryPipelineStage( private val kayentaService: KayentaService ) : StageDefinitionBuilder, CancellableStage { private val log = LoggerFactory.getLogger(javaClass) override fun taskGraph(stage: Stage, builder: TaskNode.Builder) { builder .withTask<RunKayentaCanaryTask>("runCanary") .withTask<MonitorKayentaCanaryTask>("monitorCanary") } override fun getType(): String { return STAGE_TYPE } override fun cancel(stage: Stage): CancellableStage.Result { val context = stage.context val canaryPipelineExecutionId = context["canaryPipelineExecutionId"] as String? if (canaryPipelineExecutionId != null) { log.info(format("Cancelling stage (stageId: %s: executionId: %s, canaryPipelineExecutionId: %s, context: %s)", stage.id, stage.execution.id, canaryPipelineExecutionId, stage.context)) try { kayentaService.cancelPipelineExecution(canaryPipelineExecutionId, "") } catch (e: Exception) { log.error(format("Failed to cancel stage (stageId: %s, executionId: %s), e: %s", stage.id, stage.execution.id, e.message), e) } } else { log.info(format("Not cancelling stage (stageId: %s: executionId: %s, context: %s) since no canary pipeline execution id exists", stage.id, stage.execution.id, stage.context)) } return CancellableStage.Result(stage, emptyMap<Any, Any>()) } companion object { @JvmStatic val STAGE_TYPE = "runCanary" } }
apache-2.0
de2e653ec9c89e7cc53a18bc1b7f9ee2
37.027778
189
0.755296
4.123494
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/stb/src/templates/kotlin/stb/templates/stb_rect_pack.kt
4
4970
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package stb.templates import org.lwjgl.generator.* import stb.* val stb_rect_pack = "STBRectPack".nativeClass(Module.STB, prefix = "STBRP", prefixMethod = "stbrp_") { includeSTBAPI( """#define STBRP_ASSERT #define STB_RECT_PACK_IMPLEMENTATION #include "stb_rect_pack.h"""") documentation = """ Native bindings to stb_rect_pack.h from the ${url("https://github.com/nothings/stb", "stb library")}. Useful for e.g. packing rectangular textures into an atlas. Does not do rotation. This library currently uses the Skyline Bottom-Left algorithm. Not necessarily the awesomest packing method, but better than the totally naive one in stb_truetype (which is primarily what this is meant to replace). """ IntConstant( "Mostly for internal use, but this is the maximum supported coordinate value.", "_MAXVAL"..0x7fffffff ) EnumConstant( "Packing heuristics", "HEURISTIC_Skyline_default".enum, "HEURISTIC_Skyline_BL_sortHeight".."STBRP_HEURISTIC_Skyline_default", "HEURISTIC_Skyline_BF_sortHeight".enum ) int( "pack_rects", """ Assigns packed locations to rectangles. The rectangles are of type ##STBRPRect, stored in the array {@code rects}, and there are {@code num_rects} many of them. Rectangles which are successfully packed have the {@code was_packed} flag set to a non-zero value and {@code x} and {@code y} store the minimum location on each axis (i.e. bottom-left in cartesian coordinates, top-left if you imagine y increasing downwards). Rectangles which do not fit have the {@code was_packed} flag set to 0. You should not try to access the {@code rects} array from another thread while this function is running, as the function temporarily reorders the array while it executes. To pack into another rectangle, you need to call #init_target() again. To continue packing into the same rectangle, you can call this function again. Calling this multiple times with multiple rect arrays will probably produce worse packing results than calling it a single time with the full rectangle array, but the option is available. """, stbrp_context.p("context", "an ##STBRPContext struct"), stbrp_rect.p("rects", "an array of ##STBRPRect structs"), AutoSize("rects")..int("num_rects", "the number of structs in {@code rects}"), returnDoc = "1 if all of the rectangles were successfully packed and 0 otherwise" ) void( "init_target", """ Initialize a rectangle packer to: pack a rectangle that is {@code width} by {@code height} in dimensions using temporary storage provided by the array {@code nodes}, which is {@code num_nodes} long. You must call this function every time you start packing into a new target. There is no "shutdown" function. The {@code nodes} memory must stay valid for the following #pack_rects() call (or calls), but can be freed after the call (or calls) finish. Note: to guarantee best results, either: ${ol( "make sure {@code num_nodes &ge; width}", "or, call #setup_allow_out_of_mem() with {@code allow_out_of_mem = 1}" )} If you don't do either of the above things, widths will be quantized to multiples of small integers to guarantee the algorithm doesn't run out of temporary storage. If you do \#2, then the non-quantized algorithm will be used, but the algorithm may run out of temporary storage and be unable to pack some rectangles. """, stbrp_context.p("context", "an ##STBRPContext struct"), int("width", "the rectangle width"), int("height", "the rectangle height"), stbrp_node.p("nodes", "an array of ##STBRPNode structs"), AutoSize("nodes")..int("num_nodes", "the number of structs in {@code nodes}") ) void( "setup_allow_out_of_mem", """ Optionally call this function after init but before doing any packing to change the handling of the out-of-temp-memory scenario, described in #init_target(). If you call init again, this will be reset to the default (false). """, stbrp_context.p("context", "an ##STBRPContext struct"), intb("allow_out_of_mem", "1 to allow running out of temporary storage") ) void( "setup_heuristic", """ Optionally select which packing heuristic the library should use. Different heuristics will produce better/worse results for different data sets. If you call init again, this will be reset to the default. """, stbrp_context.p("context", "an ##STBRPContext struct"), int("heuristic", "the packing heuristic") ) }
bsd-3-clause
50af46a08ed24a64e6623e2174f193f7
42.226087
159
0.659759
4.352014
false
false
false
false
rinp/task
src/main/kotlin/todo/Filter.kt
1
1953
package task import org.slf4j.LoggerFactory import org.springframework.core.Ordered import org.springframework.core.annotation.Order import org.springframework.stereotype.Component import org.springframework.util.StringUtils import org.springframework.web.filter.OncePerRequestFilter import java.util.* import javax.servlet.FilterChain import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletRequestWrapper import javax.servlet.http.HttpServletResponse /** * @author rinp * @since 2016/08/12 */ private val log = LoggerFactory.getLogger("filter") @Component @Order(org.springframework.core.Ordered.HIGHEST_PRECEDENCE) @Suppress("unused") open class HttpMethodOverrideHeaderFilter : OncePerRequestFilter() { override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, filterChain: FilterChain?) { if ("POST" != request.method) { filterChain?.doFilter(request, response) return } val headerValue: String? = request.getHeader(X_HTTP_METHOD_OVERRIDE_HEADER); if (headerValue != null && StringUtils.hasLength(headerValue)) { val method = headerValue.toUpperCase(); val wrapper = HttpMethodRequestWrapper(method, request) filterChain?.doFilter(wrapper, response); return } filterChain?.doFilter(request, response); } val X_HTTP_METHOD_OVERRIDE_HEADER = "X-HTTP-Method-Override"; /** * Simple {@link HttpServletRequest} wrapper that returns the supplied method for * {@link HttpServletRequest#getMethod()}. */ class HttpMethodRequestWrapper : HttpServletRequestWrapper { constructor(method: String, request: HttpServletRequest) : super(request) { this._method = method; } lateinit var _method: String override fun getMethod(): String { return this._method } } }
apache-2.0
eb99f4eff6905e35c8ba2cce9713edba
28.164179
122
0.706093
4.834158
false
false
false
false
russianwordnet/yarn-android
app/src/main/java/net/russianword/android/ProcessState.kt
1
610
package net.russianword.android import net.russianword.android.api.Task import java.io.Serializable import java.util.* const val USER_STATE_BUNDLE_ID = "userState" enum class State { NOT_AUTHENTICATED, AUTHENTICATING, NOT_LOADED, LOADING, LOADED, DISPLAYED, ANSWER_READY, SENDING_ANSWER } data class ProcessState(@Volatile var currentState: State = State.NOT_AUTHENTICATED, @Volatile var userId: String? = null, @Volatile var task: Task? = null, @Volatile var preparedAnswers: Set<String>? = HashSet()) : Serializable
apache-2.0
228c18dab18317a41a8b046d3e7f6ab7
31.105263
95
0.667213
4.265734
false
false
false
false
dahlstrom-g/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/CacheSettingsPanel.kt
9
1894
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.committed import com.intellij.openapi.options.BoundConfigurable import com.intellij.openapi.options.ShowSettingsUtil import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.vcs.VcsBundle.message import com.intellij.ui.dsl.builder.* object CacheSettingsDialog { @JvmStatic fun showSettingsDialog(project: Project): Boolean = ShowSettingsUtil.getInstance().editConfigurable(project, CacheSettingsPanel(project)) } internal class CacheSettingsPanel(project: Project) : BoundConfigurable(message("cache.settings.dialog.title")) { private val cache = CommittedChangesCache.getInstance(project) private val cacheState = CommittedChangesCacheState().apply { copyFrom(cache.state) } override fun apply() { super.apply() cache.loadState(cacheState) } override fun createPanel(): DialogPanel = panel { if (cache.isMaxCountSupportedForProject) countRow() else daysRow() row { val refreshCheckBox = checkBox(message("changes.refresh.changes.every")) .bindSelected(cacheState::isRefreshEnabled) intTextField(1..60 * 24) .bindIntText(cacheState::refreshInterval) .enabledIf(refreshCheckBox.selected) .gap(RightGap.SMALL) label(message("changes.minutes")) }.layout(RowLayout.PARENT_GRID) } private fun Panel.countRow() = row(message("changes.changelists.to.cache.initially")) { intTextField(1..100000) .bindIntText(cacheState::initialCount) } private fun Panel.daysRow() = row(message("changes.days.of.history.to.cache.initially")) { intTextField(1..720) .bindIntText(cacheState::initialDays) } }
apache-2.0
a164cf4a229f1afdc20cef1fba215880
36.137255
140
0.734424
4.334096
false
true
false
false
Jay-Y/yframework
yframework-android/framework/src/main/java/org/yframework/android/common/CommonExtens.kt
1
1940
package org.yframework.android.common import android.app.Activity import android.content.Intent import android.os.Bundle import android.widget.Toast import com.becypress.framework.android.BuildConfig import java.net.ConnectException import java.net.SocketTimeoutException import java.net.UnknownHostException /** * Description: CommonExtens<br> * Comments Name: CommonExtens<br> * Date: 2019-08-20 22:09<br> * Author: ysj<br> * EditorDate: 2019-08-20 22:09<br> * Editor: ysj */ enum class TipTypeEnum { NORMAL, SUCCESS, WARNING, ERROR } fun Activity.tip( msg: CharSequence, type: TipTypeEnum = TipTypeEnum.NORMAL, duration: Int = Toast.LENGTH_SHORT ) { runOnUiThread { when (type) { TipTypeEnum.NORMAL -> Toast.makeText(this, msg, duration).show() TipTypeEnum.SUCCESS -> Toast.makeText(this, msg, duration).show() TipTypeEnum.WARNING -> Toast.makeText(this, msg, duration).show() TipTypeEnum.ERROR -> Toast.makeText(this, msg, duration).show() } } } fun Activity.dispatchFailure(error: Throwable?) { error?.let { if (BuildConfig.DEBUG) { it.printStackTrace() } when { it is NullPointerException -> { } error is SocketTimeoutException -> it.message?.let { tip("网络连接超时", TipTypeEnum.ERROR ) } it is UnknownHostException || it is ConnectException -> //网络未连接 it.message?.let { tip("网络未连接", TipTypeEnum.ERROR) } else -> it.message?.let { message -> tip(message, TipTypeEnum.ERROR ) } } } } fun Activity.navigateUpToActivity(c: Class<*>, bundle: Bundle? = null, killed: Boolean? = true) { val intent = Intent(this, c) bundle?.let { intent.putExtras(it) } startActivity(intent) if (killed!!) finish() }
apache-2.0
bf3df5f253fc8fa7eefa3d3cfa558fd0
27.073529
97
0.625786
4.033827
false
false
false
false
ThePreviousOne/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/data/source/online/russian/Readmanga.kt
1
7024
package eu.kanade.tachiyomi.data.source.online.russian import android.content.Context import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.source.Language import eu.kanade.tachiyomi.data.source.RU import eu.kanade.tachiyomi.data.source.model.Page import eu.kanade.tachiyomi.data.source.online.ParsedOnlineSource import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element import java.text.SimpleDateFormat import java.util.* import java.util.regex.Pattern class Readmanga(override val id: Int) : ParsedOnlineSource() { override val name = "Readmanga" override val baseUrl = "http://readmanga.me" override val lang: Language get() = RU override val supportsLatest = true override fun popularMangaInitialUrl() = "$baseUrl/list?sortType=rate" override fun latestUpdatesInitialUrl() = "$baseUrl/list?sortType=updated" override fun searchMangaInitialUrl(query: String, filters: List<Filter>) = "$baseUrl/search?q=$query&${filters.map { it.id + "=in" }.joinToString("&")}" override fun popularMangaSelector() = "div.desc" override fun latestUpdatesSelector() = "div.desc" override fun popularMangaFromElement(element: Element, manga: Manga) { element.select("h3 > a").first().let { manga.setUrlWithoutDomain(it.attr("href")) manga.title = it.attr("title") } } override fun latestUpdatesFromElement(element: Element, manga: Manga) { popularMangaFromElement(element, manga) } override fun popularMangaNextPageSelector() = "a.nextLink" override fun latestUpdatesNextPageSelector() = "a.nextLink" override fun searchMangaSelector() = popularMangaSelector() override fun searchMangaFromElement(element: Element, manga: Manga) { element.select("h3 > a").first().let { manga.setUrlWithoutDomain(it.attr("href")) manga.title = it.attr("title") } } // max 200 results override fun searchMangaNextPageSelector() = null override fun mangaDetailsParse(document: Document, manga: Manga) { val infoElement = document.select("div.leftContent").first() manga.author = infoElement.select("span.elem_author").first()?.text() manga.genre = infoElement.select("span.elem_genre").text().replace(" ,", ",") manga.description = infoElement.select("div.manga-description").text() manga.status = parseStatus(infoElement.html()) manga.thumbnail_url = infoElement.select("img").attr("data-full") } private fun parseStatus(element: String): Int { when { element.contains("<h3>Запрещена публикация произведения по копирайту</h3>") -> return Manga.LICENSED element.contains("<h1 class=\"names\"> Сингл") || element.contains("<b>Перевод:</b> завершен") -> return Manga.COMPLETED element.contains("<b>Перевод:</b> продолжается") -> return Manga.ONGOING else -> return Manga.UNKNOWN } } override fun chapterListSelector() = "div.chapters-link tbody tr" override fun chapterFromElement(element: Element, chapter: Chapter) { val urlElement = element.select("a").first() chapter.setUrlWithoutDomain(urlElement.attr("href") + "?mature=1") chapter.name = urlElement.text().replace(" новое", "") chapter.date_upload = element.select("td:eq(1)").first()?.text()?.let { SimpleDateFormat("dd/MM/yy", Locale.US).parse(it).time } ?: 0 } override fun parseChapterNumber(chapter: Chapter) { chapter.chapter_number = -2f } override fun pageListParse(response: Response, pages: MutableList<Page>) { val html = response.body().string() val beginIndex = html.indexOf("rm_h.init( [") val endIndex = html.indexOf("], 0, false);", beginIndex) val trimmedHtml = html.substring(beginIndex, endIndex) val p = Pattern.compile("'.+?','.+?',\".+?\"") val m = p.matcher(trimmedHtml) var i = 0 while (m.find()) { val urlParts = m.group().replace("[\"\']+".toRegex(), "").split(',') pages.add(Page(i++, "", urlParts[1] + urlParts[0] + urlParts[2])) } } override fun pageListParse(document: Document, pages: MutableList<Page>) { } override fun imageUrlParse(document: Document) = "" /* [...document.querySelectorAll("tr.advanced_option:nth-child(1) > td:nth-child(3) span.js-link")].map((el,i) => { * const onClick=el.getAttribute('onclick');const id=onClick.substr(31,onClick.length-33); * return `Filter("${id}", "${el.textContent.trim()}")` }).join(',\n') * on http://readmanga.me/search */ override fun getFilterList(): List<Filter> = listOf( Filter("el_5685", "арт"), Filter("el_2155", "боевик"), Filter("el_2143", "боевые искусства"), Filter("el_2148", "вампиры"), Filter("el_2142", "гарем"), Filter("el_2156", "гендерная интрига"), Filter("el_2146", "героическое фэнтези"), Filter("el_2152", "детектив"), Filter("el_2158", "дзёсэй"), Filter("el_2141", "додзинси"), Filter("el_2118", "драма"), Filter("el_2154", "игра"), Filter("el_2119", "история"), Filter("el_2137", "кодомо"), Filter("el_2136", "комедия"), Filter("el_2147", "махо-сёдзё"), Filter("el_2126", "меха"), Filter("el_2132", "мистика"), Filter("el_2133", "научная фантастика"), Filter("el_2135", "повседневность"), Filter("el_2151", "постапокалиптика"), Filter("el_2130", "приключения"), Filter("el_2144", "психология"), Filter("el_2121", "романтика"), Filter("el_2124", "самурайский боевик"), Filter("el_2159", "сверхъестественное"), Filter("el_2122", "сёдзё"), Filter("el_2128", "сёдзё-ай"), Filter("el_2134", "сёнэн"), Filter("el_2139", "сёнэн-ай"), Filter("el_2129", "спорт"), Filter("el_2138", "сэйнэн"), Filter("el_2153", "трагедия"), Filter("el_2150", "триллер"), Filter("el_2125", "ужасы"), Filter("el_2140", "фантастика"), Filter("el_2131", "фэнтези"), Filter("el_2127", "школа"), Filter("el_2149", "этти"), Filter("el_2123", "юри") ) }
apache-2.0
d14cd9a8a84c3f232c728155520be1b8
38.297619
132
0.608999
3.822235
false
false
false
false
Pagejects/pagejects-core
src/main/kotlin/net/pagejects/core/forms/DefaultFormFieldHandler.kt
1
985
package net.pagejects.core.forms import com.codeborne.selenide.SelenideElement import net.pagejects.core.annotation.PublicAPI import net.pagejects.core.util.TypeConverter /** * Default implementation of the [net.pagejects.core.FormFieldHandler] * * @author Andrey Paslavsky * @since 0.1 */ @PublicAPI class DefaultFormFieldHandler : AbstractFormFieldHandler() { override fun fillValue(element: SelenideElement, value: Any?) { if (element.isCheckbox) { element.isSelected = true == TypeConverter.convert(value, Boolean::class) } else { element.value = TypeConverter.convert(value, String::class) } } override fun readInternalValueFrom(element: SelenideElement): String? = if (element.isCheckbox) { element.isSelected.toString() } else { element.value } private val SelenideElement.isCheckbox: Boolean get() = "input".equals(tagName, true) && "checkbox".equals(attr("type"), true) }
apache-2.0
7b0cbc749a3e77c398f01f05c22c3aa7
30.806452
101
0.698477
4.282609
false
false
false
false
paplorinc/intellij-community
platform/lang-impl/src/com/intellij/ide/actions/CopyTBXReferenceAction.kt
1
7990
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.actions import com.intellij.ide.IdeBundle import com.intellij.ide.actions.CopyReferenceUtil.* import com.intellij.navigation.JBProtocolNavigateCommand.Companion.FQN_KEY import com.intellij.navigation.JBProtocolNavigateCommand.Companion.NAVIGATE_COMMAND import com.intellij.navigation.JBProtocolNavigateCommand.Companion.PATH_KEY import com.intellij.navigation.JBProtocolNavigateCommand.Companion.PROJECT_NAME_KEY import com.intellij.navigation.JBProtocolNavigateCommand.Companion.REFERENCE_TARGET import com.intellij.navigation.JBProtocolNavigateCommand.Companion.SELECTION import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.JetBrainsProtocolHandler import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Caret import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.ide.CopyPasteManager import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtil import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFileSystemItem import com.intellij.util.PlatformUtils import com.intellij.util.PlatformUtils.* import java.awt.datatransfer.StringSelection import java.util.stream.Collectors import java.util.stream.IntStream class CopyTBXReferenceAction : DumbAwareAction() { init { isEnabledInModalContext = true setInjectedContext(true) } override fun update(e: AnActionEvent) { var plural = false var enabled: Boolean var paths = false val dataContext = e.dataContext val editor = CommonDataKeys.EDITOR.getData(dataContext) if (editor != null && FileDocumentManager.getInstance().getFile(editor.document) != null) { enabled = true } else { val elements = getElementsToCopy(editor, dataContext) enabled = !elements.isEmpty() plural = elements.size > 1 paths = elements.stream().allMatch { el -> el is PsiFileSystemItem && getQualifiedNameFromProviders(el) == null } } enabled = enabled && (ActionPlaces.MAIN_MENU == e.place) e.presentation.isEnabled = enabled if (ActionPlaces.isPopupPlace(e.place)) { e.presentation.isVisible = enabled } else { e.presentation.isVisible = true } e.presentation.text = if (paths) if (plural) "Cop&y Toolbox Relative Paths URL" else "Cop&y Toolbox Relative Path URL" else if (plural) "Cop&y Toolbox References URL" else "Cop&y Toolbox Reference URL" } override fun actionPerformed(e: AnActionEvent) { val dataContext = e.dataContext val editor = CommonDataKeys.EDITOR.getData(dataContext) val project = CommonDataKeys.PROJECT.getData(dataContext) val elements = getElementsToCopy(editor, dataContext) if (project == null) { LOG.warn("'Copy TBX Reference' action cannot find project.") return } var copy = createJetbrainsLink(project, elements, editor) if (copy != null) { CopyPasteManager.getInstance().setContents(CopyReferenceFQNTransferable(copy)) setStatusBarText(project, IdeBundle.message("message.reference.to.fqn.has.been.copied", copy)) } else if (editor != null) { val document = editor.document val file = PsiDocumentManager.getInstance(project).getCachedPsiFile(document) if (file != null) { val logicalPosition = editor.caretModel.logicalPosition val path = "${getFileFqn(file)}:${logicalPosition.line + 1}:${logicalPosition.column + 1}" copy = createLink(editor, project, createRefs(true, path, "")) CopyPasteManager.getInstance().setContents(StringSelection(copy)) setStatusBarText(project, "$copy has been copied") } return } highlight(editor, project, elements) } companion object { private val LOG = Logger.getInstance(CopyTBXReferenceAction::class.java) private const val JETBRAINS_NAVIGATE = JetBrainsProtocolHandler.PROTOCOL private val IDE_TAGS = mapOf(IDEA_PREFIX to "idea", IDEA_CE_PREFIX to "idea", APPCODE_PREFIX to "appcode", CLION_PREFIX to "clion", PYCHARM_PREFIX to "pycharm", PYCHARM_CE_PREFIX to "pycharm", PYCHARM_EDU_PREFIX to "pycharm", PHP_PREFIX to "php-storm", RUBY_PREFIX to "rubymine", WEB_PREFIX to "web-storm", RIDER_PREFIX to "rd", GOIDE_PREFIX to "goland") fun createJetbrainsLink(project: Project, elements: List<PsiElement>, editor: Editor?): String? { val refsParameters = IntArray(elements.size) { i -> i } .associateBy({ it }, { elementToFqn(elements[it], editor) }) .filter { it.value != null } .mapValues { FileUtil.getLocationRelativeToUserHome(it.value, false) } .entries .ifEmpty { return null } .joinToString("") { createRefs(isFile(elements[it.key]), it.value, parameterIndex(it.key, elements.size)) } return createLink(editor, project, refsParameters) } private fun isFile(element: PsiElement) = element is PsiFileSystemItem && getQualifiedNameFromProviders(element) == null private fun parameterIndex(index: Int, size: Int) = if (size == 1) "" else "${index + 1}" private fun createRefs(isFile: Boolean, reference: String?, index: String) = "&${if (isFile) PATH_KEY else FQN_KEY}${index}=$reference" private fun createLink(editor: Editor?, project: Project, refsParameters: String?): String? { val tool = IDE_TAGS[PlatformUtils.getPlatformPrefix()] if (tool == null) { LOG.warn("Cannot find TBX tool for IDE: ${PlatformUtils.getPlatformPrefix()}") return null } val selectionParameters = getSelectionParameters(editor) ?: "" val projectParameter = "$PROJECT_NAME_KEY=${project.name}" return "$JETBRAINS_NAVIGATE$tool/$NAVIGATE_COMMAND/$REFERENCE_TARGET?$projectParameter$refsParameters$selectionParameters" } private fun getSelectionParameters(editor: Editor?): String? { if (editor == null) { return null } ApplicationManager.getApplication().assertReadAccessAllowed() if (editor.caretModel.supportsMultipleCarets()) { val carets = editor.caretModel.allCarets return IntStream.range(0, carets.size).mapToObj { i -> getSelectionParameters(editor, carets[i], parameterIndex(i, carets.size)) } .filter { it != null }.collect(Collectors.joining()) } else { return getSelectionParameters(editor, editor.caretModel.currentCaret, "") } } private fun getSelectionParameters(editor: Editor, caret: Caret, index: String): String? = getSelectionRange(editor, caret)?.let { "&$SELECTION$index=$it" } private fun getSelectionRange(editor: Editor, caret: Caret): String? { if (!caret.hasSelection()) { return null } val selectionStart = editor.visualToLogicalPosition(caret.selectionStartPosition) val selectionEnd = editor.visualToLogicalPosition(caret.selectionEndPosition) return String.format("%d:%d-%d:%d", selectionStart.line + 1, selectionStart.column + 1, selectionEnd.line + 1, selectionEnd.column + 1) } } }
apache-2.0
5fff575c7f2e92710e36d5675b051a9f
42.194595
140
0.68373
4.76446
false
false
false
false
akhbulatov/wordkeeper
app/src/main/java/com/akhbulatov/wordkeeper/presentation/ui/wordcategories/WordCategoriesViewModel.kt
1
4558
package com.akhbulatov.wordkeeper.presentation.ui.wordcategories import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.akhbulatov.wordkeeper.domain.global.models.WordCategory import com.akhbulatov.wordkeeper.domain.wordcategory.WordCategoryInteractor import com.akhbulatov.wordkeeper.presentation.global.mvvm.BaseViewModel import com.akhbulatov.wordkeeper.presentation.global.navigation.Screens import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.launch import ru.terrakok.cicerone.Router import javax.inject.Inject class WordCategoriesViewModel @Inject constructor( private val router: Router, private val wordCategoryInteractor: WordCategoryInteractor ) : BaseViewModel() { private val _viewState = MutableLiveData<ViewState>() val viewState: LiveData<ViewState> get() = _viewState private val currentViewState: ViewState get() = _viewState.value!! private var loadedWordCategories = listOf<WordCategory>() init { _viewState.value = ViewState() } fun loadWordCategories() { viewModelScope.launch { wordCategoryInteractor.getWordCategories() .onStart { _viewState.value = currentViewState.copy(emptyProgress = true) } .onEach { _viewState.value = currentViewState.copy(emptyProgress = false) } .catch { _viewState.value = currentViewState.copy( emptyProgress = false, emptyError = Pair(true, it.message) ) } .collect { loadedWordCategories = it if (it.isNotEmpty()) { _viewState.value = currentViewState.copy( emptyData = false, emptyError = Pair(false, null), wordCategories = Pair(true, it) ) } else { _viewState.value = currentViewState.copy( emptyData = true, emptyError = Pair(false, null), wordCategories = Pair(false, it) ) } } } } fun onWordCategoryClicked(wordCategory: WordCategory) { router.navigateTo(Screens.CategoryWords(wordCategory.name)) } fun onAddWordCategoryClicked(name: String) { val wordCategory = WordCategory(name = name) viewModelScope.launch { wordCategoryInteractor.addWordCategory(wordCategory) } } fun onEditWordCategoryClicked(id: Long, name: String) { val wordCategory = WordCategory( id = id, name = name ) viewModelScope.launch { wordCategoryInteractor.editWordCategory(wordCategory) } } fun onDeleteWordCategoryWithWordsClicked(wordCategory: WordCategory) { viewModelScope.launch { wordCategoryInteractor.deleteWordCategoryWithWords(wordCategory) } } fun onSearchWordCategoryChanged(query: String) { viewModelScope.launch { if (query.isNotBlank()) { val foundWords = wordCategoryInteractor.searchWordCategories(query, loadedWordCategories) _viewState.value = currentViewState.copy( emptySearchResult = Pair(foundWords.isEmpty(), query), wordCategories = Pair(true, foundWords) ) } else { _viewState.value = currentViewState.copy( emptySearchResult = Pair(false, null), wordCategories = Pair(true, loadedWordCategories) ) } } } fun onCloseSearchWordCategoryClicked() { _viewState.value = currentViewState.copy( emptySearchResult = Pair(false, null), wordCategories = Pair(true, loadedWordCategories) ) } data class ViewState( val emptyProgress: Boolean = false, val emptyData: Boolean = false, val emptyError: Pair<Boolean, String?> = Pair(false, null), val emptySearchResult: Pair<Boolean, String?> = Pair(false, null), val wordCategories: Pair<Boolean, List<WordCategory>> = Pair(false, emptyList()) ) }
apache-2.0
a6ec408b220676ea80ea1259999fed00
35.758065
105
0.609478
5.558537
false
false
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/Decimator.kt
1
2277
package org.runestar.client.updater.mapper.std.classes import org.objectweb.asm.Opcodes.BIPUSH import org.objectweb.asm.Opcodes.PUTFIELD import org.objectweb.asm.Type.INT_TYPE import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.OrderMapper import org.runestar.client.updater.mapper.MethodParameters import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.withDimensions import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Field2 import org.runestar.client.updater.mapper.Instruction2 import org.runestar.client.updater.mapper.Method2 class Decimator : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.superType == Any::class.type } .and { it.instanceFields.size == 3 } .and { it.instanceFields.count { it.type == INT_TYPE.withDimensions(2) } == 1 } class resample : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == ByteArray::class.type } } class inputRate : OrderMapper.InConstructor.Field(Decimator::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } class outputRate : OrderMapper.InConstructor.Field(Decimator::class, 1) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } class table : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == INT_TYPE.withDimensions(2) } } @MethodParameters("rate") class scaleRate : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == INT_TYPE } .and { it.instructions.none { it.opcode == BIPUSH && it.intOperand == 6 } } } @MethodParameters("position") class scalePosition : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == INT_TYPE } .and { it.instructions.any { it.opcode == BIPUSH && it.intOperand == 6 } } } }
mit
2df5b1947578867063f79be3e8593ee2
44.56
112
0.721124
4.110108
false
false
false
false
denzelby/telegram-bot-bumblebee
telegram-bot-bumblebee-core/src/main/kotlin/com/github/bumblebee/command/youtube/YoutubeUnsubscribeCommand.kt
1
2170
package com.github.bumblebee.command.youtube import com.github.bumblebee.command.SingleArgumentCommand import com.github.bumblebee.command.youtube.entity.Subscription import com.github.bumblebee.command.youtube.service.YoutubeSubscriptionService import com.github.bumblebee.service.RandomPhraseService import com.github.telegram.api.BotApi import com.github.telegram.domain.Update import org.springframework.stereotype.Component @Component class YoutubeUnsubscribeCommand(private val botApi: BotApi, private val service: YoutubeSubscriptionService, private val randomPhraseService: RandomPhraseService) : SingleArgumentCommand() { override fun handleCommand(update: Update, chatId: Long, argument: String?) { if (argument == null) { botApi.sendMessage(chatId, randomPhraseService.surprise()) return } val channelId: String = argument service.getSubscriptions().forEach { sub -> if (sub.channelId == channelId) { processUnsubscription(sub, channelId, chatId) return } } botApi.sendMessage(chatId, "Channel to unsubscribe not exist!") } private fun processUnsubscription(sub: Subscription, channelId: String, chatId: Long) { val chats = sub.chats for (chat in chats) { if (chat.chatId == chatId) { if (chats.size == 1) { removeChannel(sub, channelId, chatId) return } if (chats.size > 1) { chats.remove(chat) service.storeSubscription(sub) botApi.sendMessage(chatId, "Chat successfully unsubscribed!") return } } } } private fun removeChannel(sub: Subscription, channelId: String, chatId: Long) { if (service.unsubscribeChannel(channelId)) { service.deleteSubscription(sub) service.getSubscriptions().remove(sub) botApi.sendMessage(chatId, "Channel removed!") } } }
mit
807d7db4004344b2c714ad3e61a0492d
37.070175
113
0.614747
5.130024
false
false
false
false
Virtlink/aesi
paplj/src/main/kotlin/com/virtlink/terms/InterningTermFactory.kt
1
2096
package com.virtlink.terms import com.google.common.collect.Interners /** * Term factory that ensures maximal sharing. */ open class InterningTermFactory(): DefaultTermFactory() { //class InterningTermFactory(private val innerTermFactory: TermFactory): TermFactory() { // /** // * Initializes this factory with the default term factory. // */ // constructor() : this(DefaultTermFactory()) /** * The term interner, which ensures that two instances of the same term * refer to the same object in memory (reference equality). */ private val interner = Interners.newWeakInterner<ITerm>() // // override fun createString(value: String): StringTerm // = getTerm(this.innerTermFactory.createString(value)) // // override fun createInt(value: Int): IntTerm // = getTerm(this.innerTermFactory.createInt(value)) // // override fun <T: ITerm> createList(elements: List<T>): ListTerm<T> // = getTerm(this.innerTermFactory.createList(elements)) // // override fun <T : ITerm> createOption(value: T?): OptionTerm<T> // = getTerm(this.innerTermFactory.createOption(value)) // // override fun createTerm(constructor: ITermConstructor, children: List<ITerm>): ITerm // = getTerm(this.innerTermFactory.createTerm(constructor, children)) // // override fun registerBuilder(constructor: ITermConstructor, builder: (ITermConstructor, List<ITerm>) -> ITerm) // = this.innerTermFactory.registerBuilder(constructor, builder) // // override fun unregisterBuilder(constructor: ITermConstructor) // = this.innerTermFactory.unregisterBuilder(constructor) /** * Gets the interned term that is equal to the given term; * or the given term when the term was not interned yet. * * This is the core method that ensures maximal sharing. * * @param term The input term. * @return The resulting term. */ override fun <T: ITerm> getTerm(term: T): T { @Suppress("UNCHECKED_CAST") return this.interner.intern(term) as T } }
apache-2.0
29d598a99bfdb483fb5cbce55e6fe5f2
35.155172
116
0.677004
4.268839
false
false
false
false
vhromada/Catalog
core/src/main/kotlin/com/github/vhromada/catalog/domain/Song.kt
1
1532
package com.github.vhromada.catalog.domain import javax.persistence.Column import javax.persistence.Entity import javax.persistence.FetchType import javax.persistence.GeneratedValue import javax.persistence.GenerationType import javax.persistence.Id import javax.persistence.JoinColumn import javax.persistence.ManyToOne import javax.persistence.SequenceGenerator import javax.persistence.Table /** * A class represents song. * * @author Vladimir Hromada */ @Entity @Table(name = "songs") @Suppress("JpaDataSourceORMInspection") data class Song( /** * ID */ @Id @SequenceGenerator(name = "song_generator", sequenceName = "songs_sq", allocationSize = 1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "song_generator") var id: Int?, /** * UUID */ val uuid: String, /** * Name */ @Column(name = "song_name") var name: String, /** * Length */ @Column(name = "song_length") var length: Int, /** * Note */ var note: String?, /** * Music */ @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "music") var music: Music? = null ) : Audit() { /** * Merges song. * * @param song song */ fun merge(song: Song) { name = song.name length = song.length note = song.note } override fun toString(): String { return "Song(id=$id, uuid=$uuid, name=$name, length=$length, note=$note, music=${music?.id})" } }
mit
b6c26bf6cd14bf8e698ee23b7dee55e7
19.157895
101
0.619452
3.948454
false
false
false
false
square/okhttp
mockwebserver/src/main/kotlin/mockwebserver3/RecordedRequest.kt
4
4149
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mockwebserver3 import java.io.IOException import java.net.Inet6Address import java.net.Socket import javax.net.ssl.SSLSocket import okhttp3.Handshake import okhttp3.Handshake.Companion.handshake import okhttp3.Headers import okhttp3.HttpUrl import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.TlsVersion import okio.Buffer /** An HTTP request that came into the mock web server. */ class RecordedRequest @JvmOverloads constructor( val requestLine: String, /** All headers. */ val headers: Headers, /** * The sizes of the chunks of this request's body, or an empty list if the request's body * was empty or unchunked. */ val chunkSizes: List<Int>, /** The total size of the body of this POST request (before truncation).*/ val bodySize: Long, /** The body of this POST request. This may be truncated. */ val body: Buffer, /** * The index of this request on its HTTP connection. Since a single HTTP connection may serve * multiple requests, each request is assigned its own sequence number. */ val sequenceNumber: Int, socket: Socket, /** * The failure MockWebServer recorded when attempting to decode this request. If, for example, * the inbound request was truncated, this exception will be non-null. */ val failure: IOException? = null ) { val method: String? val path: String? /** * The TLS handshake of the connection that carried this request, or null if the request was * received without TLS. */ val handshake: Handshake? val requestUrl: HttpUrl? @get:JvmName("-deprecated_utf8Body") @Deprecated( message = "Use body.readUtf8()", replaceWith = ReplaceWith("body.readUtf8()"), level = DeprecationLevel.ERROR) val utf8Body: String get() = body.readUtf8() /** Returns the connection's TLS version or null if the connection doesn't use SSL. */ val tlsVersion: TlsVersion? get() = handshake?.tlsVersion init { if (socket is SSLSocket) { try { this.handshake = socket.session.handshake() } catch (e: IOException) { throw IllegalArgumentException(e) } } else { this.handshake = null } if (requestLine.isNotEmpty()) { val methodEnd = requestLine.indexOf(' ') val pathEnd = requestLine.indexOf(' ', methodEnd + 1) this.method = requestLine.substring(0, methodEnd) var path = requestLine.substring(methodEnd + 1, pathEnd) if (!path.startsWith("/")) { path = "/" } this.path = path val scheme = if (socket is SSLSocket) "https" else "http" val localPort = socket.localPort val hostAndPort = headers[":authority"] ?: headers["Host"] ?: when (val inetAddress = socket.localAddress) { is Inet6Address -> "[${inetAddress.hostAddress}]:$localPort" else -> "${inetAddress.hostAddress}:$localPort" } // Allow null in failure case to allow for testing bad requests this.requestUrl = "$scheme://$hostAndPort$path".toHttpUrlOrNull() } else { this.requestUrl = null this.method = null this.path = null } } @Deprecated( message = "Use body.readUtf8()", replaceWith = ReplaceWith("body.readUtf8()"), level = DeprecationLevel.WARNING) fun getUtf8Body(): String = body.readUtf8() /** Returns the first header named [name], or null if no such header exists. */ fun getHeader(name: String): String? = headers.values(name).firstOrNull() override fun toString(): String = requestLine }
apache-2.0
53baf511bcdafed5f8dc1f1d5dd44fa0
29.962687
96
0.680164
4.308411
false
false
false
false
JetBrains/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/checkin/RearrangeBeforeCheckinHandler.kt
1
1943
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.checkin import com.intellij.codeInsight.CodeInsightBundle import com.intellij.codeInsight.actions.AbstractLayoutCodeProcessor import com.intellij.codeInsight.actions.RearrangeCodeProcessor import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.vcs.CheckinProjectPanel import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.changes.CommitContext import com.intellij.openapi.vcs.changes.ui.BooleanCommitOption import com.intellij.openapi.vcs.checkin.CheckinHandlerUtil.getPsiFiles import com.intellij.openapi.vcs.ui.RefreshableOnComponent import com.intellij.openapi.vfs.VirtualFile class RearrangeCheckinHandlerFactory : CheckinHandlerFactory() { override fun createHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler = RearrangeBeforeCheckinHandler(panel.project) } class RearrangeBeforeCheckinHandler(project: Project) : CodeProcessorCheckinHandler(project) { override fun getBeforeCheckinConfigurationPanel(): RefreshableOnComponent = BooleanCommitOption(project, VcsBundle.message("checkbox.checkin.options.rearrange.code"), true, settings::REARRANGE_BEFORE_PROJECT_COMMIT) .withCheckinHandler(this) override fun isEnabled(): Boolean = settings.REARRANGE_BEFORE_PROJECT_COMMIT override fun getProgressMessage(): String = VcsBundle.message("progress.text.rearranging.code") override fun createCodeProcessor(files: List<VirtualFile>): AbstractLayoutCodeProcessor = RearrangeCodeProcessor(project, getPsiFiles(project, files), COMMAND_NAME, null, true) companion object { @JvmField @NlsSafe val COMMAND_NAME: String = CodeInsightBundle.message("process.rearrange.code.before.commit") } }
apache-2.0
f673c702e402be046153cfdb9defbeb5
47.6
140
0.815234
4.693237
false
false
false
false
google/iosched
shared/src/main/java/com/google/samples/apps/iosched/shared/data/session/json/SpeakerDeserializer.kt
4
1748
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.samples.apps.iosched.shared.data.session.json import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.google.samples.apps.iosched.model.Speaker import java.lang.reflect.Type /** * Deserializer for [Speaker]s. */ class SpeakerDeserializer : JsonDeserializer<Speaker> { override fun deserialize( json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext? ): Speaker { val obj = json?.asJsonObject!! val social = obj.getAsJsonObject("socialLinks") return Speaker( id = obj.get("id").asString, name = obj.get("name").asString, imageUrl = obj.get("thumbnailUrl")?.asString ?: "", company = obj.get("company")?.asString ?: "", biography = obj.get("bio")?.asString ?: "", websiteUrl = social?.get("Website")?.asString, twitterUrl = social?.get("Twitter")?.asString, githubUrl = social?.get("GitHub")?.asString, linkedInUrl = social?.get("LinkedIn")?.asString ) } }
apache-2.0
451214d5ba98202252aa45a623a615db
34.673469
75
0.668764
4.425316
false
false
false
false
allotria/intellij-community
plugins/git4idea/src/git4idea/repo/GitRepoInfo.kt
2
1609
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.repo import com.intellij.dvcs.repo.Repository import com.intellij.vcs.log.Hash import git4idea.GitLocalBranch import git4idea.GitReference import git4idea.GitRemoteBranch import gnu.trove.THashMap import org.jetbrains.annotations.NonNls data class GitRepoInfo(val currentBranch: GitLocalBranch?, val currentRevision: String?, val state: Repository.State, val remotes: Collection<GitRemote>, val localBranchesWithHashes: Map<GitLocalBranch, Hash>, val remoteBranchesWithHashes: Map<GitRemoteBranch, Hash>, val branchTrackInfos: Collection<GitBranchTrackInfo>, val submodules: Collection<GitSubmoduleInfo>, val hooksInfo: GitHooksInfo, val isShallow: Boolean) { val branchTrackInfosMap = THashMap<String, GitBranchTrackInfo>(GitReference.BRANCH_NAME_HASHING_STRATEGY).apply { branchTrackInfos.associateByTo(this) { it.localBranch.name } } val remoteBranches: Collection<GitRemoteBranch> @Deprecated("") get() = remoteBranchesWithHashes.keys @NonNls override fun toString() = "GitRepoInfo{current=$currentBranch, remotes=$remotes, localBranches=$localBranchesWithHashes, " + "remoteBranches=$remoteBranchesWithHashes, trackInfos=$branchTrackInfos, submodules=$submodules, hooks=$hooksInfo}" }
apache-2.0
bb5cad6da9ace06f22e6fae02c3c5e7d
47.757576
143
0.691734
5.107937
false
false
false
false
matrix-org/matrix-android-sdk
matrix-sdk-crypto/src/main/java/org/matrix/androidsdk/crypto/verification/VerificationManager.kt
1
18414
/* * 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 org.matrix.androidsdk.crypto.verification import android.os.Handler import android.os.Looper import org.matrix.androidsdk.core.JsonUtility import org.matrix.androidsdk.core.Log import org.matrix.androidsdk.core.callback.ApiCallback import org.matrix.androidsdk.core.model.MatrixError import org.matrix.androidsdk.crypto.MXCrypto import org.matrix.androidsdk.crypto.data.MXDeviceInfo import org.matrix.androidsdk.crypto.data.MXUsersDevicesMap import org.matrix.androidsdk.crypto.interfaces.CryptoEvent import org.matrix.androidsdk.crypto.interfaces.CryptoSession import org.matrix.androidsdk.crypto.rest.model.crypto.* import java.util.* import kotlin.collections.HashMap /** * Manages all current verifications transactions with short codes. * Short codes interactive verification is a more user friendly way of verifying devices * that is still maintaining a good level of security (alternative to the 43-character strings compare method). */ class VerificationManager ( private val session: CryptoSession, private val mxCrypto: MXCrypto ) : VerificationTransaction.Listener { interface VerificationManagerListener { fun transactionCreated(tx: VerificationTransaction) fun transactionUpdated(tx: VerificationTransaction) fun markedAsManuallyVerified(userId: String, deviceId: String) } private val uiHandler = Handler(Looper.getMainLooper()) // map [sender : [transaction]] private val txMap = HashMap<String, HashMap<String, VerificationTransaction>>() // Event received from the sync fun onToDeviceEvent(event: CryptoEvent) { mxCrypto.getDecryptingThreadHandler().post { when (event.getType()) { CryptoEvent.EVENT_TYPE_KEY_VERIFICATION_START -> { onStartRequestReceived(event) } CryptoEvent.EVENT_TYPE_KEY_VERIFICATION_CANCEL -> { onCancelReceived(event) } CryptoEvent.EVENT_TYPE_KEY_VERIFICATION_ACCEPT -> { onAcceptReceived(event) } CryptoEvent.EVENT_TYPE_KEY_VERIFICATION_KEY -> { onKeyReceived(event) } CryptoEvent.EVENT_TYPE_KEY_VERIFICATION_MAC -> { onMacReceived(event) } else -> { //ignore } } } } private var listeners = ArrayList<VerificationManagerListener>() fun addListener(listener: VerificationManagerListener) { uiHandler.post { if (!listeners.contains(listener)) { listeners.add(listener) } } } fun removeListener(listener: VerificationManagerListener) { uiHandler.post { listeners.remove(listener) } } private fun dispatchTxAdded(tx: VerificationTransaction) { uiHandler.post { listeners.forEach { try { it.transactionCreated(tx) } catch (e: Throwable) { Log.e(LOG_TAG, "## Error while notifying listeners", e) } } } } private fun dispatchTxUpdated(tx: VerificationTransaction) { uiHandler.post { listeners.forEach { try { it.transactionUpdated(tx) } catch (e: Throwable) { Log.e(LOG_TAG, "## Error while notifying listeners", e) } } } } fun markedLocallyAsManuallyVerified(userId: String, deviceID: String) { mxCrypto.setDeviceVerification(MXDeviceInfo.DEVICE_VERIFICATION_VERIFIED, deviceID, userId, object : ApiCallback<Void> { override fun onSuccess(info: Void?) { uiHandler.post { listeners.forEach { try { it.markedAsManuallyVerified(userId, deviceID) } catch (e: Throwable) { Log.e(LOG_TAG, "## Error while notifying listeners", e) } } } } override fun onUnexpectedError(e: Exception?) { Log.e(SASVerificationTransaction.LOG_TAG, "## Manual verification failed in state", e) } override fun onNetworkError(e: Exception?) { Log.e(SASVerificationTransaction.LOG_TAG, "## Manual verification failed in state", e) } override fun onMatrixError(e: MatrixError?) { Log.e(SASVerificationTransaction.LOG_TAG, "## Manual verification failed in state " + e?.mReason) } }) } private fun onStartRequestReceived(event: CryptoEvent) { val startReq = JsonUtility.getBasicGson() .fromJson(event.content, KeyVerificationStart::class.java) val otherUserId = event.getSender() if (!startReq.isValid()) { Log.e(SASVerificationTransaction.LOG_TAG, "## received invalid verification request") if (startReq.transactionID != null) { cancelTransaction( session, startReq.transactionID!!, otherUserId, startReq?.fromDevice ?: event.senderKey, CancelCode.UnknownMethod ) } return } //Download device keys prior to everything checkKeysAreDownloaded( session, otherUserId, startReq, success = { Log.d(SASVerificationTransaction.LOG_TAG, "## SAS onStartRequestReceived ${startReq.transactionID!!}") val tid = startReq.transactionID!! val existing = getExistingTransaction(otherUserId, tid) val existingTxs = getExistingTransactionsForUser(otherUserId) if (existing != null) { //should cancel both! Log.d(SASVerificationTransaction.LOG_TAG, "## SAS onStartRequestReceived - Request exist with same if ${startReq.transactionID!!}") existing.cancel(session, CancelCode.UnexpectedMessage) cancelTransaction(session, tid, otherUserId, startReq.fromDevice!!, CancelCode.UnexpectedMessage) } else if (existingTxs?.isEmpty() == false) { Log.d(SASVerificationTransaction.LOG_TAG, "## SAS onStartRequestReceived - There is already a transaction with this user ${startReq.transactionID!!}") //Multiple keyshares between two devices: any two devices may only have at most one key verification in flight at a time. existingTxs.forEach { it.cancel(session, CancelCode.UnexpectedMessage) } cancelTransaction(session, tid, otherUserId, startReq.fromDevice!!, CancelCode.UnexpectedMessage) } else { //Ok we can create if (KeyVerificationStart.VERIF_METHOD_SAS == startReq.method) { Log.d(SASVerificationTransaction.LOG_TAG, "## SAS onStartRequestReceived - request accepted ${startReq.transactionID!!}") val tx = IncomingSASVerificationTransaction(startReq.transactionID!!, otherUserId) addTransaction(tx) tx.acceptToDeviceEvent(session, otherUserId, startReq) } else { Log.e(SASVerificationTransaction.LOG_TAG, "## SAS onStartRequestReceived - unknown method ${startReq.method}") cancelTransaction(session, tid, otherUserId, startReq.fromDevice ?: event.senderKey, CancelCode.UnknownMethod) } } }, error = { cancelTransaction(session, startReq.transactionID!!, otherUserId, startReq.fromDevice!!, CancelCode.UnexpectedMessage) }) } private fun checkKeysAreDownloaded(session: CryptoSession, otherUserId: String, startReq: KeyVerificationStart, success: (MXUsersDevicesMap<MXDeviceInfo>) -> Unit, error: () -> Unit) { mxCrypto.getDeviceList().downloadKeys(listOf(otherUserId), true, object : ApiCallback<MXUsersDevicesMap<MXDeviceInfo>> { override fun onUnexpectedError(e: Exception) { mxCrypto.getDecryptingThreadHandler().post { error() } } override fun onNetworkError(e: Exception) { mxCrypto.getDecryptingThreadHandler().post { error() } } override fun onMatrixError(e: MatrixError) { mxCrypto.getDecryptingThreadHandler().post { error() } } override fun onSuccess(info: MXUsersDevicesMap<MXDeviceInfo>) { mxCrypto.getDecryptingThreadHandler().post { if (info.getUserDeviceIds(otherUserId).contains(startReq.fromDevice)) { success(info) } else { error() } } } }) } private fun onCancelReceived(event: CryptoEvent) { Log.d(LOG_TAG, "## SAS onCancelReceived") val cancelReq = JsonUtility.getBasicGson() .fromJson(event.content, KeyVerificationCancel::class.java) if (!cancelReq.isValid()) { //ignore Log.e(LOG_TAG, "## Received invalid accept request") return } val otherUserId = event.getSender() Log.d(LOG_TAG, "## SAS onCancelReceived otherUser:$otherUserId reason:${cancelReq.reason}") val existing = getExistingTransaction(otherUserId, cancelReq.transactionID!!) if (existing == null) { Log.e(LOG_TAG, "## Received invalid cancel request") return } if (existing is SASVerificationTransaction) { existing.cancelledReason = safeValueOf(cancelReq.code) existing.state = SASVerificationTransaction.SASVerificationTxState.OnCancelled } } private fun onAcceptReceived(event: CryptoEvent) { val acceptReq = JsonUtility.getBasicGson() .fromJson(event.content, KeyVerificationAccept::class.java) if (!acceptReq.isValid()) { //ignore Log.e(LOG_TAG, "## Received invalid accept request") return } val otherUserId = event.getSender() val existing = getExistingTransaction(otherUserId, acceptReq.transactionID!!) if (existing == null) { Log.e(LOG_TAG, "## Received invalid accept request") return } if (existing is SASVerificationTransaction) { existing.acceptToDeviceEvent(session, otherUserId, acceptReq) } else { //not other types now } } private fun onKeyReceived(event: CryptoEvent) { val keyReq = JsonUtility.getBasicGson() .fromJson(event.content, KeyVerificationKey::class.java) if (!keyReq.isValid()) { //ignore Log.e(LOG_TAG, "## Received invalid key request") return } val otherUserId = event.getSender() val existing = getExistingTransaction(otherUserId, keyReq.transactionID!!) if (existing == null) { Log.e(LOG_TAG, "## Received invalid accept request") return } if (existing is SASVerificationTransaction) { existing.acceptToDeviceEvent(session, otherUserId, keyReq) } else { //not other types now } } private fun onMacReceived(event: CryptoEvent) { val macReq = JsonUtility.getBasicGson() .fromJson(event.content, KeyVerificationMac::class.java) if (!macReq.isValid()) { //ignore Log.e(LOG_TAG, "## Received invalid key request") return } val otherUserId = event.getSender() val existing = getExistingTransaction(otherUserId, macReq.transactionID!!) if (existing == null) { Log.e(LOG_TAG, "## Received invalid accept request") return } if (existing is SASVerificationTransaction) { existing.acceptToDeviceEvent(session, otherUserId, macReq) } else { //not other types known for now } } fun getExistingTransaction(otherUser: String, tid: String): VerificationTransaction? { synchronized(lock = txMap) { return txMap[otherUser]?.get(tid) } } private fun getExistingTransactionsForUser(otherUser: String): Collection<VerificationTransaction>? { synchronized(txMap) { return txMap[otherUser]?.values } } private fun removeTransaction(otherUser: String, tid: String) { synchronized(txMap) { txMap[otherUser]?.remove(tid)?.removeListener(this) } } private fun addTransaction(tx: VerificationTransaction) { tx.otherUserId.let { otherUserId -> synchronized(txMap) { if (txMap[otherUserId] == null) { txMap[otherUserId] = HashMap() } txMap[otherUserId]?.set(tx.transactionId, tx) dispatchTxAdded(tx) tx.addListener(this) } } } fun beginKeyVerificationSAS(userId: String, deviceID: String): String? { return beginKeyVerification(KeyVerificationStart.VERIF_METHOD_SAS, userId, deviceID) } fun beginKeyVerification(method: String, userId: String, deviceID: String): String? { val txID = createUniqueIDForTransaction(userId, deviceID) //should check if already one (and cancel it) if (KeyVerificationStart.VERIF_METHOD_SAS == method) { val tx = OutgoingSASVerificationRequest(txID, userId, deviceID) addTransaction(tx) mxCrypto.getDecryptingThreadHandler().post { tx.start(session) } return txID } else { throw IllegalArgumentException("Unknown verification method") } } /** * This string must be unique for the pair of users performing verification for the duration that the transaction is valid */ private fun createUniqueIDForTransaction(userId: String, deviceID: String): String { val buff = StringBuffer() buff .append(session.myUserId).append("|") .append(mxCrypto.myDevice.deviceId).append("|") .append(userId).append("|") .append(deviceID).append("|") .append(UUID.randomUUID().toString()) return buff.toString() } override fun transactionUpdated(tx: VerificationTransaction) { dispatchTxUpdated(tx) if (tx is SASVerificationTransaction && (tx.state == SASVerificationTransaction.SASVerificationTxState.Cancelled || tx.state == SASVerificationTransaction.SASVerificationTxState.OnCancelled || tx.state == SASVerificationTransaction.SASVerificationTxState.Verified) ) { //remove this.removeTransaction(tx.otherUserId, tx.transactionId) } } companion object { val LOG_TAG: String = VerificationManager::class.java.name fun cancelTransaction(session: CryptoSession, transactionId: String, userId: String, userDevice: String, code: CancelCode) { val cancelMessage = KeyVerificationCancel.create(transactionId, code) val contentMap = MXUsersDevicesMap<Any>() contentMap.setObject(cancelMessage, userId, userDevice) session.requireCrypto() .getCryptoRestClient() .sendToDevice(CryptoEvent.EVENT_TYPE_KEY_VERIFICATION_CANCEL, contentMap, transactionId, object : ApiCallback<Void> { override fun onSuccess(info: Void?) { Log.d(SASVerificationTransaction.LOG_TAG, "## SAS verification [$transactionId] canceled for reason ${code.value}") } override fun onUnexpectedError(e: Exception?) { Log.e(SASVerificationTransaction.LOG_TAG, "## SAS verification [$transactionId] failed to cancel.", e) } override fun onNetworkError(e: Exception?) { Log.e(SASVerificationTransaction.LOG_TAG, "## SAS verification [$transactionId] failed to cancel.", e) } override fun onMatrixError(e: MatrixError?) { Log.e(SASVerificationTransaction.LOG_TAG, "## SAS verification [$transactionId] failed to cancel. ${e?.localizedMessage}") } }) } } }
apache-2.0
b3215b8b2a78d01ffdd1d24992fda70a
40.568849
155
0.571522
5.68158
false
false
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/common/test/selects/SelectRendezvousChannelTest.kt
1
12116
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ @file:Suppress("NAMED_ARGUMENTS_NOT_ALLOWED") // KT-21913 package kotlinx.coroutines.selects import kotlinx.coroutines.* import kotlinx.coroutines.channels.* import kotlinx.coroutines.intrinsics.* import kotlin.test.* class SelectRendezvousChannelTest : TestBase() { @Test fun testSelectSendSuccess() = runTest { expect(1) val channel = Channel<String>(Channel.RENDEZVOUS) launch { expect(2) assertEquals("OK", channel.receive()) finish(6) } yield() // to launched coroutine expect(3) select<Unit> { channel.onSend("OK") { expect(4) } } expect(5) } @Test fun testSelectSendSuccessWithDefault() = runTest { expect(1) val channel = Channel<String>(Channel.RENDEZVOUS) launch { expect(2) assertEquals("OK", channel.receive()) finish(6) } yield() // to launched coroutine expect(3) select<Unit> { channel.onSend("OK") { expect(4) } default { expectUnreached() } } expect(5) } @Test fun testSelectSendWaitWithDefault() = runTest { expect(1) val channel = Channel<String>(Channel.RENDEZVOUS) select<Unit> { channel.onSend("OK") { expectUnreached() } default { expect(2) } } expect(3) // make sure receive blocks (select above is over) launch { expect(5) assertEquals("CHK", channel.receive()) finish(8) } expect(4) yield() expect(6) channel.send("CHK") expect(7) } @Test fun testSelectSendWait() = runTest { expect(1) val channel = Channel<String>(Channel.RENDEZVOUS) launch { expect(3) assertEquals("OK", channel.receive()) expect(4) } expect(2) select<Unit> { channel.onSend("OK") { expect(5) } } finish(6) } @Test fun testSelectReceiveSuccess() = runTest { expect(1) val channel = Channel<String>(Channel.RENDEZVOUS) launch { expect(2) channel.send("OK") finish(6) } yield() // to launched coroutine expect(3) select<Unit> { channel.onReceive { v -> expect(4) assertEquals("OK", v) } } expect(5) } @Test fun testSelectReceiveSuccessWithDefault() = runTest { expect(1) val channel = Channel<String>(Channel.RENDEZVOUS) launch { expect(2) channel.send("OK") finish(6) } yield() // to launched coroutine expect(3) select<Unit> { channel.onReceive { v -> expect(4) assertEquals("OK", v) } default { expectUnreached() } } expect(5) } @Test fun testSelectReceiveWaitWithDefault() = runTest { expect(1) val channel = Channel<String>(Channel.RENDEZVOUS) select<Unit> { channel.onReceive { expectUnreached() } default { expect(2) } } expect(3) // make sure send blocks (select above is over) launch { expect(5) channel.send("CHK") finish(8) } expect(4) yield() expect(6) assertEquals("CHK", channel.receive()) expect(7) } @Test fun testSelectReceiveWait() = runTest { expect(1) val channel = Channel<String>(Channel.RENDEZVOUS) launch { expect(3) channel.send("OK") expect(4) } expect(2) select<Unit> { channel.onReceive { v -> expect(5) assertEquals("OK", v) } } finish(6) } @Test fun testSelectReceiveClosed() = runTest(expected = { it is ClosedReceiveChannelException }) { expect(1) val channel = Channel<String>(Channel.RENDEZVOUS) channel.close() finish(2) select<Unit> { channel.onReceive { expectUnreached() } } expectUnreached() } @Test fun testSelectReceiveWaitClosed() = runTest(expected = {it is ClosedReceiveChannelException}) { expect(1) val channel = Channel<String>(Channel.RENDEZVOUS) launch { expect(3) channel.close() finish(4) } expect(2) select<Unit> { channel.onReceive { expectUnreached() } } expectUnreached() } @Test fun testSelectSendResourceCleanup() = runTest { val channel = Channel<Int>(Channel.RENDEZVOUS) val n = 1_000 expect(1) repeat(n) { i -> select { channel.onSend(i) { expectUnreached() } default { expect(i + 2) } } } finish(n + 2) } @Test fun testSelectReceiveResourceCleanup() = runTest { val channel = Channel<Int>(Channel.RENDEZVOUS) val n = 1_000 expect(1) repeat(n) { i -> select { channel.onReceive { expectUnreached() } default { expect(i + 2) } } } finish(n + 2) } @Test fun testSelectAtomicFailure() = runTest { val c1 = Channel<Int>(Channel.RENDEZVOUS) val c2 = Channel<Int>(Channel.RENDEZVOUS) expect(1) launch { expect(3) val res = select<String> { c1.onReceive { v1 -> expect(4) assertEquals(42, v1) yield() // back to main expect(7) "OK" } c2.onReceive { "FAIL" } } expect(8) assertEquals("OK", res) } expect(2) c1.send(42) // send to coroutine, suspends expect(5) c2.close() // makes sure that selected expression does not fail! expect(6) yield() // back finish(9) } @Test fun testSelectWaitDispatch() = runTest { val c = Channel<Int>(Channel.RENDEZVOUS) expect(1) launch { expect(3) val res = select<String> { c.onReceive { v -> expect(6) assertEquals(42, v) yield() // back to main expect(8) "OK" } } expect(9) assertEquals("OK", res) } expect(2) yield() // to launch expect(4) c.send(42) // do not suspend expect(5) yield() // to receive expect(7) yield() // again finish(10) } @Test fun testSelectReceiveCatchingWaitClosed() = runTest { expect(1) val channel = Channel<String>(Channel.RENDEZVOUS) launch { expect(3) channel.close() expect(4) } expect(2) select<Unit> { channel.onReceiveCatching { expect(5) assertTrue(it.isClosed) assertNull(it.exceptionOrNull()) } } finish(6) } @Test fun testSelectReceiveCatchingWaitClosedWithCause() = runTest { expect(1) val channel = Channel<String>(Channel.RENDEZVOUS) launch { expect(3) channel.close(TestException()) expect(4) } expect(2) select<Unit> { channel.onReceiveCatching { expect(5) assertTrue(it.isClosed) assertTrue(it.exceptionOrNull() is TestException) } } finish(6) } @Test fun testSelectReceiveCatchingForClosedChannel() = runTest { val channel = Channel<Unit>() channel.close() expect(1) select<Unit> { expect(2) channel.onReceiveCatching { assertTrue(it.isClosed) assertNull(it.exceptionOrNull()) finish(3) } } } @Test fun testSelectReceiveCatching() = runTest { val channel = Channel<Int>(Channel.RENDEZVOUS) val iterations = 10 expect(1) val job = launch { repeat(iterations) { select<Unit> { channel.onReceiveCatching { v -> expect(4 + it * 2) assertEquals(it, v.getOrThrow()) } } } } expect(2) repeat(iterations) { expect(3 + it * 2) channel.send(it) yield() } job.join() finish(3 + iterations * 2) } @Test fun testSelectReceiveCatchingDispatch() = runTest { val c = Channel<Int>(Channel.RENDEZVOUS) expect(1) launch { expect(3) val res = select<String> { c.onReceiveCatching { v -> expect(6) assertEquals(42, v.getOrThrow()) yield() // back to main expect(8) "OK" } } expect(9) assertEquals("OK", res) } expect(2) yield() // to launch expect(4) c.send(42) // do not suspend expect(5) yield() // to receive expect(7) yield() // again finish(10) } @Test fun testSelectSendWhenClosed() = runTest { expect(1) val c = Channel<Int>(Channel.RENDEZVOUS) val sender = launch(start = CoroutineStart.UNDISPATCHED) { expect(2) c.send(1) // enqueue sender expectUnreached() } c.close() // then close assertFailsWith<ClosedSendChannelException> { // select sender should fail expect(3) select { c.onSend(2) { expectUnreached() } } } sender.cancel() finish(4) } // only for debugging internal fun <R> SelectBuilder<R>.default(block: suspend () -> R) { this as SelectBuilderImpl // type assertion if (!trySelect()) return block.startCoroutineUnintercepted(this) } @Test fun testSelectSendAndReceive() = runTest { val c = Channel<Int>() assertFailsWith<IllegalStateException> { select<Unit> { c.onSend(1) { expectUnreached() } c.onReceive { expectUnreached() } } } checkNotBroken(c) } @Test fun testSelectReceiveAndSend() = runTest { val c = Channel<Int>() assertFailsWith<IllegalStateException> { select<Unit> { c.onReceive { expectUnreached() } c.onSend(1) { expectUnreached() } } } checkNotBroken(c) } // makes sure the channel is not broken private suspend fun checkNotBroken(c: Channel<Int>) { coroutineScope { launch { c.send(42) } assertEquals(42, c.receive()) } } }
apache-2.0
e1f3deb10dc2552aab1b05b6d28f6427
24.033058
102
0.463767
4.858059
false
true
false
false
leafclick/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/changes/GHPRChangesBrowser.kt
1
4669
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.ui.changes import com.intellij.diff.util.DiffUserDataKeys import com.intellij.diff.util.DiffUserDataKeysEx import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.ToggleAction import com.intellij.openapi.diff.impl.GenericDataProvider import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.vcs.changes.Change import com.intellij.openapi.vcs.changes.actions.diff.ChangeDiffRequestProducer import com.intellij.openapi.vcs.changes.ui.ChangeDiffRequestChain import com.intellij.openapi.vcs.changes.ui.ChangesBrowserBase import com.intellij.openapi.vcs.changes.ui.VcsTreeModelData import com.intellij.ui.IdeBorderFactory import com.intellij.ui.SideBorder import com.intellij.util.ui.ComponentWithEmptyText import com.intellij.util.ui.tree.TreeUtil import org.jetbrains.plugins.github.pullrequest.comment.GHPRDiffReviewSupport import org.jetbrains.plugins.github.pullrequest.comment.action.GHPRDiffReviewThreadsReloadAction import org.jetbrains.plugins.github.pullrequest.comment.action.GHPRDiffReviewThreadsToggleAction import org.jetbrains.plugins.github.pullrequest.config.GithubPullRequestsProjectUISettings import org.jetbrains.plugins.github.util.GHToolbarLabelAction import java.awt.event.FocusEvent import java.awt.event.FocusListener import javax.swing.border.Border import javax.swing.tree.DefaultTreeModel internal class GHPRChangesBrowser(private val model: GHPRChangesModel, private val diffHelper: GHPRChangesDiffHelper, private val project: Project) : ChangesBrowserBase(project, false, false), ComponentWithEmptyText { init { init() model.addStateChangesListener { myViewer.rebuildTree() } } override fun canShowDiff(): Boolean { val selection = VcsTreeModelData.getListSelectionOrAll(myViewer) return selection.list.any { it is Change && ChangeDiffRequestProducer.canCreate(project, it) } } override fun getDiffRequestProducer(userObject: Any): ChangeDiffRequestChain.Producer? { return if (userObject is Change) { val dataKeys: MutableMap<Key<out Any>, Any?> = mutableMapOf() val diffComputer = diffHelper.getDiffComputer(userObject) if (diffComputer != null) { dataKeys[DiffUserDataKeysEx.CUSTOM_DIFF_COMPUTER] = diffComputer } val reviewSupport = diffHelper.getReviewSupport(userObject) if (reviewSupport != null) { dataKeys[GHPRDiffReviewSupport.KEY] = reviewSupport dataKeys[DiffUserDataKeys.DATA_PROVIDER] = GenericDataProvider().apply { putData(GHPRDiffReviewSupport.DATA_KEY, reviewSupport) } dataKeys[DiffUserDataKeys.CONTEXT_ACTIONS] = listOf(GHToolbarLabelAction("Review:"), GHPRDiffReviewThreadsToggleAction(), GHPRDiffReviewThreadsReloadAction()) } ChangeDiffRequestProducer.create(myProject, userObject, dataKeys) } else null } override fun getEmptyText() = myViewer.emptyText override fun createTreeList(project: Project, showCheckboxes: Boolean, highlightProblems: Boolean): ChangesBrowserTreeList { return super.createTreeList(project, showCheckboxes, highlightProblems).also { it.addFocusListener(object : FocusListener { override fun focusGained(e: FocusEvent?) { if (it.isSelectionEmpty && !it.isEmpty) TreeUtil.selectFirstNode(it) } override fun focusLost(e: FocusEvent?) {} }) } } override fun createViewerBorder(): Border = IdeBorderFactory.createBorder(SideBorder.TOP) override fun buildTreeModel(): DefaultTreeModel { return model.buildChangesTree(grouping) } class ToggleZipCommitsAction : ToggleAction("Commit"), DumbAware { override fun update(e: AnActionEvent) { super.update(e) e.presentation.isEnabledAndVisible = e.getData(DATA_KEY) is GHPRChangesBrowser } override fun isSelected(e: AnActionEvent): Boolean { val project = e.project ?: return false return !GithubPullRequestsProjectUISettings.getInstance(project).zipChanges } override fun setSelected(e: AnActionEvent, state: Boolean) { val project = e.project ?: return GithubPullRequestsProjectUISettings.getInstance(project).zipChanges = !state } } }
apache-2.0
41fc0d6586b39c5febfe423cc6850ff8
41.454545
140
0.746841
4.883891
false
false
false
false
alibaba/transmittable-thread-local
ttl2-compatible/src/test/java/com/alibaba/user_api_test/ttl/TransmittableThreadLocal_Transmitter_registerTransmittee_UserTest.kt
1
4082
package com.alibaba.user_api_test.ttl import com.alibaba.noTtlAgentRun import com.alibaba.ttl.TransmittableThreadLocal.Transmitter import io.kotest.core.spec.style.AnnotationSpec import io.kotest.core.test.config.TestCaseConfig import io.kotest.matchers.booleans.shouldBeTrue import io.mockk.* import org.apache.commons.lang3.JavaVersion import org.apache.commons.lang3.SystemUtils /** * Test [Transmitter] from user code(different package) */ class TransmittableThreadLocal_Transmitter_registerTransmittee_UserTest : AnnotationSpec() { @Suppress("OVERRIDE_DEPRECATION") override fun defaultTestCaseConfig(): TestCaseConfig { // If run under Agent and under java 11+, fail to find proxy classes; // so just skipped. // // error info: // java.lang.NoClassDefFoundError: io/mockk/proxy/jvm/advice/jvm/JvmMockKProxyInterceptor // more info error info see: // https://github.com/alibaba/transmittable-thread-local/runs/7826806473?check_suite_focus=true if (SystemUtils.isJavaVersionAtMost(JavaVersion.JAVA_1_8)) { return TestCaseConfig(enabled = true) } return TestCaseConfig(enabled = noTtlAgentRun()) } @Test fun test_registerTransmittee_crr() { // ======================================== // 0. mocks creation and stubbing // ======================================== val transmittee = mockk<Transmitter.Transmittee<List<String>, Set<Int>>>() @Suppress("UnusedEquals", "ReplaceCallWithBinaryOperator") excludeRecords { transmittee.equals(any()) transmittee.hashCode() } every { transmittee.capture() } returns listOf("42", "43") every { transmittee.replay(listOf("42", "43")) } returns setOf(42, 43) every { transmittee.restore(setOf(42, 43)) } just Runs try { // ======================================== // 1. mock record(aka. invocation) // ======================================== Transmitter.registerTransmittee(transmittee).shouldBeTrue() val captured = Transmitter.capture() val backup = Transmitter.replay(captured) Transmitter.restore(backup) // ======================================== // 2. mock verification // ======================================== verifySequence { transmittee.capture() transmittee.replay(any()) transmittee.restore(any()) } confirmVerified(transmittee) } finally { Transmitter.unregisterTransmittee(transmittee).shouldBeTrue() } } @Test fun test_registerTransmittee_clear_restore() { // ======================================== // 0. mocks creation and stubbing // ======================================== val transmittee = mockk<Transmitter.Transmittee<List<String>, Set<Int>>>() @Suppress("UnusedEquals", "ReplaceCallWithBinaryOperator") excludeRecords { transmittee.equals(any()) transmittee.hashCode() } every { transmittee.clear() } returns setOf(42, 43) every { transmittee.restore(setOf(42, 43)) } just Runs try { // ======================================== // 1. mock record(aka. invocation) // ======================================== Transmitter.registerTransmittee(transmittee).shouldBeTrue() val backup = Transmitter.clear() Transmitter.restore(backup) // ======================================== // 2. mock verification // ======================================== verifySequence { transmittee.clear() transmittee.restore(any()) } confirmVerified(transmittee) } finally { Transmitter.unregisterTransmittee(transmittee).shouldBeTrue() } } }
apache-2.0
73cf85db16eb6ac82d3c340439020343
36.796296
105
0.531602
5.576503
false
true
false
false
google/intellij-community
platform/lang-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/project/ProjectRootManagerBridge.kt
1
3489
// 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.ide.impl.legacyBridge.project import com.intellij.openapi.project.Project import com.intellij.openapi.project.RootsChangeRescanningInfo import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.impl.OrderRootsCache import com.intellij.openapi.roots.impl.ProjectRootManagerComponent import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar import com.intellij.openapi.util.EmptyRunnable import com.intellij.util.indexing.BuildableRootsChangeRescanningInfo import com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots.OrderRootsCacheBridge import com.intellij.workspaceModel.ide.legacyBridge.ModuleDependencyIndex import com.intellij.workspaceModel.ide.legacyBridge.ModuleDependencyListener class ProjectRootManagerBridge(project: Project) : ProjectRootManagerComponent(project) { init { if (!project.isDefault) { moduleDependencyIndex.addListener(ModuleDependencyListenerImpl()) } } private val moduleDependencyIndex get() = ModuleDependencyIndex.getInstance(project) override fun getActionToRunWhenProjectJdkChanges(): Runnable { return Runnable { super.getActionToRunWhenProjectJdkChanges().run() if (moduleDependencyIndex.hasProjectSdkDependency()) fireRootsChanged(BuildableRootsChangeRescanningInfo.newInstance().addInheritedSdk()) } } override fun getOrderRootsCache(project: Project): OrderRootsCache { return OrderRootsCacheBridge(project, project) } fun isFiringEvent(): Boolean = isFiringEvent fun setupTrackedLibrariesAndJdks() { moduleDependencyIndex.setupTrackedLibrariesAndJdks() } private fun fireRootsChanged(info: RootsChangeRescanningInfo) { if (myProject.isOpen) { makeRootsChange(EmptyRunnable.INSTANCE, info) } } inner class ModuleDependencyListenerImpl : ModuleDependencyListener { private var insideRootsChange = false override fun referencedLibraryAdded(library: Library) { if (shouldListen(library)) { fireRootsChanged(BuildableRootsChangeRescanningInfo.newInstance().addLibrary(library)) } } override fun referencedLibraryChanged(library: Library) { if (insideRootsChange || !shouldListen(library)) return insideRootsChange = true try { fireRootsChanged(BuildableRootsChangeRescanningInfo.newInstance().addLibrary(library)) } finally { insideRootsChange = false } } override fun referencedLibraryRemoved(library: Library) { if (shouldListen(library)) { fireRootsChanged(RootsChangeRescanningInfo.NO_RESCAN_NEEDED) } } private fun shouldListen(library: Library): Boolean { //project-level libraries are stored in WorkspaceModel, and changes in their roots are handled by RootsChangeWatcher return library.table?.tableLevel != LibraryTablesRegistrar.PROJECT_LEVEL } override fun referencedSdkAdded(sdk: Sdk) { fireRootsChanged(BuildableRootsChangeRescanningInfo.newInstance().addSdk(sdk)) } override fun referencedSdkChanged(sdk: Sdk) { fireRootsChanged(BuildableRootsChangeRescanningInfo.newInstance().addSdk(sdk)) } override fun referencedSdkRemoved(sdk: Sdk) { fireRootsChanged(RootsChangeRescanningInfo.NO_RESCAN_NEEDED) } } }
apache-2.0
26132ddeae5dbfbc5e4ecf64daa24432
36.526882
143
0.776154
5.215247
false
false
false
false
MarcinMoskala/ActivityStarter
activitystarter-compiler/src/main/java/activitystarter/compiler/processing/ArgumentFactory.kt
1
6364
package activitystarter.compiler.processing import activitystarter.Arg import activitystarter.compiler.error.Errors import activitystarter.compiler.error.error import activitystarter.compiler.model.ConverterModel import activitystarter.compiler.model.ProjectConfig import activitystarter.compiler.model.classbinding.KnownClassType import activitystarter.compiler.model.param.ArgumentModel import activitystarter.compiler.model.param.FieldAccessor import activitystarter.compiler.model.param.ParamType import activitystarter.compiler.utils.getElementType import com.squareup.javapoet.TypeName import javax.lang.model.element.Element import javax.lang.model.element.ElementKind import javax.lang.model.element.Modifier import javax.lang.model.element.TypeElement import javax.lang.model.type.ExecutableType import javax.lang.model.type.TypeMirror class ArgumentFactory(val enclosingElement: TypeElement, val config: ProjectConfig) { fun create(element: Element, packageName: String, knownClassType: KnownClassType): ArgumentModel? = when (element.kind) { ElementKind.FIELD -> createFromField(element, packageName, knownClassType) ElementKind.METHOD -> createFromGetter(element, packageName, knownClassType) else -> null } private fun createFromField(element: Element, packageName: String, knownClassType: KnownClassType): ArgumentModel? { val elementType: TypeMirror = getElementType(element) val paramType = ParamType.fromType(elementType) val accessor: FieldAccessor = FieldAccessor.fromElement(element) val error = getFieldError(knownClassType, paramType, accessor) if (error != null) { showProcessingError(element, error) return null } val name: String = element.simpleName.toString() val annotation = element.getAnnotation(Arg::class.java) val keyFromAnnotation = annotation?.key val isParceler = annotation?.parceler ?: false val optional: Boolean = annotation?.optional ?: false val key: String = if (keyFromAnnotation.isNullOrBlank()) "$packageName.${name}StarterKey" else keyFromAnnotation!! val typeName: TypeName = TypeName.get(elementType) val (converter, saveParamType) = getConverterAndSaveType(isParceler, elementType, paramType, element) ?: return null return ArgumentModel(name, key, paramType, typeName, saveParamType, optional, accessor, converter, isParceler) } fun createFromGetter(getterElement: Element, packageName: String?, knownClassType: KnownClassType): ArgumentModel? { if (!getterElement.simpleName.startsWith("get")) { showProcessingError(getterElement, "Function is not getter") return null } val name = getterElement.simpleName.toString().substringAfter("get").decapitalize() val getter = getterElement.asType() as? ExecutableType if (getter == null) { showProcessingError(getterElement, "Type is not method") return null } val returnType: TypeMirror = getter.returnType val paramType = ParamType.fromType(returnType) val accessor: FieldAccessor = FieldAccessor.fromGetter(getterElement, name) val error = getGetterError(knownClassType, paramType, accessor) if (error != null) { showProcessingError(getterElement, error) return null } val annotation = getterElement.getAnnotation(Arg::class.java) val keyFromAnnotation = annotation?.key val parceler = annotation?.parceler ?: false val optional: Boolean = annotation?.optional ?: false val key: String = if (keyFromAnnotation.isNullOrBlank()) "$packageName.${name}StarterKey" else keyFromAnnotation!! val typeName: TypeName = TypeName.get(returnType) val (converter, saveParamType) = getConverterAndSaveType(parceler, returnType, paramType, getterElement) ?: return null return ArgumentModel(name, key, paramType, typeName, saveParamType, optional, accessor, converter, parceler) } private fun getConverterAndSaveType(isParceler: Boolean, elementType: TypeMirror, paramType: ParamType, element: Element): Pair<ConverterModel?, ParamType>? { if (isParceler) { return null to ParamType.ParcelableSubtype } else { val converter = config.converterFor(elementType) val saveParamType = converter?.toParamType ?: paramType if (saveParamType == ParamType.ObjectSubtype) { showProcessingError(element, Errors.notSupportedType.replace("{Type}", paramType.name).replace("{Field}", element.simpleName?.toString() ?: "")) return null } return converter to saveParamType } } private fun getFieldError(knownClassType: KnownClassType, paramTypeNullable: ParamType?, accessor: FieldAccessor) = when { enclosingElement.kind != ElementKind.CLASS -> Errors.notAClass enclosingElement.modifiers.contains(Modifier.PRIVATE) -> Errors.privateClass paramTypeNullable == null -> Errors.notSupportedType.replace("{Type}", paramTypeNullable?.name ?: "null").replace("{Field}", accessor.fieldName) !accessor.isAccessible() -> Errors.inaccessibleField paramTypeNullable.typeUsedBySupertype() && knownClassType == KnownClassType.BroadcastReceiver -> Errors.notBasicTypeInReceiver else -> null } private fun getGetterError(knownClassType: KnownClassType, paramTypeNullable: ParamType?, accessor: FieldAccessor) = when { enclosingElement.kind != ElementKind.CLASS -> Errors.notAClass enclosingElement.modifiers.contains(Modifier.PRIVATE) -> Errors.privateClass paramTypeNullable == null -> Errors.notSupportedType.replace("{Type}", paramTypeNullable?.name ?: "null").replace("{Field}", accessor.fieldName) paramTypeNullable.typeUsedBySupertype() && knownClassType == KnownClassType.BroadcastReceiver -> Errors.notBasicTypeInReceiver else -> null } private fun showProcessingError(element: Element, text: String) { error(enclosingElement, "@%s %s $text (%s)", Arg::class.java.simpleName, enclosingElement.qualifiedName, element.simpleName) } class ProcessingError(override val message: String) : Throwable(message) }
apache-2.0
2e8387b39a6f00169ad9af88134d5019
51.603306
162
0.723602
5.276949
false
false
false
false
kickstarter/android-oss
app/src/test/java/com/kickstarter/libs/PerimeterXTest.kt
1
5248
package com.kickstarter.libs import androidx.test.core.app.ApplicationProvider import com.kickstarter.KSRobolectricTestCase import com.kickstarter.mock.factories.PXClientFactory import okhttp3.Protocol import okhttp3.Request import okhttp3.Response import okhttp3.ResponseBody.Companion.toResponseBody import org.junit.Test import rx.observers.TestSubscriber import java.util.HashMap class PerimeterXTest : KSRobolectricTestCase() { lateinit var build: Build private val mockRequest = Request.Builder() .url("http://url.com") .build() private val mockResponse = Response.Builder() .request(mockRequest) .protocol(Protocol.HTTP_2) .message("") .code(403) .body("body".toResponseBody()) .build() private val mockBody = mockResponse.body?.string() ?: "" override fun setUp() { super.setUp() build = requireNotNull(environment().build()) } @Test fun testCookieForWebView() { val pxClient = PXClientFactory.pxChallengedSuccessful(build) val cookie = pxClient.getCookieForWebView() val assertValue = "_pxmvid=${pxClient.visitorId()}" assert(cookie.contains(assertValue)) } @Test fun testVisitiorId() { val pxClient = PXClientFactory.pxChallengedSuccessful(build) val vid = pxClient.visitorId() assertNotNull(vid) assertEquals(vid, "VID") } @Test fun testHeaders() { val pxClient = PXClientFactory.pxChallengedSuccessful(build) val pxHeader = pxClient.httpHeaders() val headerVariable = mutableMapOf("h1" to "value1", "h2" to "value2") assert(pxHeader.isNotEmpty()) assertEquals(pxHeader.size, 2) assertEquals(pxHeader.keys, headerVariable.keys) assertEquals(pxHeader.values.toString(), headerVariable.values.toString()) } @Test fun testAddHeaderToBuilder() { val pxClient = PXClientFactory.pxChallengedSuccessful(build) val mockRequestBuilder = Request.Builder() .url("http://url.com") val headerVariable = mutableMapOf("h1" to "value1", "h2" to "value2") pxClient.addHeaderTo(mockRequestBuilder) val request = mockRequestBuilder.build() val first = request.headers[headerVariable.keys.first()] val last = request.headers[headerVariable.keys.last()] assertEquals(first, headerVariable[headerVariable.keys.first()]) assertEquals(last, headerVariable[headerVariable.keys.last()]) } @Test fun testChallengedResponse() { val build = requireNotNull(environment().build()) val clientNotChallenged = PXClientFactory.pxNotChallenged(build) val clientWithChallenged = PXClientFactory.pxChallengedSuccessful(build) val challenge1 = clientWithChallenged.isChallenged(mockBody) val challenge2 = clientNotChallenged.isChallenged(mockBody) assertTrue(challenge1) assertFalse(challenge2) } @Test fun testIntercept_whenCaptchaSuccess() { val pxClient = PXClientFactory.pxChallengedSuccessful(build) val testIsManagerReady = TestSubscriber.create<Boolean>() val testCaptchaSuccess = TestSubscriber.create<Boolean>() val testCaptchaCanceled = TestSubscriber.create<String>() val testHeadersAdded = TestSubscriber.create<HashMap<String, String>>() pxClient.isReady.subscribe(testIsManagerReady) pxClient.isCaptchaSuccess.subscribe(testCaptchaSuccess) pxClient.headersAdded.subscribe(testHeadersAdded) pxClient.isCaptchaCanceled.subscribe(testCaptchaCanceled) pxClient.start(ApplicationProvider.getApplicationContext()) pxClient.intercept(mockResponse) testIsManagerReady.assertValue(true) testCaptchaSuccess.assertValue(true) testCaptchaCanceled.assertNoValues() testHeadersAdded.assertValueCount(1) } @Test fun testIntercept_whenCaptchaCanceled() { val build = requireNotNull(environment().build()) val client = PXClientFactory.pxChallengedCanceled(build) val testCaptchaSuccess = TestSubscriber.create<Boolean>() val testCaptchaCanceled = TestSubscriber.create<String>() client.isCaptchaSuccess.subscribe(testCaptchaSuccess) client.isCaptchaCanceled.subscribe(testCaptchaCanceled) client.start(ApplicationProvider.getApplicationContext()) client.intercept(mockResponse) testCaptchaCanceled.assertValue("Back Button") testCaptchaSuccess.assertNoValues() } @Test fun testIntercept_whenNoChallenged_NoCaptcha() { val client = PXClientFactory.pxNotChallenged(build) val testCaptchaSuccess = TestSubscriber.create<Boolean>() val testCaptchaCanceled = TestSubscriber.create<String>() client.isCaptchaSuccess.subscribe(testCaptchaSuccess) client.isCaptchaCanceled.subscribe(testCaptchaCanceled) client.start(ApplicationProvider.getApplicationContext()) client.intercept(mockResponse) assertFalse(client.isChallenged(mockBody)) testCaptchaCanceled.assertNoValues() testCaptchaSuccess.assertNoValues() } }
apache-2.0
e27328cd23b9b88d81195c51b889572d
33.077922
82
0.705221
5.13001
false
true
false
false
Flank/flank
test_runner/src/main/kotlin/ftl/client/google/IosCatalog.kt
1
2608
package ftl.client.google import com.google.testing.model.IosDeviceCatalog import com.google.testing.model.IosModel import com.google.testing.model.Orientation import ftl.config.Device import ftl.environment.getLocaleDescription import ftl.environment.ios.getDescription import ftl.environment.ios.iosVersionsToCliTable import ftl.http.executeWithRetry /** * Validates iOS device model and version * * note: 500 Internal Server Error is returned on invalid model id/version **/ object IosCatalog { private val catalogMap: MutableMap<String, IosDeviceCatalog> = mutableMapOf() private val xcodeMap: MutableMap<String, List<String>> = mutableMapOf() fun getModels(projectId: String): List<IosModel> = iosDeviceCatalog(projectId).models.orEmpty() fun softwareVersionsAsTable(projectId: String) = getVersionsList(projectId).iosVersionsToCliTable() fun describeSoftwareVersion(projectId: String, versionId: String) = getVersionsList(projectId).getDescription(versionId) private fun getVersionsList(projectId: String) = iosDeviceCatalog(projectId).versions private fun getLocaleDescription(projectId: String, locale: String) = getLocales(projectId).getLocaleDescription(locale) internal fun getLocales(projectId: String) = iosDeviceCatalog(projectId).runtimeConfiguration.locales fun supportedOrientations(projectId: String): List<Orientation> = iosDeviceCatalog(projectId).runtimeConfiguration.orientations fun supportedXcode(version: String, projectId: String) = xcodeVersions(projectId).contains(version) private fun xcodeVersions(projectId: String) = xcodeMap.getOrPut(projectId) { iosDeviceCatalog(projectId).xcodeVersions.map { it.version } } fun Device.getSupportedVersionId(projectId: String): List<String> = iosDeviceCatalog(projectId).models.find { it.id == model }?.supportedVersionIds ?: emptyList() // Device catalogMap is different depending on the project id private fun iosDeviceCatalog( projectId: String ) = try { catalogMap.getOrPut(projectId) { GcTesting.get.testEnvironmentCatalog() .get("ios") .setProjectId(projectId) .executeWithRetry() .iosDeviceCatalog .filterDevicesWithoutSupportedVersions() } } catch (e: java.lang.Exception) { throw java.lang.RuntimeException(e) } private fun IosDeviceCatalog.filterDevicesWithoutSupportedVersions() = setModels(models.filterNotNull().filter { it.supportedVersionIds?.isNotEmpty() ?: false }) }
apache-2.0
29887a85a60d557a4584c8b7b9fae393
40.396825
151
0.742331
4.785321
false
true
false
false
ReplayMod/ReplayMod
src/main/kotlin/com/replaymod/replay/gui/overlay/UIStatusIndicator.kt
1
963
package com.replaymod.replay.gui.overlay import com.replaymod.core.ReplayMod import com.replaymod.core.gui.common.UITexture import gg.essential.elementa.components.UIContainer import gg.essential.elementa.constraints.CenterConstraint import gg.essential.elementa.constraints.SiblingConstraint import gg.essential.elementa.dsl.childOf import gg.essential.elementa.dsl.constrain import gg.essential.elementa.dsl.pixels import gg.essential.elementa.dsl.provideDelegate class UIStatusIndicator(u: Int, v: Int) : UIContainer() { val icon by UITexture(ReplayMod.TEXTURE, UITexture.TextureData.ofSize(16, 16).offset(u, v)).constrain { x = CenterConstraint() y = CenterConstraint() width = 16.pixels height = 16.pixels } childOf this init { constrain { x = SiblingConstraint(4f) y = 0.pixels(alignOpposite = true) width = 20.pixels height = 20.pixels } } }
gpl-3.0
96a6668ae6192532668f8ad4fe437a12
32.241379
107
0.711319
3.995851
false
false
false
false
siosio/intellij-community
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/scratch/compile/KtScratchExecutionSession.kt
1
7637
// 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.scratch.compile import com.intellij.execution.configurations.JavaCommandLineState import com.intellij.execution.process.CapturingProcessHandler import com.intellij.execution.target.TargetEnvironmentRequest import com.intellij.execution.target.TargetProgressIndicatorAdapter import com.intellij.execution.target.TargetedCommandLine import com.intellij.execution.target.local.LocalTargetEnvironmentRequest import com.intellij.openapi.diagnostic.ControlFlowException import com.intellij.openapi.module.Module import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.util.Computable import com.intellij.openapi.util.io.FileUtil import org.jetbrains.kotlin.idea.KotlinJvmBundle import org.jetbrains.kotlin.idea.core.KotlinCompilerIde import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager import org.jetbrains.kotlin.idea.scratch.LOG import org.jetbrains.kotlin.idea.scratch.ScratchExpression import org.jetbrains.kotlin.idea.scratch.ScratchFile import org.jetbrains.kotlin.idea.scratch.compile.KtScratchSourceFileProcessor.Result import org.jetbrains.kotlin.idea.scratch.printDebugMessage import org.jetbrains.kotlin.idea.util.JavaParametersBuilder import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPsiFactory import java.io.File class KtScratchExecutionSession( private val file: ScratchFile, private val executor: KtCompilingExecutor ) { companion object { private const val TIMEOUT_MS = 30000 } @Volatile private var backgroundProcessIndicator: ProgressIndicator? = null fun execute(callback: () -> Unit) { val psiFile = file.ktScratchFile ?: return executor.errorOccurs( KotlinJvmBundle.message("couldn.t.find.ktfile.for.current.editor"), isFatal = true ) val expressions = file.getExpressions() if (!executor.checkForErrors(psiFile, expressions)) return when (val result = runReadAction { KtScratchSourceFileProcessor().process(expressions) }) { is Result.Error -> return executor.errorOccurs(result.message, isFatal = true) is Result.OK -> { LOG.printDebugMessage("After processing by KtScratchSourceFileProcessor:\n ${result.code}") executeInBackground(KotlinJvmBundle.message("running.kotlin.scratch")) { indicator -> backgroundProcessIndicator = indicator val modifiedScratchSourceFile = createFileWithLightClassSupport(result, psiFile) tryRunCommandLine(modifiedScratchSourceFile, psiFile, result, callback) } } } } private fun executeInBackground(title: String, block: (indicator: ProgressIndicator) -> Unit) { object : Task.Backgroundable(file.project, title, true) { override fun run(indicator: ProgressIndicator) = block.invoke(indicator) }.queue() } private fun createFileWithLightClassSupport(result: Result.OK, psiFile: KtFile): KtFile = runReadAction { KtPsiFactory(file.project).createFileWithLightClassSupport("tmp.kt", result.code, psiFile) } private fun tryRunCommandLine(modifiedScratchSourceFile: KtFile, psiFile: KtFile, result: Result.OK, callback: () -> Unit) { assert(backgroundProcessIndicator != null) try { runCommandLine( file.project, modifiedScratchSourceFile, file.getExpressions(), psiFile, result, backgroundProcessIndicator!!, callback ) } catch (e: Throwable) { if (e is ControlFlowException) throw e reportError(result, e, psiFile) } } fun reportError(result: Result.OK, e: Throwable, psiFile: KtFile) { LOG.printDebugMessage(result.code) executor.errorOccurs(e.message ?: KotlinJvmBundle.message("couldn.t.compile.0", psiFile.name), e, isFatal = true) } private fun runCommandLine( project: Project, modifiedScratchSourceFile: KtFile, expressions: List<ScratchExpression>, psiFile: KtFile, result: Result.OK, indicator: ProgressIndicator, callback: () -> Unit ) { val tempDir = DumbService.getInstance(project).runReadActionInSmartMode(Computable { compileFileToTempDir(modifiedScratchSourceFile, expressions) }) ?: return try { val (environmentRequest, commandLine) = createCommandLine(psiFile, file.module, result.mainClassName, tempDir.path) val environment = environmentRequest.prepareEnvironment(TargetProgressIndicatorAdapter(indicator)) val commandLinePresentation = commandLine.getCommandPresentation(environment) LOG.printDebugMessage(commandLinePresentation) val processHandler = CapturingProcessHandler(environment.createProcess(commandLine, indicator), null, commandLinePresentation) val executionResult = processHandler.runProcessWithProgressIndicator(indicator, TIMEOUT_MS) when { executionResult.isTimeout -> { executor.errorOccurs( KotlinJvmBundle.message( "couldn.t.get.scratch.execution.result.stopped.by.timeout.0.ms", TIMEOUT_MS ) ) } executionResult.isCancelled -> { // ignore } else -> { executor.parseOutput(executionResult, expressions) } } } finally { tempDir.delete() callback() } } fun stop() { backgroundProcessIndicator?.cancel() } private fun compileFileToTempDir(psiFile: KtFile, expressions: List<ScratchExpression>): File? { if (!executor.checkForErrors(psiFile, expressions)) return null val tmpDir = FileUtil.createTempDirectory("compile", "scratch") LOG.printDebugMessage("Temp output dir: ${tmpDir.path}") KotlinCompilerIde(psiFile).compileToDirectory(tmpDir) return tmpDir } private fun createCommandLine(originalFile: KtFile, module: Module?, mainClassName: String, tempOutDir: String): Pair<TargetEnvironmentRequest, TargetedCommandLine> { val javaParameters = JavaParametersBuilder(originalFile.project) .withSdkFrom(module, true) .withMainClassName(mainClassName) .build() javaParameters.classPath.add(tempOutDir) if (module != null) { javaParameters.classPath.addAll(JavaParametersBuilder.getModuleDependencies(module)) } ScriptConfigurationManager.getInstance(originalFile.project) .getConfiguration(originalFile)?.let { javaParameters.classPath.addAll(it.dependenciesClassPath.map { f -> f.absolutePath }) } val wslConfiguration = JavaCommandLineState.checkCreateWslConfiguration(javaParameters.jdk) val request = wslConfiguration?.createEnvironmentRequest(originalFile.project) ?: LocalTargetEnvironmentRequest() return request to javaParameters.toCommandLine(request).build() } }
apache-2.0
b163da447dddb4041988ecb5a8aec27d
43.150289
170
0.694775
5.40864
false
false
false
false
siosio/intellij-community
plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/proxy/mirror/coroutinesDebugMirror.kt
1
9961
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.coroutine.proxy.mirror import com.sun.jdi.* import org.jetbrains.kotlin.idea.debugger.coroutine.util.isSubTypeOrSame import org.jetbrains.kotlin.idea.debugger.coroutine.util.logger import org.jetbrains.kotlin.idea.debugger.evaluate.DefaultExecutionContext class DebugProbesImpl private constructor(context: DefaultExecutionContext) : BaseMirror<ObjectReference, MirrorOfDebugProbesImpl>("kotlinx.coroutines.debug.internal.DebugProbesImpl", context) { private val instanceField by FieldDelegate<ObjectReference>("INSTANCE") private val instance = instanceField.staticValue() private val javaLangListMirror = JavaUtilAbstractCollection(context) private val stackTraceElement = StackTraceElement(context) private val coroutineInfo = CoroutineInfo.instance(this, context) ?: throw IllegalStateException("CoroutineInfo implementation not found.") private val debugProbesCoroutineOwner = DebugProbesImplCoroutineOwner(coroutineInfo, context) private val isInstalledInCoreMethod by MethodDelegate<BooleanValue>("isInstalled\$kotlinx_coroutines_debug", "()Z") private val isInstalledInDebugMethod by MethodDelegate<BooleanValue>("isInstalled\$kotlinx_coroutines_core", "()Z") private val enhanceStackTraceWithThreadDumpMethod by MethodMirrorDelegate("enhanceStackTraceWithThreadDump", javaLangListMirror) private val dumpMethod by MethodMirrorDelegate("dumpCoroutinesInfo", javaLangListMirror, "()Ljava/util/List;") val isInstalled: Boolean by lazy { isInstalled(context) } override fun fetchMirror(value: ObjectReference, context: DefaultExecutionContext) = MirrorOfDebugProbesImpl(value, instance, isInstalled) fun isInstalled(context: DefaultExecutionContext): Boolean = isInstalledInDebugMethod.value(instance, context)?.booleanValue() ?: isInstalledInCoreMethod.value(instance, context)?.booleanValue() ?: throw IllegalStateException("isInstalledMethod not found") fun enhanceStackTraceWithThreadDump( context: DefaultExecutionContext, coroutineInfo: ObjectReference, lastObservedStackTrace: ObjectReference ): List<MirrorOfStackTraceElement>? { instance ?: return emptyList() val list = enhanceStackTraceWithThreadDumpMethod.mirror(instance, context, coroutineInfo, lastObservedStackTrace) ?: return emptyList() return list.values.mapNotNull { stackTraceElement.mirror(it, context) } } fun dumpCoroutinesInfo(context: DefaultExecutionContext): List<MirrorOfCoroutineInfo> { instance ?: return emptyList() val referenceList = dumpMethod.mirror(instance, context) ?: return emptyList() return referenceList.values.mapNotNull { coroutineInfo.mirror(it, context) } } fun getCoroutineInfo(value: ObjectReference?, context: DefaultExecutionContext): MirrorOfCoroutineInfo? { val coroutineOwner = debugProbesCoroutineOwner.mirror(value, context) return coroutineOwner?.coroutineInfo } companion object { val log by logger fun instance(context: DefaultExecutionContext) = try { DebugProbesImpl(context) } catch (e: IllegalStateException) { log.debug("Attempt to access DebugProbesImpl but none found.", e) null } } } class DebugProbesImplCoroutineOwner(private val coroutineInfo: CoroutineInfo, context: DefaultExecutionContext) : BaseMirror<ObjectReference, MirrorOfCoroutineOwner>(COROUTINE_OWNER_CLASS_NAME, context) { private val infoField by FieldMirrorDelegate("info", DebugCoroutineInfoImpl(context)) override fun fetchMirror(value: ObjectReference, context: DefaultExecutionContext): MirrorOfCoroutineOwner? { val info = infoField.value(value) ?: return null if (infoField.isCompatible(info)) return MirrorOfCoroutineOwner(value, infoField.mirrorOnly(info, context)) else return MirrorOfCoroutineOwner(value, coroutineInfo.mirror(info, context)) } companion object { const val COROUTINE_OWNER_CLASS_NAME = "kotlinx.coroutines.debug.internal.DebugProbesImpl\$CoroutineOwner" fun instanceOf(value: ObjectReference?) = value?.referenceType()?.isSubTypeOrSame(COROUTINE_OWNER_CLASS_NAME) ?: false } } class DebugCoroutineInfoImpl constructor(context: DefaultExecutionContext) : BaseMirror<ObjectReference, MirrorOfCoroutineInfo>("kotlinx.coroutines.debug.internal.DebugCoroutineInfoImpl", context) { private val stackTraceElement = StackTraceElement(context) val lastObservedThread by FieldDelegate<ThreadReference>("lastObservedThread") val state by FieldMirrorDelegate<ObjectReference, String>("_state", JavaLangObjectToString(context)) val lastObservedFrame by FieldMirrorDelegate("_lastObservedFrame", WeakReference(context)) val creationStackBottom by FieldMirrorDelegate("creationStackBottom", CoroutineStackFrame(context)) val sequenceNumber by FieldDelegate<LongValue>("sequenceNumber") val _context by MethodMirrorDelegate("getContext", CoroutineContext(context)) val getCreationStackTrace by MethodMirrorDelegate("getCreationStackTrace", JavaUtilAbstractCollection(context)) override fun fetchMirror(value: ObjectReference, context: DefaultExecutionContext): MirrorOfCoroutineInfo? { val state = state.mirror(value, context) val coroutineContext = _context.mirror(value, context) val creationStackBottom = creationStackBottom.mirror(value, context) val creationStackTraceMirror = getCreationStackTrace.mirror(value, context) val creationStackTrace = creationStackTraceMirror?.values?.mapNotNull { stackTraceElement.mirror(it, context) } val lastObservedFrame = lastObservedFrame.mirror(value, context) return MirrorOfCoroutineInfo( value, coroutineContext, creationStackBottom, sequenceNumber.value(value)?.longValue(), null, creationStackTrace, state, lastObservedThread.value(value), lastObservedFrame?.reference ) } } class CoroutineInfo private constructor( private val debugProbesImplMirror: DebugProbesImpl, context: DefaultExecutionContext, val className: String = AGENT_134_CLASS_NAME ) : BaseMirror<ObjectReference, MirrorOfCoroutineInfo>(className, context) { //private val javaLangListMirror = //private val coroutineContextMirror = private val stackTraceElement = StackTraceElement(context) private val contextFieldRef by FieldMirrorDelegate("context", CoroutineContext(context)) private val creationStackBottom by FieldMirrorDelegate("creationStackBottom", CoroutineStackFrame(context)) private val sequenceNumberField by FieldDelegate<LongValue>("sequenceNumber") private val creationStackTraceMethod by MethodMirrorDelegate("getCreationStackTrace", JavaUtilAbstractCollection(context)) private val stateMethod by MethodMirrorDelegate<ObjectReference, String>("getState", JavaLangObjectToString(context)) private val lastObservedStackTraceMethod by MethodDelegate<ObjectReference>("lastObservedStackTrace") private val lastObservedFrameField by FieldDelegate<ObjectReference>("lastObservedFrame") private val lastObservedThreadField by FieldDelegate<ThreadReference>("lastObservedThread") companion object { val log by logger private const val AGENT_134_CLASS_NAME = "kotlinx.coroutines.debug.CoroutineInfo" private const val AGENT_135_AND_UP_CLASS_NAME = "kotlinx.coroutines.debug.internal.DebugCoroutineInfo" fun instance(debugProbesImplMirror: DebugProbesImpl, context: DefaultExecutionContext): CoroutineInfo? { val classType = context.findClassSafe(AGENT_135_AND_UP_CLASS_NAME) ?: context.findClassSafe(AGENT_134_CLASS_NAME) ?: return null return try { CoroutineInfo(debugProbesImplMirror, context, classType.name()) } catch (e: IllegalStateException) { log.warn("coroutine-debugger: $classType not found", e) null } } } override fun fetchMirror(value: ObjectReference, context: DefaultExecutionContext): MirrorOfCoroutineInfo { val state = stateMethod.mirror(value, context) val coroutineContext = contextFieldRef.mirror(value, context) val creationStackBottom = creationStackBottom.mirror(value, context) val sequenceNumber = sequenceNumberField.value(value)?.longValue() val creationStackTraceMirror = creationStackTraceMethod.mirror(value, context) val creationStackTrace = creationStackTraceMirror?.values?.mapNotNull { stackTraceElement.mirror(it, context) } val lastObservedStackTrace = lastObservedStackTraceMethod.value(value, context) val enhancedList = if (lastObservedStackTrace != null) debugProbesImplMirror.enhanceStackTraceWithThreadDump(context, value, lastObservedStackTrace) else emptyList() val lastObservedThread = lastObservedThreadField.value(value) val lastObservedFrame = lastObservedFrameField.value(value) return MirrorOfCoroutineInfo( value, coroutineContext, creationStackBottom, sequenceNumber, enhancedList, creationStackTrace, state, lastObservedThread, lastObservedFrame ) } }
apache-2.0
582cb20d66c0c2b285f9912bdd1dfc9a
51.151832
158
0.72824
5.975405
false
false
false
false
jwren/intellij-community
plugins/IntelliLang/IntelliLang-tests/test/org/intellij/plugins/intelliLang/JavaLanguageInjectionSupportTest.kt
2
7795
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.intelliLang import com.intellij.lang.Language import com.intellij.openapi.command.undo.UndoManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider import com.intellij.openapi.ui.TestDialog import com.intellij.openapi.ui.TestDialogManager import com.intellij.psi.PsiMethodCallExpression import com.intellij.psi.injection.Injectable import com.intellij.psi.util.parentOfType import com.intellij.util.ui.UIUtil import junit.framework.TestCase import org.intellij.plugins.intelliLang.inject.InjectLanguageAction import org.intellij.plugins.intelliLang.inject.InjectorUtils import org.intellij.plugins.intelliLang.inject.UnInjectLanguageAction import org.intellij.plugins.intelliLang.inject.config.BaseInjection import org.intellij.plugins.intelliLang.inject.config.InjectionPlace import org.intellij.plugins.intelliLang.inject.java.JavaLanguageInjectionSupport class JavaLanguageInjectionSupportTest : AbstractLanguageInjectionTestCase() { fun testAnnotationInjection() { myFixture.configureByText("Foo.java", """ class Foo { void bar() { baz("{\"a\": <caret> 1 }"); } void baz(String json){} } """) StoringFixPresenter().apply { InjectLanguageAction.invokeImpl(project, myFixture.editor, myFixture.file, Injectable.fromLanguage(Language.findLanguageByID("JSON")), this ) }.process() assertInjectedLangAtCaret("JSON") myFixture.checkResult(""" |import org.intellij.lang.annotations.Language; | |class Foo { | void bar() { | baz("{\"a\": 1 }"); | } | | void baz(@Language("JSON") String json){} | } | """.trimMargin()) assertNotNull(myFixture.getAvailableIntention("Uninject language or reference")) UnInjectLanguageAction.invokeImpl(project, topLevelEditor, topLevelFile) assertInjectedLangAtCaret(null) } fun testTemplateLanguageInjection() { myFixture.configureByText("Foo.java", """ class Foo { void bar() { baz("Text with **Mark<caret>down**"); } void baz(String str){} } """) assertNotNull(myFixture.getAvailableIntention("Inject language or reference")) InjectLanguageAction.invokeImpl(project, myFixture.editor, myFixture.file, Injectable.fromLanguage(Language.findLanguageByID("Markdown")) ) assertInjectedLangAtCaret("XML") assertNotNull(myFixture.getAvailableIntention("Uninject language or reference")) UnInjectLanguageAction.invokeImpl(project, topLevelEditor, topLevelFile) assertInjectedLangAtCaret(null) } fun testConfigInjection() { fun currentPrintlnInjection(): BaseInjection? { val psiMethod = topLevelFile.findElementAt(topLevelCaretPosition)!!.parentOfType<PsiMethodCallExpression>()!!.resolveMethod()!! val injection = JavaLanguageInjectionSupport.makeParameterInjection(psiMethod, 0, "JSON"); return InjectorUtils.getEditableInstance(project).findExistingInjection(injection) } myFixture.configureByText("Foo.java", """ class Foo { void bar() { System.out.println("{\"a\": <caret> 1 }"); } } """) TestCase.assertNull(currentPrintlnInjection()) InjectLanguageAction.invokeImpl(project, myFixture.editor, myFixture.file, Injectable.fromLanguage(Language.findLanguageByID("JSON"))) assertInjectedLangAtCaret("JSON") TestCase.assertNotNull(currentPrintlnInjection()) myFixture.configureByText("Another.java", """ class Another { void bar() { System.out.println("{\"a\": <caret> 1 }"); } } """) assertInjectedLangAtCaret("JSON") UnInjectLanguageAction.invokeImpl(project, topLevelEditor, topLevelFile) TestCase.assertNull(currentPrintlnInjection()) assertInjectedLangAtCaret(null) } fun testConfigUnInjectionAndUndo() { Configuration.getInstance().withInjections(listOf(jsonToPrintlnInjection())) { myFixture.configureByText("Foo.java", """ class Foo { void bar() { System.out.println("{\"a\": <caret> 1 }"); } } """) assertInjectedLangAtCaret("JSON") UnInjectLanguageAction.invokeImpl(project, topLevelEditor, topLevelFile) assertInjectedLangAtCaret(null) InjectLanguageAction.invokeImpl(project, topLevelEditor, topLevelFile, Injectable.fromLanguage(Language.findLanguageByID("JSON"))) assertInjectedLangAtCaret("JSON") undo(topLevelEditor) assertInjectedLangAtCaret(null) } } fun testPartialJson() { Configuration.getInstance().withInjections(listOf(jsonToPrintlnInjection())) { myFixture.configureByText("Foo.java", """ class Foo { void bar() { System.out.println( "{'id': '0'," + "'uri': 'http://localhost/'}" .replaceAll("'", "\"")); System.out.println("{ bad_json: 123 }".replaceAll("'", "\"")); } } """) injectionTestFixture.assertInjectedContent("'", "{'id': '0',missingValue") } } fun testRegexJson() { Configuration.getInstance().withInjections(listOf(jsonToPrintlnInjection().apply { setValuePattern("""\((.*?)\)""") isSingleFile = true })) { myFixture.configureByText("Foo.java", """ class Foo { void bar() { System.out.println("({'id':1,) bbb ('boo': 3})"); } } """) injectionTestFixture.assertInjectedContent("{'id':1,'boo': 3}") } } fun testRegexJsonNotSingle() { Configuration.getInstance().withInjections(listOf(jsonToPrintlnInjection().apply { setValuePattern("""\((.*?)\)""") isSingleFile = false })) { myFixture.configureByText("Foo.java", """ class Foo { void bar() { System.out.println("({'id':1}) bbb ({'boo': 3})"); } } """) injectionTestFixture.assertInjectedContent("{'id':1}", "{'boo': 3}") } } private fun jsonToPrintlnInjection(): BaseInjection = BaseInjection("java").apply { injectedLanguageId = "JSON" setInjectionPlaces( InjectionPlace(compiler.createElementPattern( """psiParameter().ofMethod(0, psiMethod().withName("println").withParameters("java.lang.String").definedInClass("java.io.PrintStream"))""", "println JSOM"), true ), InjectionPlace(compiler.createElementPattern( """psiParameter().ofMethod(0, psiMethod().withName("print").withParameters("java.lang.String").definedInClass("java.io.PrintStream"))""", "print JSON"), true ) ) } private fun undo(editor: Editor) { UIUtil.invokeAndWaitIfNeeded(Runnable { val oldTestDialog = TestDialogManager.setTestDialog(TestDialog.OK) try { val undoManager = UndoManager.getInstance(project) val textEditor = TextEditorProvider.getInstance().getTextEditor(editor) undoManager.undo(textEditor) } finally { TestDialogManager.setTestDialog(oldTestDialog) } }) } }
apache-2.0
4bb346bd4e07313e1c01c42951cd86e6
32.170213
148
0.626427
5.249158
false
true
false
false
jwren/intellij-community
plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/KotlinGradleModelBuilder.kt
1
15033
// 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.gradleTooling import org.gradle.api.Project import org.gradle.api.Task import org.gradle.api.artifacts.Dependency import org.gradle.api.artifacts.ProjectDependency import org.gradle.api.provider.Property import org.gradle.tooling.BuildController import org.gradle.tooling.model.Model import org.gradle.tooling.model.build.BuildEnvironment import org.gradle.tooling.model.gradle.GradleBuild import org.gradle.util.GradleVersion import org.jetbrains.kotlin.idea.gradleTooling.arguments.CachedExtractedArgsInfo import org.jetbrains.kotlin.idea.gradleTooling.arguments.CompilerArgumentsCacheMapperImpl import org.jetbrains.kotlin.idea.gradleTooling.arguments.CompilerArgumentsCachingChain import org.jetbrains.kotlin.idea.gradleTooling.arguments.CompilerArgumentsCachingManager.cacheCompilerArgument import org.jetbrains.kotlin.idea.projectModel.CompilerArgumentsCacheAware import org.jetbrains.kotlin.idea.projectModel.KotlinTaskProperties import org.jetbrains.plugins.gradle.model.ProjectImportModelProvider import org.jetbrains.plugins.gradle.tooling.ErrorMessageBuilder import org.jetbrains.plugins.gradle.tooling.ModelBuilderContext import org.jetbrains.plugins.gradle.tooling.ModelBuilderService import java.io.File import java.io.Serializable import java.lang.reflect.InvocationTargetException import java.util.* @Deprecated("Use org.jetbrains.kotlin.idea.projectModel.CachedArgsInfo instead") interface ArgsInfo : Serializable { val currentArguments: List<String> val defaultArguments: List<String> val dependencyClasspath: List<String> } @Suppress("DEPRECATION") @Deprecated("Use org.jetbrains.kotlin.idea.gradleTooling.CachedCompilerArgumentsBySourceSet instead") typealias CompilerArgumentsBySourceSet = Map<String, ArgsInfo> typealias CachedCompilerArgumentsBySourceSet = Map<String, CachedExtractedArgsInfo> typealias AdditionalVisibleSourceSetsBySourceSet = Map</* Source Set Name */ String, /* Visible Source Set Names */ Set<String>> interface KotlinGradleModel : Serializable { val hasKotlinPlugin: Boolean @Suppress("DEPRECATION", "TYPEALIAS_EXPANSION_DEPRECATION") @Deprecated( "Use 'cachedCompilerArgumentsBySourceSet' instead", ReplaceWith("cachedCompilerArgumentsBySourceSet"), DeprecationLevel.ERROR ) val compilerArgumentsBySourceSet: CompilerArgumentsBySourceSet val additionalVisibleSourceSets: AdditionalVisibleSourceSetsBySourceSet val cachedCompilerArgumentsBySourceSet: CachedCompilerArgumentsBySourceSet val coroutines: String? val platformPluginId: String? val implements: List<String> val kotlinTarget: String? val kotlinTaskProperties: KotlinTaskPropertiesBySourceSet val gradleUserHome: String val cacheAware: CompilerArgumentsCacheAware @Deprecated(level = DeprecationLevel.ERROR, message = "Use KotlinGradleModel#cacheAware instead") val partialCacheAware: CompilerArgumentsCacheAware } data class KotlinGradleModelImpl( override val hasKotlinPlugin: Boolean, @Suppress("OverridingDeprecatedMember", "DEPRECATION", "TYPEALIAS_EXPANSION_DEPRECATION") override val compilerArgumentsBySourceSet: CompilerArgumentsBySourceSet, override val cachedCompilerArgumentsBySourceSet: CachedCompilerArgumentsBySourceSet, override val additionalVisibleSourceSets: AdditionalVisibleSourceSetsBySourceSet, override val coroutines: String?, override val platformPluginId: String?, override val implements: List<String>, override val kotlinTarget: String? = null, override val kotlinTaskProperties: KotlinTaskPropertiesBySourceSet, override val gradleUserHome: String, override val cacheAware: CompilerArgumentsCacheAware ) : KotlinGradleModel { @Deprecated( "Use KotlinGradleModel#cacheAware instead", level = DeprecationLevel.ERROR, replaceWith = ReplaceWith("KotlinGradleModel#cacheAware") ) @Suppress("OverridingDeprecatedMember") override val partialCacheAware: CompilerArgumentsCacheAware get() = throw UnsupportedOperationException("Not yet implemented") } abstract class AbstractKotlinGradleModelBuilder : ModelBuilderService { companion object { val kotlinCompileJvmTaskClasses = listOf( "org.jetbrains.kotlin.gradle.tasks.KotlinCompile_Decorated", "org.jetbrains.kotlin.gradle.tasks.KotlinCompileWithWorkers_Decorated" ) val kotlinCompileTaskClasses = kotlinCompileJvmTaskClasses + listOf( "org.jetbrains.kotlin.gradle.tasks.Kotlin2JsCompile_Decorated", "org.jetbrains.kotlin.gradle.tasks.KotlinCompileCommon_Decorated", "org.jetbrains.kotlin.gradle.tasks.Kotlin2JsCompileWithWorkers_Decorated", "org.jetbrains.kotlin.gradle.tasks.KotlinCompileCommonWithWorkers_Decorated" ) val platformPluginIds = listOf("kotlin-platform-jvm", "kotlin-platform-js", "kotlin-platform-common") val pluginToPlatform = linkedMapOf( "kotlin" to "kotlin-platform-jvm", "kotlin2js" to "kotlin-platform-js" ) val kotlinPluginIds = listOf("kotlin", "kotlin2js", "kotlin-android") const val ABSTRACT_KOTLIN_COMPILE_CLASS = "org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile" const val kotlinProjectExtensionClass = "org.jetbrains.kotlin.gradle.dsl.KotlinProjectExtension" const val kotlinSourceSetClass = "org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet" const val kotlinPluginWrapper = "org.jetbrains.kotlin.gradle.plugin.KotlinPluginWrapperKt" private val propertyClassPresent = GradleVersion.current() >= GradleVersion.version("4.3") fun Task.getSourceSetName(): String = try { val method = javaClass.methods.firstOrNull { it.name.startsWith("getSourceSetName") && it.parameterTypes.isEmpty() } val sourceSetName = method?.invoke(this) when { sourceSetName is String -> sourceSetName propertyClassPresent && sourceSetName is Property<*> -> sourceSetName.get() as? String else -> null } } catch (e: InvocationTargetException) { null // can be thrown if property is not initialized yet } ?: "main" } } private const val REQUEST_FOR_NON_ANDROID_MODULES_ONLY = "*" class AndroidAwareGradleModelProvider<TModel>( private val modelClass: Class<TModel>, private val androidPluginIsRequestingVariantSpecificModels: Boolean ) : ProjectImportModelProvider { override fun populateBuildModels( controller: BuildController, buildModel: GradleBuild, consumer: ProjectImportModelProvider.BuildModelConsumer ) = Unit override fun populateProjectModels( controller: BuildController, projectModel: Model, modelConsumer: ProjectImportModelProvider.ProjectModelConsumer ) { val supportsParametrizedModels: Boolean = controller.findModel(BuildEnvironment::class.java)?.gradle?.gradleVersion?.let { // Parametrized build models were introduced in 4.4. Make sure that gradle import does not fail on pre-4.4 GradleVersion.version(it) >= GradleVersion.version("4.4") } ?: false val model = if (androidPluginIsRequestingVariantSpecificModels && supportsParametrizedModels) { controller.findModel(projectModel, modelClass, ModelBuilderService.Parameter::class.java) { it.value = REQUEST_FOR_NON_ANDROID_MODULES_ONLY } } else { controller.findModel(projectModel, modelClass) } if (model != null) { modelConsumer.consume(model, modelClass) } } class Result( private val hasProjectAndroidBasePlugin: Boolean, private val requestedVariantNames: Set<String>? ) { fun shouldSkipBuildAllCall(): Boolean = hasProjectAndroidBasePlugin && requestedVariantNames?.singleOrNull() == REQUEST_FOR_NON_ANDROID_MODULES_ONLY fun shouldSkipSourceSet(sourceSetName: String): Boolean = requestedVariantNames != null && !requestedVariantNames.contains(sourceSetName.lowercase(Locale.getDefault())) } companion object { fun parseParameter(project: Project, parameterValue: String?): Result { return Result( hasProjectAndroidBasePlugin = project.plugins.findPlugin("com.android.base") != null, requestedVariantNames = parameterValue?.splitToSequence(',')?.map { it.lowercase(Locale.getDefault()) }?.toSet() ) } } } class KotlinGradleModelBuilder : AbstractKotlinGradleModelBuilder(), ModelBuilderService.Ex { override fun getErrorMessageBuilder(project: Project, e: Exception): ErrorMessageBuilder { return ErrorMessageBuilder.create(project, e, "Gradle import errors") .withDescription("Unable to build Kotlin project configuration") } override fun canBuild(modelName: String?): Boolean = modelName == KotlinGradleModel::class.java.name private fun getImplementedProjects(project: Project): List<Project> { return listOf("expectedBy", "implement") .flatMap { project.configurations.findByName(it)?.dependencies ?: emptySet<Dependency>() } .filterIsInstance<ProjectDependency>() .mapNotNull { it.dependencyProject } } // see GradleProjectResolverUtil.getModuleId() in IDEA codebase private fun Project.pathOrName() = if (path == ":") name else path private fun Task.getDependencyClasspath(): List<String> { try { val abstractKotlinCompileClass = javaClass.classLoader.loadClass(ABSTRACT_KOTLIN_COMPILE_CLASS) val getCompileClasspath = abstractKotlinCompileClass.getDeclaredMethod("getCompileClasspath").apply { isAccessible = true } @Suppress("UNCHECKED_CAST") return (getCompileClasspath.invoke(this) as Collection<File>).map { it.path } } catch (e: ClassNotFoundException) { // Leave arguments unchanged } catch (e: NoSuchMethodException) { // Leave arguments unchanged } catch (e: InvocationTargetException) { // We can safely ignore this exception here as getCompileClasspath() gets called again at a later time // Leave arguments unchanged } return emptyList() } private fun getCoroutines(project: Project): String? { val kotlinExtension = project.extensions.findByName("kotlin") ?: return null val experimentalExtension = try { kotlinExtension::class.java.getMethod("getExperimental").invoke(kotlinExtension) } catch (e: NoSuchMethodException) { return null } return try { experimentalExtension::class.java.getMethod("getCoroutines").invoke(experimentalExtension)?.toString() } catch (e: NoSuchMethodException) { null } } override fun buildAll(modelName: String, project: Project): KotlinGradleModelImpl? { return buildAll(project, null) } override fun buildAll(modelName: String, project: Project, builderContext: ModelBuilderContext): KotlinGradleModelImpl? { return buildAll(project, builderContext) } private fun buildAll(project: Project, builderContext: ModelBuilderContext?): KotlinGradleModelImpl? { // When running in Android Studio, Android Studio would request specific source sets only to avoid syncing // currently not active build variants. We convert names to the lower case to avoid ambiguity with build variants // accidentally named starting with upper case. val androidVariantRequest = AndroidAwareGradleModelProvider.parseParameter(project, builderContext?.parameter) if (androidVariantRequest.shouldSkipBuildAllCall()) return null val kotlinPluginId = kotlinPluginIds.singleOrNull { project.plugins.findPlugin(it) != null } val platformPluginId = platformPluginIds.singleOrNull { project.plugins.findPlugin(it) != null } val target = project.getTarget() if (kotlinPluginId == null && platformPluginId == null && target == null) { return null } val cachedCompilerArgumentsBySourceSet = LinkedHashMap<String, CachedExtractedArgsInfo>() val additionalVisibleSourceSets = LinkedHashMap<String, Set<String>>() val extraProperties = HashMap<String, KotlinTaskProperties>() val argsMapper = CompilerArgumentsCacheMapperImpl() val kotlinCompileTasks = target?.let { it.compilations ?: emptyList() } ?.mapNotNull { compilation -> compilation.getCompileKotlinTaskName(project) } ?: (project.getAllTasks(false)[project]?.filter { it.javaClass.name in kotlinCompileTaskClasses } ?: emptyList()) kotlinCompileTasks.forEach { compileTask -> if (compileTask.javaClass.name !in kotlinCompileTaskClasses) return@forEach val sourceSetName = compileTask.getSourceSetName() if (androidVariantRequest.shouldSkipSourceSet(sourceSetName)) return@forEach val currentArguments = CompilerArgumentsCachingChain.extractAndCacheTask(compileTask, argsMapper, defaultsOnly = false) val defaultArguments = CompilerArgumentsCachingChain.extractAndCacheTask(compileTask, argsMapper, defaultsOnly = true) val dependencyClasspath = compileTask.getDependencyClasspath().map { cacheCompilerArgument(it, argsMapper) } cachedCompilerArgumentsBySourceSet[sourceSetName] = CachedExtractedArgsInfo(argsMapper.cacheOriginIdentifier, currentArguments, defaultArguments, dependencyClasspath) additionalVisibleSourceSets[sourceSetName] = getAdditionalVisibleSourceSets(project, sourceSetName) extraProperties.acknowledgeTask(compileTask, null) } val platform = platformPluginId ?: pluginToPlatform.entries.singleOrNull { project.plugins.findPlugin(it.key) != null }?.value val implementedProjects = getImplementedProjects(project) return KotlinGradleModelImpl( hasKotlinPlugin = kotlinPluginId != null || platformPluginId != null, compilerArgumentsBySourceSet = emptyMap(), cachedCompilerArgumentsBySourceSet = cachedCompilerArgumentsBySourceSet, additionalVisibleSourceSets = additionalVisibleSourceSets, coroutines = getCoroutines(project), platformPluginId = platform, implements = implementedProjects.map { it.pathOrName() }, kotlinTarget = platform ?: kotlinPluginId, kotlinTaskProperties = extraProperties, gradleUserHome = project.gradle.gradleUserHomeDir.absolutePath, cacheAware = argsMapper ) } }
apache-2.0
0827c75961eaaef5f49755b1ff1efdce
48.943522
158
0.729994
5.705123
false
false
false
false
jwren/intellij-community
platform/execution-impl/src/com/intellij/execution/runToolbar/RunToolbarRunConfigurationsAction.kt
1
7530
// 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.execution.runToolbar import com.intellij.execution.* import com.intellij.execution.actions.RunConfigurationsComboBoxAction import com.intellij.execution.impl.EditConfigurationsDialog import com.intellij.execution.runToolbar.components.ComboBoxArrowComponent import com.intellij.execution.runToolbar.components.MouseListenerHelper import com.intellij.execution.runToolbar.components.TrimmedMiddleLabel import com.intellij.ide.DataManager import com.intellij.ide.HelpTooltip import com.intellij.idea.ActionsBundle import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl.DO_NOT_ADD_CUSTOMIZATION_HANDLER import com.intellij.openapi.actionSystem.impl.segmentedActionBar.SegmentedCustomPanel import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopup import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.wm.IdeFocusManager import com.intellij.ui.Gray import com.intellij.ui.JBColor import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import net.miginfocom.swing.MigLayout import java.awt.Color import java.awt.Dimension import java.awt.Font import java.beans.PropertyChangeEvent import javax.swing.JComponent import javax.swing.SwingUtilities open class RunToolbarRunConfigurationsAction : RunConfigurationsComboBoxAction(), RTRunConfiguration { companion object { fun doRightClick(dataContext: DataContext) { ActionManager.getInstance().getAction("RunToolbarSlotContextMenuGroup")?.let { if(it is ActionGroup) { SwingUtilities.invokeLater { val popup = JBPopupFactory.getInstance().createActionGroupPopup( null, it, dataContext, false, false, false, null, 5, null) popup.showInBestPositionFor(dataContext) } } } } } open fun trace(e: AnActionEvent, add: String? = null) { } override fun getEditRunConfigurationAction(): AnAction? { return ActionManager.getInstance().getAction(RunToolbarEditConfigurationAction.ACTION_ID) } override fun createFinalAction(configuration: RunnerAndConfigurationSettings, project: Project): AnAction { return RunToolbarSelectConfigAction(configuration, project) } override fun getSelectedConfiguration(e: AnActionEvent): RunnerAndConfigurationSettings? { return e.configuration() ?: e.project?.let { val value = RunManager.getInstance(it).selectedConfiguration e.setConfiguration(value) value } } override fun checkMainSlotVisibility(state: RunToolbarMainSlotState): Boolean { return false } override fun update(e: AnActionEvent) { super.update(e) if(!e.presentation.isVisible) return e.presentation.isVisible = !e.isActiveProcess() if (!RunToolbarProcess.isExperimentalUpdatingEnabled) { e.mainState()?.let { e.presentation.isVisible = e.presentation.isVisible && checkMainSlotVisibility(it) } } e.presentation.description = e.runToolbarData()?.let { RunToolbarData.prepareDescription(e.presentation.text, ActionsBundle.message("action.RunToolbarShowHidePopupAction.click.to.open.combo.text")) } } override fun createCustomComponent(presentation: Presentation, place: String): JComponent { return object : SegmentedCustomPanel(presentation) { private val setting = object : TrimmedMiddleLabel() { override fun getFont(): Font { return UIUtil.getToolbarFont() } override fun getForeground(): Color { return UIUtil.getLabelForeground() } } private val arrow = ComboBoxArrowComponent().getView() init { MouseListenerHelper.addListener(this, { doClick() }, { doShiftClick() }, { doRightClick() }) fill() putClientProperty(DO_NOT_ADD_CUSTOMIZATION_HANDLER, true) background = JBColor.namedColor("ComboBoxButton.background", Gray.xDF) } override fun presentationChanged(event: PropertyChangeEvent) { setting.icon = presentation.icon setting.text = presentation.text setting.putClientProperty(DO_NOT_ADD_CUSTOMIZATION_HANDLER, true) isEnabled = presentation.isEnabled setting.isEnabled = isEnabled arrow.isVisible = isEnabled toolTipText = presentation.description setting.toolTipText = presentation.description arrow.toolTipText = presentation.description } private fun fill() { layout = MigLayout("ins 0 0 0 3, novisualpadding, gap 0, fill, hidemode 3", "4[][min!]") add(setting, "ay center, growx, wmin 10") add(arrow) setting.border = JBUI.Borders.empty() } private fun doRightClick() { RunToolbarRunConfigurationsAction.doRightClick(ActionToolbar.getDataContextFor(this)) } private fun doClick() { IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown { showPopup() } } fun showPopup() { val popup: JBPopup = createPopup() {} if (Registry.`is`("ide.helptooltip.enabled")) { HelpTooltip.setMasterPopup(this, popup) } popup.showUnderneathOf(this) } private fun createPopup(onDispose: Runnable): JBPopup { return createActionPopup(ActionToolbar.getDataContextFor(this), this, onDispose) } private fun doShiftClick() { val context = DataManager.getInstance().getDataContext(this) val project = CommonDataKeys.PROJECT.getData(context) if (project != null && !ActionUtil.isDumbMode(project)) { EditConfigurationsDialog(project).show() return } } override fun getPreferredSize(): Dimension { val d = super.getPreferredSize() d.width = FixWidthSegmentedActionToolbarComponent.RUN_CONFIG_WIDTH return d } } } private class RunToolbarSelectConfigAction(val configuration: RunnerAndConfigurationSettings, val project: Project) : DumbAwareAction() { init { var name = Executor.shortenNameIfNeeded(configuration.name) if (name.isEmpty()) { name = " " } val presentation = templatePresentation presentation.setText(name, false) presentation.description = ExecutionBundle.message("select.0.1", configuration.type.configurationTypeDescription, name) updateIcon(presentation) } private fun updateIcon(presentation: Presentation) { setConfigurationIcon(presentation, configuration, project) } override fun actionPerformed(e: AnActionEvent) { e.project?.let { e.runToolbarData()?.clear() e.setConfiguration(configuration) e.id()?.let {id -> RunToolbarSlotManager.getInstance(it).configurationChanged(id, configuration) } updatePresentation(ExecutionTargetManager.getActiveTarget(project), configuration, project, e.presentation, e.place) } } override fun update(e: AnActionEvent) { super.update(e) updateIcon(e.presentation) } } }
apache-2.0
d53dfd3d211c035562132240b82098fe
34.023256
158
0.705312
4.967018
false
true
false
false
jwren/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/externalCodeProcessing/JKMemberData.kt
2
2528
// 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.nj2k.externalCodeProcessing import com.intellij.psi.PsiField import com.intellij.psi.PsiMember import com.intellij.psi.PsiMethod import com.intellij.psi.SmartPsiElementPointer import org.jetbrains.kotlin.idea.base.utils.fqname.getKotlinFqName import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.psiUtil.isPrivate interface JKMemberData<K : KtDeclaration> { var kotlinElementPointer: SmartPsiElementPointer<K>? var isStatic: Boolean val fqName: FqName? var name: String val kotlinElement get() = kotlinElementPointer?.element val searchInJavaFiles: Boolean get() = true val searchInKotlinFiles: Boolean get() = true val searchingNeeded get() = kotlinElement?.isPrivate() != true && (searchInJavaFiles || searchInKotlinFiles) } interface JKMemberDataCameFromJava<J : PsiMember, K : KtDeclaration> : JKMemberData<K> { val javaElement: J override val fqName get() = javaElement.getKotlinFqName() } interface JKFieldData : JKMemberData<KtProperty> data class JKFakeFieldData( override var isStatic: Boolean, override var kotlinElementPointer: SmartPsiElementPointer<KtProperty>? = null, override val fqName: FqName?, override var name: String ) : JKFieldData { override val searchInJavaFiles: Boolean get() = false override val searchInKotlinFiles: Boolean get() = false } data class JKFieldDataFromJava( override val javaElement: PsiField, override var isStatic: Boolean = false, override var kotlinElementPointer: SmartPsiElementPointer<KtProperty>? = null, override var name: String = javaElement.name ) : JKMemberDataCameFromJava<PsiField, KtProperty>, JKFieldData { override val searchInKotlinFiles: Boolean get() = wasRenamed val wasRenamed: Boolean get() = javaElement.name != name } data class JKMethodData( override val javaElement: PsiMethod, override var isStatic: Boolean = false, override var kotlinElementPointer: SmartPsiElementPointer<KtNamedFunction>? = null, var usedAsAccessorOfProperty: JKFieldData? = null ) : JKMemberDataCameFromJava<PsiMethod, KtNamedFunction> { override var name: String = javaElement.name }
apache-2.0
f4c743ef0929c033e0f5e388754d202d
32.276316
120
0.752769
4.796964
false
false
false
false
androidx/androidx
privacysandbox/tools/tools-apicompiler/src/test/test-data/fullfeaturedsdk/output/com/mysdk/ResponseConverter.kt
3
714
package com.mysdk public object ResponseConverter { public fun fromParcelable(parcelable: ParcelableResponse): Response { val annotatedValue = Response( response = parcelable.response, mySecondInterface = (parcelable.mySecondInterface as MySecondInterfaceStubDelegate).delegate) return annotatedValue } public fun toParcelable(annotatedValue: Response): ParcelableResponse { val parcelable = ParcelableResponse() parcelable.response = annotatedValue.response parcelable.mySecondInterface = MySecondInterfaceStubDelegate(annotatedValue.mySecondInterface) return parcelable } }
apache-2.0
00144476ccf9ce70161ba12b5611e5b8
36.578947
79
0.689076
6.050847
false
false
false
false
androidx/androidx
compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/Card.kt
3
34041
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material3 import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.VectorConverter import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.interaction.DragInteraction import androidx.compose.foundation.interaction.FocusInteraction import androidx.compose.foundation.interaction.HoverInteraction import androidx.compose.foundation.interaction.Interaction import androidx.compose.foundation.interaction.InteractionSource import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.PressInteraction import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.material3.tokens.ElevatedCardTokens import androidx.compose.material3.tokens.FilledCardTokens import androidx.compose.material3.tokens.OutlinedCardTokens import androidx.compose.runtime.Composable import androidx.compose.runtime.Immutable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.compositeOver import androidx.compose.ui.unit.Dp /** * <a href="https://m3.material.io/components/cards/overview" class="external" target="_blank">Material Design filled card</a>. * * Cards contain contain content and actions that relate information about a subject. Filled cards * provide subtle separation from the background. This has less emphasis than elevated or outlined * cards. * * This Card does not handle input events - see the other Card overloads if you want a clickable or * selectable Card. * * ![Filled card image](https://developer.android.com/images/reference/androidx/compose/material3/filled-card.png) * * Card sample: * @sample androidx.compose.material3.samples.CardSample * * @param modifier the [Modifier] to be applied to this card * @param shape defines the shape of this card's container, border (when [border] is not null), and * shadow (when using [elevation]) * @param colors [CardColors] that will be used to resolve the colors used for this card in * different states. See [CardDefaults.cardColors]. * @param elevation [CardElevation] used to resolve the elevation for this card in different states. * This controls the size of the shadow below the card. Additionally, when the container color is * [ColorScheme.surface], this controls the amount of primary color applied as an overlay. See also: * [Surface]. * @param border the border to draw around the container of this card */ @Composable fun Card( modifier: Modifier = Modifier, shape: Shape = CardDefaults.shape, colors: CardColors = CardDefaults.cardColors(), elevation: CardElevation = CardDefaults.cardElevation(), border: BorderStroke? = null, content: @Composable ColumnScope.() -> Unit ) { Surface( modifier = modifier, shape = shape, color = colors.containerColor(enabled = true).value, contentColor = colors.contentColor(enabled = true).value, tonalElevation = elevation.tonalElevation(enabled = true, interactionSource = null).value, shadowElevation = elevation.shadowElevation(enabled = true, interactionSource = null).value, border = border, ) { Column(content = content) } } /** * <a href="https://m3.material.io/components/cards/overview" class="external" target="_blank">Material Design filled card</a>. * * Cards contain contain content and actions that relate information about a subject. Filled cards * provide subtle separation from the background. This has less emphasis than elevated or outlined * cards. * * This Card handles click events, calling its [onClick] lambda. * * ![Filled card image](https://developer.android.com/images/reference/androidx/compose/material3/filled-card.png) * * Clickable card sample: * @sample androidx.compose.material3.samples.ClickableCardSample * * @param onClick called when this card is clicked * @param modifier the [Modifier] to be applied to this card * @param enabled controls the enabled state of this card. When `false`, this component will not * respond to user input, and it will appear visually disabled and disabled to accessibility * services. * @param shape defines the shape of this card's container, border (when [border] is not null), and * shadow (when using [elevation]) * @param colors [CardColors] that will be used to resolve the color(s) used for this card in * different states. See [CardDefaults.cardColors]. * @param elevation [CardElevation] used to resolve the elevation for this card in different states. * This controls the size of the shadow below the card. Additionally, when the container color is * [ColorScheme.surface], this controls the amount of primary color applied as an overlay. See also: * [Surface]. * @param border the border to draw around the container of this card * @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s * for this card. You can create and pass in your own `remember`ed instance to observe * [Interaction]s and customize the appearance / behavior of this card in different states. * */ @ExperimentalMaterial3Api @Composable fun Card( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, shape: Shape = CardDefaults.shape, colors: CardColors = CardDefaults.cardColors(), elevation: CardElevation = CardDefaults.cardElevation(), border: BorderStroke? = null, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable ColumnScope.() -> Unit ) { Surface( onClick = onClick, modifier = modifier, enabled = enabled, shape = shape, color = colors.containerColor(enabled).value, contentColor = colors.contentColor(enabled).value, tonalElevation = elevation.tonalElevation(enabled, interactionSource).value, shadowElevation = elevation.shadowElevation(enabled, interactionSource).value, border = border, interactionSource = interactionSource, ) { Column(content = content) } } /** * <a href="https://m3.material.io/components/cards/overview" class="external" target="_blank">Material Design elevated card</a>. * * Elevated cards contain content and actions that relate information about a subject. They have a * drop shadow, providing more separation from the background than filled cards, but less than * outlined cards. * * This ElevatedCard does not handle input events - see the other ElevatedCard overloads if you * want a clickable or selectable ElevatedCard. * * ![Elevated card image](https://developer.android.com/images/reference/androidx/compose/material3/elevated-card.png) * * Elevated card sample: * @sample androidx.compose.material3.samples.ElevatedCardSample * * @param modifier the [Modifier] to be applied to this card * @param shape defines the shape of this card's container and shadow (when using [elevation]) * @param colors [CardColors] that will be used to resolve the color(s) used for this card in * different states. See [CardDefaults.elevatedCardElevation]. * @param elevation [CardElevation] used to resolve the elevation for this card in different states. * This controls the size of the shadow below the card. Additionally, when the container color is * [ColorScheme.surface], this controls the amount of primary color applied as an overlay. See also: * [Surface]. */ @Composable fun ElevatedCard( modifier: Modifier = Modifier, shape: Shape = CardDefaults.elevatedShape, colors: CardColors = CardDefaults.elevatedCardColors(), elevation: CardElevation = CardDefaults.elevatedCardElevation(), content: @Composable ColumnScope.() -> Unit ) = Card( modifier = modifier, shape = shape, border = null, elevation = elevation, colors = colors, content = content ) /** * <a href="https://m3.material.io/components/cards/overview" class="external" target="_blank">Material Design elevated card</a>. * * Elevated cards contain content and actions that relate information about a subject. They have a * drop shadow, providing more separation from the background than filled cards, but less than * outlined cards. * * This ElevatedCard handles click events, calling its [onClick] lambda. * * ![Elevated card image](https://developer.android.com/images/reference/androidx/compose/material3/elevated-card.png) * * Clickable elevated card sample: * @sample androidx.compose.material3.samples.ClickableElevatedCardSample * * @param onClick called when this card is clicked * @param modifier the [Modifier] to be applied to this card * @param enabled controls the enabled state of this card. When `false`, this component will not * respond to user input, and it will appear visually disabled and disabled to accessibility * services. * @param shape defines the shape of this card's container and shadow (when using [elevation]) * @param colors [CardColors] that will be used to resolve the color(s) used for this card in * different states. See [CardDefaults.elevatedCardElevation]. * @param elevation [CardElevation] used to resolve the elevation for this card in different states. * This controls the size of the shadow below the card. Additionally, when the container color is * [ColorScheme.surface], this controls the amount of primary color applied as an overlay. See also: * [Surface]. * @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s * for this card. You can create and pass in your own `remember`ed instance to observe * [Interaction]s and customize the appearance / behavior of this card in different states. */ @ExperimentalMaterial3Api @Composable fun ElevatedCard( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, shape: Shape = CardDefaults.elevatedShape, colors: CardColors = CardDefaults.elevatedCardColors(), elevation: CardElevation = CardDefaults.elevatedCardElevation(), interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable ColumnScope.() -> Unit ) = Card( onClick = onClick, modifier = modifier, enabled = enabled, shape = shape, colors = colors, elevation = elevation, border = null, interactionSource = interactionSource, content = content ) /** * <a href="https://m3.material.io/components/cards/overview" class="external" target="_blank">Material Design outlined card</a>. * * Outlined cards contain content and actions that relate information about a subject. They have a * visual boundary around the container. This can provide greater emphasis than the other types. * * This OutlinedCard does not handle input events - see the other OutlinedCard overloads if you want * a clickable or selectable OutlinedCard. * * ![Outlined card image](https://developer.android.com/images/reference/androidx/compose/material3/outlined-card.png) * * Outlined card sample: * @sample androidx.compose.material3.samples.OutlinedCardSample * * @param modifier the [Modifier] to be applied to this card * @param shape defines the shape of this card's container, border (when [border] is not null), and * shadow (when using [elevation]) * @param colors [CardColors] that will be used to resolve the color(s) used for this card in * different states. See [CardDefaults.outlinedCardColors]. * @param elevation [CardElevation] used to resolve the elevation for this card in different states. * This controls the size of the shadow below the card. Additionally, when the container color is * [ColorScheme.surface], this controls the amount of primary color applied as an overlay. See also: * [Surface]. * @param border the border to draw around the container of this card */ @Composable fun OutlinedCard( modifier: Modifier = Modifier, shape: Shape = CardDefaults.outlinedShape, colors: CardColors = CardDefaults.outlinedCardColors(), elevation: CardElevation = CardDefaults.outlinedCardElevation(), border: BorderStroke = CardDefaults.outlinedCardBorder(), content: @Composable ColumnScope.() -> Unit ) = Card( modifier = modifier, shape = shape, colors = colors, elevation = elevation, border = border, content = content ) /** * <a href="https://m3.material.io/components/cards/overview" class="external" target="_blank">Material Design outlined card</a>. * * Outlined cards contain content and actions that relate information about a subject. They have a * visual boundary around the container. This can provide greater emphasis than the other types. * * This OutlinedCard handles click events, calling its [onClick] lambda. * * ![Outlined card image](https://developer.android.com/images/reference/androidx/compose/material3/outlined-card.png) * * Clickable outlined card sample: * @sample androidx.compose.material3.samples.ClickableOutlinedCardSample * * @param onClick called when this card is clicked * @param modifier the [Modifier] to be applied to this card * @param enabled controls the enabled state of this card. When `false`, this component will not * respond to user input, and it will appear visually disabled and disabled to accessibility * services. * @param shape defines the shape of this card's container, border (when [border] is not null), and * shadow (when using [elevation]) * @param colors [CardColors] that will be used to resolve the color(s) used for this card in * different states. See [CardDefaults.outlinedCardColors]. * @param elevation [CardElevation] used to resolve the elevation for this card in different states. * This controls the size of the shadow below the card. Additionally, when the container color is * [ColorScheme.surface], this controls the amount of primary color applied as an overlay. See also: * [Surface]. * @param border the border to draw around the container of this card * @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s * for this card. You can create and pass in your own `remember`ed instance to observe * [Interaction]s and customize the appearance / behavior of this card in different states. */ @ExperimentalMaterial3Api @Composable fun OutlinedCard( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, shape: Shape = CardDefaults.outlinedShape, colors: CardColors = CardDefaults.outlinedCardColors(), elevation: CardElevation = CardDefaults.outlinedCardElevation(), border: BorderStroke = CardDefaults.outlinedCardBorder(enabled), interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable ColumnScope.() -> Unit ) = Card( onClick = onClick, modifier = modifier, enabled = enabled, shape = shape, colors = colors, elevation = elevation, border = border, interactionSource = interactionSource, content = content ) /** * Contains the default values used by all card types. */ object CardDefaults { // shape Defaults /** Default shape for a card. */ val shape: Shape @Composable get() = FilledCardTokens.ContainerShape.toShape() /** Default shape for an elevated card. */ val elevatedShape: Shape @Composable get() = ElevatedCardTokens.ContainerShape.toShape() /** Default shape for an outlined card. */ val outlinedShape: Shape @Composable get() = OutlinedCardTokens.ContainerShape.toShape() /** * Creates a [CardElevation] that will animate between the provided values according to the * Material specification for a [Card]. * * @param defaultElevation the elevation used when the [Card] is has no other [Interaction]s. * @param pressedElevation the elevation used when the [Card] is pressed. * @param focusedElevation the elevation used when the [Card] is focused. * @param hoveredElevation the elevation used when the [Card] is hovered. * @param draggedElevation the elevation used when the [Card] is dragged. */ @Composable fun cardElevation( defaultElevation: Dp = FilledCardTokens.ContainerElevation, pressedElevation: Dp = FilledCardTokens.PressedContainerElevation, focusedElevation: Dp = FilledCardTokens.FocusContainerElevation, hoveredElevation: Dp = FilledCardTokens.HoverContainerElevation, draggedElevation: Dp = FilledCardTokens.DraggedContainerElevation, disabledElevation: Dp = FilledCardTokens.DisabledContainerElevation ): CardElevation = CardElevation( defaultElevation = defaultElevation, pressedElevation = pressedElevation, focusedElevation = focusedElevation, hoveredElevation = hoveredElevation, draggedElevation = draggedElevation, disabledElevation = disabledElevation ) /** * Creates a [CardElevation] that will animate between the provided values according to the * Material specification for an [ElevatedCard]. * * @param defaultElevation the elevation used when the [ElevatedCard] is has no other * [Interaction]s. * @param pressedElevation the elevation used when the [ElevatedCard] is pressed. * @param focusedElevation the elevation used when the [ElevatedCard] is focused. * @param hoveredElevation the elevation used when the [ElevatedCard] is hovered. * @param draggedElevation the elevation used when the [ElevatedCard] is dragged. */ @Composable fun elevatedCardElevation( defaultElevation: Dp = ElevatedCardTokens.ContainerElevation, pressedElevation: Dp = ElevatedCardTokens.PressedContainerElevation, focusedElevation: Dp = ElevatedCardTokens.FocusContainerElevation, hoveredElevation: Dp = ElevatedCardTokens.HoverContainerElevation, draggedElevation: Dp = ElevatedCardTokens.DraggedContainerElevation, disabledElevation: Dp = ElevatedCardTokens.DisabledContainerElevation ): CardElevation = CardElevation( defaultElevation = defaultElevation, pressedElevation = pressedElevation, focusedElevation = focusedElevation, hoveredElevation = hoveredElevation, draggedElevation = draggedElevation, disabledElevation = disabledElevation ) /** * Creates a [CardElevation] that will animate between the provided values according to the * Material specification for an [OutlinedCard]. * * @param defaultElevation the elevation used when the [OutlinedCard] is has no other * [Interaction]s. * @param pressedElevation the elevation used when the [OutlinedCard] is pressed. * @param focusedElevation the elevation used when the [OutlinedCard] is focused. * @param hoveredElevation the elevation used when the [OutlinedCard] is hovered. * @param draggedElevation the elevation used when the [OutlinedCard] is dragged. */ @Composable fun outlinedCardElevation( defaultElevation: Dp = OutlinedCardTokens.ContainerElevation, pressedElevation: Dp = defaultElevation, focusedElevation: Dp = defaultElevation, hoveredElevation: Dp = defaultElevation, draggedElevation: Dp = OutlinedCardTokens.DraggedContainerElevation, disabledElevation: Dp = OutlinedCardTokens.DisabledContainerElevation ): CardElevation = CardElevation( defaultElevation = defaultElevation, pressedElevation = pressedElevation, focusedElevation = focusedElevation, hoveredElevation = hoveredElevation, draggedElevation = draggedElevation, disabledElevation = disabledElevation ) /** * Creates a [CardColors] that represents the default container and content colors used in a * [Card]. * * @param containerColor the container color of this [Card] when enabled. * @param contentColor the content color of this [Card] when enabled. * @param disabledContainerColor the container color of this [Card] when not enabled. * @param disabledContentColor the content color of this [Card] when not enabled. */ @Composable fun cardColors( containerColor: Color = FilledCardTokens.ContainerColor.toColor(), contentColor: Color = contentColorFor(containerColor), disabledContainerColor: Color = FilledCardTokens.DisabledContainerColor.toColor() .copy(alpha = FilledCardTokens.DisabledContainerOpacity) .compositeOver( MaterialTheme.colorScheme.surfaceColorAtElevation( FilledCardTokens.DisabledContainerElevation ) ), disabledContentColor: Color = contentColorFor(containerColor).copy(DisabledAlpha), ): CardColors = CardColors( containerColor = containerColor, contentColor = contentColor, disabledContainerColor = disabledContainerColor, disabledContentColor = disabledContentColor ) /** * Creates a [CardColors] that represents the default container and content colors used in an * [ElevatedCard]. * * @param containerColor the container color of this [ElevatedCard] when enabled. * @param contentColor the content color of this [ElevatedCard] when enabled. * @param disabledContainerColor the container color of this [ElevatedCard] when not enabled. * @param disabledContentColor the content color of this [ElevatedCard] when not enabled. */ @Composable fun elevatedCardColors( containerColor: Color = ElevatedCardTokens.ContainerColor.toColor(), contentColor: Color = contentColorFor(containerColor), disabledContainerColor: Color = ElevatedCardTokens.DisabledContainerColor.toColor() .copy(alpha = ElevatedCardTokens.DisabledContainerOpacity) .compositeOver( MaterialTheme.colorScheme.surfaceColorAtElevation( ElevatedCardTokens.DisabledContainerElevation ) ), disabledContentColor: Color = contentColor.copy(DisabledAlpha), ): CardColors = CardColors( containerColor = containerColor, contentColor = contentColor, disabledContainerColor = disabledContainerColor, disabledContentColor = disabledContentColor ) /** * Creates a [CardColors] that represents the default container and content colors used in an * [OutlinedCard]. * * @param containerColor the container color of this [OutlinedCard] when enabled. * @param contentColor the content color of this [OutlinedCard] when enabled. * @param disabledContainerColor the container color of this [OutlinedCard] when not enabled. * @param disabledContentColor the content color of this [OutlinedCard] when not enabled. */ @Composable fun outlinedCardColors( containerColor: Color = OutlinedCardTokens.ContainerColor.toColor(), contentColor: Color = contentColorFor(containerColor), disabledContainerColor: Color = containerColor, disabledContentColor: Color = contentColor.copy(DisabledAlpha), ): CardColors = CardColors( containerColor = containerColor, contentColor = contentColor, disabledContainerColor = disabledContainerColor, disabledContentColor = disabledContentColor ) /** * Creates a [BorderStroke] that represents the default border used in [OutlinedCard]. * * @param enabled whether the card is enabled */ @Composable fun outlinedCardBorder(enabled: Boolean = true): BorderStroke { val color = if (enabled) { OutlinedCardTokens.OutlineColor.toColor() } else { OutlinedCardTokens.DisabledOutlineColor.toColor() .copy(alpha = OutlinedCardTokens.DisabledOutlineOpacity) .compositeOver( MaterialTheme.colorScheme.surfaceColorAtElevation( OutlinedCardTokens.DisabledContainerElevation ) ) } return remember(color) { BorderStroke(OutlinedCardTokens.OutlineWidth, color) } } } /** * Represents the elevation for a card in different states. * * - See [CardDefaults.cardElevation] for the default elevation used in a [Card]. * - See [CardDefaults.elevatedCardElevation] for the default elevation used in an [ElevatedCard]. * - See [CardDefaults.outlinedCardElevation] for the default elevation used in an [OutlinedCard]. */ @Immutable class CardElevation internal constructor( private val defaultElevation: Dp, private val pressedElevation: Dp, private val focusedElevation: Dp, private val hoveredElevation: Dp, private val draggedElevation: Dp, private val disabledElevation: Dp ) { /** * Represents the tonal elevation used in a card, depending on its [enabled] state and * [interactionSource]. This should typically be the same value as the [shadowElevation]. * * Tonal elevation is used to apply a color shift to the surface to give the it higher emphasis. * When surface's color is [ColorScheme.surface], a higher elevation will result in a darker * color in light theme and lighter color in dark theme. * * See [shadowElevation] which controls the elevation of the shadow drawn around the card. * * @param enabled whether the card is enabled * @param interactionSource the [InteractionSource] for this card */ @Composable internal fun tonalElevation( enabled: Boolean, interactionSource: InteractionSource? ): State<Dp> { if (interactionSource == null) { return remember { mutableStateOf(defaultElevation) } } return animateElevation(enabled = enabled, interactionSource = interactionSource) } /** * Represents the shadow elevation used in a card, depending on its [enabled] state and * [interactionSource]. This should typically be the same value as the [tonalElevation]. * * Shadow elevation is used to apply a shadow around the card to give it higher emphasis. * * See [tonalElevation] which controls the elevation with a color shift to the surface. * * @param enabled whether the card is enabled * @param interactionSource the [InteractionSource] for this card */ @Composable internal fun shadowElevation( enabled: Boolean, interactionSource: InteractionSource? ): State<Dp> { if (interactionSource == null) { return remember { mutableStateOf(defaultElevation) } } return animateElevation(enabled = enabled, interactionSource = interactionSource) } @Composable private fun animateElevation( enabled: Boolean, interactionSource: InteractionSource ): State<Dp> { val interactions = remember { mutableStateListOf<Interaction>() } LaunchedEffect(interactionSource) { interactionSource.interactions.collect { interaction -> when (interaction) { is HoverInteraction.Enter -> { interactions.add(interaction) } is HoverInteraction.Exit -> { interactions.remove(interaction.enter) } is FocusInteraction.Focus -> { interactions.add(interaction) } is FocusInteraction.Unfocus -> { interactions.remove(interaction.focus) } is PressInteraction.Press -> { interactions.add(interaction) } is PressInteraction.Release -> { interactions.remove(interaction.press) } is PressInteraction.Cancel -> { interactions.remove(interaction.press) } is DragInteraction.Start -> { interactions.add(interaction) } is DragInteraction.Stop -> { interactions.remove(interaction.start) } is DragInteraction.Cancel -> { interactions.remove(interaction.start) } } } } val interaction = interactions.lastOrNull() val target = if (!enabled) { disabledElevation } else { when (interaction) { is PressInteraction.Press -> pressedElevation is HoverInteraction.Enter -> hoveredElevation is FocusInteraction.Focus -> focusedElevation is DragInteraction.Start -> draggedElevation else -> defaultElevation } } val animatable = remember { Animatable(target, Dp.VectorConverter) } LaunchedEffect(target) { if (enabled) { val lastInteraction = when (animatable.targetValue) { pressedElevation -> PressInteraction.Press(Offset.Zero) hoveredElevation -> HoverInteraction.Enter() focusedElevation -> FocusInteraction.Focus() draggedElevation -> DragInteraction.Start() else -> null } animatable.animateElevation( from = lastInteraction, to = interaction, target = target ) } else { // No transition when moving to a disabled state. animatable.snapTo(target) } } return animatable.asState() } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || other !is CardElevation) return false if (defaultElevation != other.defaultElevation) return false if (pressedElevation != other.pressedElevation) return false if (focusedElevation != other.focusedElevation) return false if (hoveredElevation != other.hoveredElevation) return false if (disabledElevation != other.disabledElevation) return false return true } override fun hashCode(): Int { var result = defaultElevation.hashCode() result = 31 * result + pressedElevation.hashCode() result = 31 * result + focusedElevation.hashCode() result = 31 * result + hoveredElevation.hashCode() result = 31 * result + disabledElevation.hashCode() return result } } /** * Represents the container and content colors used in a card in different states. * * - See [CardDefaults.cardColors] for the default colors used in a [Card]. * - See [CardDefaults.elevatedCardColors] for the default colors used in a [ElevatedCard]. * - See [CardDefaults.outlinedCardColors] for the default colors used in a [OutlinedCard]. */ @Immutable class CardColors internal constructor( private val containerColor: Color, private val contentColor: Color, private val disabledContainerColor: Color, private val disabledContentColor: Color, ) { /** * Represents the container color for this card, depending on [enabled]. * * @param enabled whether the card is enabled */ @Composable internal fun containerColor(enabled: Boolean): State<Color> { return rememberUpdatedState(if (enabled) containerColor else disabledContainerColor) } /** * Represents the content color for this card, depending on [enabled]. * * @param enabled whether the card is enabled */ @Composable internal fun contentColor(enabled: Boolean): State<Color> { return rememberUpdatedState(if (enabled) contentColor else disabledContentColor) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || other !is CardColors) return false if (containerColor != other.containerColor) return false if (contentColor != other.contentColor) return false if (disabledContainerColor != other.disabledContainerColor) return false if (disabledContentColor != other.disabledContentColor) return false return true } override fun hashCode(): Int { var result = containerColor.hashCode() result = 31 * result + contentColor.hashCode() result = 31 * result + disabledContainerColor.hashCode() result = 31 * result + disabledContentColor.hashCode() return result } }
apache-2.0
cea6c91349c2e83199ef6098b0d041ac
43.151751
129
0.700978
5.258922
false
false
false
false
GunoH/intellij-community
plugins/kotlin/jvm-debugger/core-fe10/src/org/jetbrains/kotlin/idea/debugger/stepping/smartStepInto/KotlinSmartStepIntoHandler.kt
4
8566
// 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.debugger.stepping.smartStepInto import com.intellij.debugger.SourcePosition import com.intellij.debugger.actions.JvmSmartStepIntoHandler import com.intellij.debugger.actions.SmartStepTarget import com.intellij.debugger.engine.DebugProcessImpl import com.intellij.debugger.engine.DebuggerManagerThreadImpl import com.intellij.debugger.engine.MethodFilter import com.intellij.debugger.engine.events.DebuggerCommandImpl import com.intellij.debugger.impl.DebuggerSession import com.intellij.debugger.impl.PrioritizedTask import com.intellij.debugger.jdi.MethodBytecodeUtil import com.intellij.openapi.application.ReadAction import com.intellij.openapi.progress.ProgressManager import com.intellij.psi.PsiDocumentManager import com.intellij.util.Range import com.intellij.util.containers.OrderedSet import com.sun.jdi.Location import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.compute import org.jetbrains.kotlin.idea.base.psi.getTopmostElementAtOffset import org.jetbrains.kotlin.idea.debugger.base.util.DexDebugFacility import org.jetbrains.kotlin.idea.debugger.KotlinDebuggerSettings import org.jetbrains.kotlin.idea.debugger.base.util.safeLocation import org.jetbrains.kotlin.idea.debugger.base.util.safeMethod import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile class KotlinSmartStepIntoHandler : JvmSmartStepIntoHandler() { override fun isAvailable(position: SourcePosition?) = position?.file is KtFile override fun findStepIntoTargets(position: SourcePosition, session: DebuggerSession) = if (KotlinDebuggerSettings.getInstance().alwaysDoSmartStepInto) { findSmartStepTargetsAsync(position, session) } else { super.findStepIntoTargets(position, session) } override fun findSmartStepTargetsAsync(position: SourcePosition, session: DebuggerSession): Promise<List<SmartStepTarget>> { val result = AsyncPromise<List<SmartStepTarget>>() val command = object : DebuggerCommandImpl(PrioritizedTask.Priority.NORMAL) { override fun action() = result.compute { findSmartStepTargetsInReadAction(position, session) } override fun commandCancelled() { result.setError("Cancelled") } } val managerThread = session.process.managerThread if (DebuggerManagerThreadImpl.isManagerThread()) { managerThread.invoke(command) } else { managerThread.schedule(command) } return result } override fun findSmartStepTargets(position: SourcePosition): List<SmartStepTarget> = findSmartStepTargetsInReadAction(position, null) override fun createMethodFilter(stepTarget: SmartStepTarget?): MethodFilter? = when (stepTarget) { is KotlinSmartStepTarget -> stepTarget.createMethodFilter() else -> super.createMethodFilter(stepTarget) } private fun findSmartStepTargetsInReadAction(position: SourcePosition, session: DebuggerSession?) = ReadAction.nonBlocking<List<SmartStepTarget>> { findSmartStepTargets(position, session) }.executeSynchronously() private fun findSmartStepTargets(position: SourcePosition, session: DebuggerSession?): List<SmartStepTarget> { val topmostElement = position.getTopmostElement() ?: return emptyList() val lines = topmostElement.getLines() ?: return emptyList() var targets = findSmartStepTargets(topmostElement, lines) if (session != null) { targets = calculateSmartStepTargetsToShow(targets, session.process, lines.toClosedRange()) } return reorderWithSteppingFilters(targets) } } private fun findSmartStepTargets(topmostElement: KtElement, lines: Range<Int>): List<SmartStepTarget> { val targets = OrderedSet<SmartStepTarget>() val visitor = SmartStepTargetVisitor(topmostElement, lines, targets) topmostElement.accept(visitor, null) return targets } private fun calculateSmartStepTargetsToShow(targets: List<SmartStepTarget>, debugProcess: DebugProcessImpl, lines: ClosedRange<Int>): List<SmartStepTarget> { val lambdaTargets = mutableListOf<SmartStepTarget>() val methodTargets = mutableListOf<KotlinMethodSmartStepTarget>() for (target in targets) { if (target is KotlinMethodSmartStepTarget) { methodTargets.add(target) } else { lambdaTargets.add(target) } } return lambdaTargets + methodTargets.filterAlreadyExecuted(debugProcess, lines) } private fun List<KotlinMethodSmartStepTarget>.filterAlreadyExecuted( debugProcess: DebugProcessImpl, lines: ClosedRange<Int> ): List<KotlinMethodSmartStepTarget> { DebuggerManagerThreadImpl.assertIsManagerThread() if (DexDebugFacility.isDex(debugProcess) || size <= 1) return this val frameProxy = debugProcess.suspendManager.pausedContext?.frameProxy val location = frameProxy?.safeLocation() ?: return this return filterSmartStepTargets(location, lines, this, debugProcess) } private fun SourcePosition.getTopmostElement(): KtElement? { val element = elementAt ?: return null return getTopmostElementAtOffset(element, element.textRange.startOffset) as? KtElement } private fun KtElement.getLines(): Range<Int>? { val file = containingKtFile val document = PsiDocumentManager.getInstance(file.project).getDocument(file) ?: return null val textRange = textRange return Range(document.getLineNumber(textRange.startOffset), document.getLineNumber(textRange.endOffset)) } private fun filterSmartStepTargets( location: Location, lines: ClosedRange<Int>, targets: List<KotlinMethodSmartStepTarget>, debugProcess: DebugProcessImpl ): List<KotlinMethodSmartStepTarget> { val method = location.safeMethod() ?: return targets val targetFilterer = KotlinSmartStepTargetFilterer(targets, debugProcess) val targetFiltererAdapter = KotlinSmartStepTargetFiltererAdapter( lines, location, debugProcess.positionManager, targetFilterer ) val visitedOpcodes = mutableListOf<Int>() // During the first pass we traverse the whole method to collect its opcodes (the result is different // from method.bytecodes() because of the method visiting policy), and to check // that all smart step targets are filtered out. MethodBytecodeUtil.visit(method, Long.MAX_VALUE, object : OpcodeReportingMethodVisitor(targetFiltererAdapter) { override fun reportOpcode(opcode: Int) { ProgressManager.checkCanceled() visitedOpcodes.add(opcode) targetFiltererAdapter.reportOpcode(opcode) } override fun visitMethodInsn(opcode: Int, owner: String, name: String, descriptor: String, isInterface: Boolean) { targetFiltererAdapter.visitMethodInsn(opcode, owner, name, descriptor, isInterface) } }, true) // We failed to filter out all smart step targets during the traversal of the whole method, so // we can't guarantee the correctness of filtering. if (targetFilterer.getUnvisitedTargets().isNotEmpty()) { return targets } targetFilterer.reset() // During the second pass we traverse a part of the method (until location.codeIndex()), the rest opcodes // will be replaced with mock ones, so we stop when current opcode doesn't match the previously visited one. MethodBytecodeUtil.visit(method, location.codeIndex(), object : OpcodeReportingMethodVisitor(targetFiltererAdapter) { private var visitedOpcodeCnt = 0 private var stopVisiting = false override fun reportOpcode(opcode: Int) { ProgressManager.checkCanceled() if (stopVisiting || opcode != visitedOpcodes[visitedOpcodeCnt++]) { stopVisiting = true return } targetFiltererAdapter.reportOpcode(opcode) } override fun visitMethodInsn(opcode: Int, owner: String, name: String, descriptor: String, isInterface: Boolean) { if (stopVisiting) return targetFiltererAdapter.visitMethodInsn(opcode, owner, name, descriptor, isInterface) } }, true) return targetFilterer.getUnvisitedTargets() } private fun Range<Int>.toClosedRange() = from..to
apache-2.0
df92bd1fbdc15aaa440c3be715e04222
44.322751
157
0.738968
5.204131
false
false
false
false
GunoH/intellij-community
platform/platform-tests/testSrc/com/intellij/observable/SingleEventDispatcherTest.kt
2
3106
// 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.observable import com.intellij.openapi.observable.dispatcher.SingleEventDispatcher import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.use import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import java.util.concurrent.atomic.AtomicInteger class SingleEventDispatcherTest { @Test fun `test event dispatching`() { val dispatcher = SingleEventDispatcher.create() val eventCounter = AtomicInteger() Disposer.newDisposable().use { disposable -> dispatcher.whenEventHappened(disposable) { eventCounter.incrementAndGet() } assertEquals(0, eventCounter.get()) dispatcher.fireEvent() assertEquals(1, eventCounter.get()) dispatcher.fireEvent() assertEquals(2, eventCounter.get()) dispatcher.fireEvent() assertEquals(3, eventCounter.get()) } dispatcher.fireEvent() assertEquals(3, eventCounter.get()) eventCounter.set(0) dispatcher.whenEventHappened { eventCounter.incrementAndGet() } assertEquals(0, eventCounter.get()) dispatcher.fireEvent() assertEquals(1, eventCounter.get()) dispatcher.fireEvent() assertEquals(2, eventCounter.get()) dispatcher.fireEvent() assertEquals(3, eventCounter.get()) } @Test fun `test event dispatching with ttl=1`() { val dispatcher = SingleEventDispatcher.create() val eventCounter = AtomicInteger() dispatcher.onceWhenEventHappened { eventCounter.incrementAndGet() } assertEquals(0, eventCounter.get()) dispatcher.fireEvent() assertEquals(1, eventCounter.get()) dispatcher.fireEvent() assertEquals(1, eventCounter.get()) eventCounter.set(0) Disposer.newDisposable().use { disposable -> dispatcher.onceWhenEventHappened(disposable) { eventCounter.incrementAndGet() } assertEquals(0, eventCounter.get()) } dispatcher.fireEvent() assertEquals(0, eventCounter.get()) } @Test fun `test event dispatching with ttl=N`() { val dispatcher = SingleEventDispatcher.create() val eventCounter = AtomicInteger() dispatcher.whenEventHappened(10) { eventCounter.incrementAndGet() } repeat(10) { assertEquals(it, eventCounter.get()) dispatcher.fireEvent() assertEquals(it + 1, eventCounter.get()) } dispatcher.fireEvent() assertEquals(10, eventCounter.get()) dispatcher.fireEvent() assertEquals(10, eventCounter.get()) eventCounter.set(0) Disposer.newDisposable().use { disposable -> dispatcher.whenEventHappened(10, disposable) { eventCounter.incrementAndGet() } repeat(5) { assertEquals(it, eventCounter.get()) dispatcher.fireEvent() assertEquals(it + 1, eventCounter.get()) } } dispatcher.fireEvent() assertEquals(5, eventCounter.get()) dispatcher.fireEvent() assertEquals(5, eventCounter.get()) } }
apache-2.0
dc7667ff938ae5a27b6430114104140a
28.590476
120
0.695428
4.706061
false
true
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ui/charts/ChartWrapper.kt
2
13061
// 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.ui.charts import com.intellij.ui.ColorUtil import com.intellij.ui.JBColor import com.intellij.util.ui.GraphicsUtil import com.intellij.util.ui.JBUI import org.intellij.lang.annotations.MagicConstant import java.awt.* import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import java.util.function.Consumer import javax.swing.JComponent import javax.swing.SwingConstants import kotlin.math.absoluteValue import kotlin.math.roundToInt import kotlin.math.sign interface ChartComponent { fun paintComponent(g: Graphics2D) } /** * Holds instance of ChartWrapper in which has been added. */ abstract class Overlay<T: ChartWrapper>: ChartComponent { var wrapper: ChartWrapper? = null set(value) { field = value afterChartInitialized() } var mouseLocation: Point? = null /** * Typed value for {@code wrapper}. * * Normally wrapper is already initialized when added to ChartWrapper. */ val chart: T @Suppress("UNCHECKED_CAST") get() = wrapper as T open fun afterChartInitialized() { } fun Point.toChartSpace(): Point? = wrapper?.let { if (it.margins.left < x && x < it.width - it.margins.right && it.margins.top < y && y < it.height - it.margins.bottom) { Point(x - it.margins.left, y - it.margins.top) } else null } } interface XYChartComponent<X: Number, Y: Number> { val ranges: MinMax<X, Y> } abstract class GridChartWrapper<X: Number, Y: Number>: ChartWrapper(), XYChartComponent<X, Y> { abstract override val ranges: Grid<X, Y> val grid: Grid<X, Y> get() = ranges val gridWidth: Int get() = width - (margins.left + margins.right) val gridHeight: Int get() = height - (margins.top + margins.bottom) var gridColor: Color = JBColor(Color(0xF0F0F0), Color(0x313335)) var gridLabelColor: Color = ColorUtil.withAlpha(JBColor.foreground(), 0.6) protected fun paintGrid(grid: Graphics2D, chart: Graphics2D, xy: MinMax<X, Y>) { val gc = Color(gridColor.rgb) val gcd = gc.darker() val bounds = grid.clipBounds val xOrigin: Int = if (ranges.xOriginInitialized) findX(xy, ranges.xOrigin).toInt() else 0 val yOrigin: Int = if (ranges.yOriginInitialized) findY(xy, ranges.yOrigin).toInt() else height var tmp: Int // — helps to filter line drawing, when lines are met too often // draws vertical grid lines tmp = -1 ranges.xLines.apply { min = xy.xMin max = xy.xMax }.forEach { val gl = GridLine(it, xy, SwingConstants.VERTICAL).apply(ranges.xPainter::accept) val px = findGridLineX(gl, it).roundToInt() if (gl.paintLine) { if ((tmp - px).absoluteValue < 1) { return@forEach } else { tmp = px } grid.color = if (gl.majorLine) gcd else gc grid.drawLine(px, bounds.y, px, bounds.y + bounds.height) } gl.label?.let { label -> chart.color = gridLabelColor val (x, y) = findGridLabelOffset(gl, chart) chart.drawString(label, px + margins.left - x.toInt(), yOrigin - margins.bottom + y.toInt()) } } // draws horizontal grid lines tmp = -1 ranges.yLines.apply { min = xy.yMin max = xy.yMax }.forEach { val gl = GridLine(it, xy).apply(ranges.yPainter::accept) val py = findGridLineY(gl, it).roundToInt() if (gl.paintLine) { if ((tmp - py).absoluteValue < 1) { return@forEach } else { tmp = py } grid.color = if (gl.majorLine) gcd else gc grid.drawLine(bounds.x, py, bounds.x + bounds.width, py) } gl.label?.let { label -> chart.color = gridLabelColor val (x, y) = findGridLabelOffset(gl, chart) chart.drawString(label, xOrigin + margins.left - x.toInt(), py + margins.top + y.toInt() ) } } } protected open fun findGridLineX(gl: GridLine<X, Y, *>, x: X) = findX(gl.xy, x) protected open fun findGridLineY(gl: GridLine<X, Y, *>, y: Y) = findY(gl.xy, y) abstract fun findMinMax(): MinMax<X, Y> protected open fun findX(xy: MinMax<X, Y>, x: X): Double { val width = width - (margins.left + margins.right) return width * (x.toDouble() - xy.xMin.toDouble()) / (xy.xMax.toDouble() - xy.xMin.toDouble()) } protected open fun findY(xy: MinMax<X, Y>, y: Y): Double { val height = height - (margins.top + margins.bottom) return height - height * (y.toDouble() - xy.yMin.toDouble()) / (xy.yMax.toDouble() - xy.yMin.toDouble()) } protected open fun findGridLabelOffset(line: GridLine<*, *, *>, g: Graphics2D): Coordinates<Double, Double> { val s = JBUI.scale(4).toDouble() val b = g.fontMetrics.getStringBounds(line.label, null) val x = when (line.horizontalAlignment) { SwingConstants.RIGHT -> -s SwingConstants.CENTER -> b.width / 2 SwingConstants.LEFT -> b.width + s else -> -s } val y = b.height - when (line.verticalAlignment) { SwingConstants.TOP -> b.height + s SwingConstants.CENTER -> b.height / 2 + s / 2 // compensate SwingConstants.BOTTOM -> 0.0 else -> 0.0 } return x to y } } abstract class ChartWrapper : ChartComponent { var width: Int = 0 private set var height: Int = 0 private set var background: Color = JBColor.background() var overlays: List<ChartComponent> = mutableListOf() set(value) { field.forEach { if (it is Overlay<*>) it.wrapper = null } (field as MutableList<ChartComponent>).addAll(value) field.forEach { if (it is Overlay<*>) it.wrapper = this } } var margins = Insets(0, 0, 0, 0) open fun paintOverlay(g: Graphics2D) { overlays.forEach { it.paintComponent(g) } } open val component: JComponent by lazy { createCentralPanel().apply { with(MouseAware()) { addMouseMotionListener(this) addMouseListener(this) } } } fun update() = component.repaint() protected open fun createCentralPanel(): JComponent = CentralPanel() protected var mouseLocation: Point? = null private set(value) { field = value overlays.forEach { if (it is Overlay<*>) it.mouseLocation = value } } private inner class MouseAware : MouseAdapter() { override fun mouseMoved(e: MouseEvent) { mouseLocation = e.point component.repaint() } override fun mouseEntered(e: MouseEvent) { mouseLocation = e.point component.repaint() } override fun mouseExited(e: MouseEvent) { mouseLocation = null component.repaint() } override fun mouseDragged(e: MouseEvent) { mouseLocation = e.point component.repaint() } } private inner class CentralPanel : JComponent() { override fun paintComponent(g: Graphics) { g.clip = Rectangle(0, 0, width, height) g.color = [email protected] (g as Graphics2D).fill(g.clip) [email protected] = height [email protected] = width val gridGraphics = (g.create(0, 0, [email protected], [email protected]) as Graphics2D).apply { setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED) setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE) GraphicsUtil.setupAntialiasing(this) } try { [email protected](gridGraphics) } finally { gridGraphics.dispose() } val overlayGraphics = (g.create() as Graphics2D).apply { setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED) setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE) GraphicsUtil.setupAntialiasing(this) } try { [email protected](overlayGraphics) } finally { overlayGraphics.dispose() } } } } open class Dataset<T> { var label: String? = null var lineColor: Paint? = JBColor.foreground() var fillColor: Paint? = null open var data: Iterable<T> = mutableListOf() fun add(vararg values: T) { addAll(values.toList()) } fun addAll(values: Collection<T>) { (data as? MutableList<T>)?.addAll(values) ?: throw UnsupportedOperationException() } fun Color.transparent(alpha: Double) = ColorUtil.withAlpha(this, alpha) } data class Coordinates<X: Number, Y: Number>(val x: X, val y: Y) { companion object { @JvmStatic fun <X: Number, Y: Number> of(x: X, y: Y) : Coordinates<X, Y> = Coordinates(x, y) } } infix fun <X: Number, Y: Number> X.to(y: Y): Coordinates<X, Y> = Coordinates(this, y) open class MinMax<X: Number, Y: Number> { lateinit var xMin: X private val xMinInitialized get() = this::xMin.isInitialized lateinit var xMax: X val xMaxInitialized get() = this::xMax.isInitialized lateinit var yMin: Y private val yMinInitialized get() = this::yMin.isInitialized lateinit var yMax: Y val yMaxInitialized get() = this::yMax.isInitialized fun process(point: Coordinates<X, Y>) { val (x, y) = point process(x, y) } fun process(x: X, y: Y) { processX(x) processY(y) } private fun processX(x: X) { xMin = if (!xMinInitialized || xMin.toDouble() > x.toDouble()) x else xMin xMax = if (!xMaxInitialized || xMax.toDouble() < x.toDouble()) x else xMax } private fun processY(y: Y) { yMin = if (!yMinInitialized || yMin.toDouble() > y.toDouble()) y else yMin yMax = if (!yMaxInitialized || yMax.toDouble() < y.toDouble()) y else yMax } operator fun times(other: MinMax<X, Y>): MinMax<X, Y> { val my = MinMax<X, Y>() if (this.xMinInitialized) my.xMin = this.xMin else if (other.xMinInitialized) my.xMin = other.xMin if (this.xMaxInitialized) my.xMax = this.xMax else if (other.xMaxInitialized) my.xMax = other.xMax if (this.yMinInitialized) my.yMin = this.yMin else if (other.yMinInitialized) my.yMin = other.yMin if (this.yMaxInitialized) my.yMax = this.yMax else if (other.yMaxInitialized) my.yMax = other.yMax return my } operator fun plus(other: MinMax<X, Y>) : MinMax<X, Y> { val my = MinMax<X, Y>() help(this.xMinInitialized, this::xMin, other.xMinInitialized, other::xMin, -1, my::xMin.setter) help(this.xMaxInitialized, this::xMax, other.xMaxInitialized, other::xMax, 1, my::xMax.setter) help(this.yMinInitialized, this::yMin, other.yMinInitialized, other::yMin, -1, my::yMin.setter) help(this.yMaxInitialized, this::yMax, other.yMaxInitialized, other::yMax, 1, my::yMax.setter) return my } private fun <T: Number> help(thisInitialized: Boolean, thisGetter: () -> T, otherInitialized: Boolean, otherGetter: () -> T, sign: Int, calc: (T) -> Unit) { when { thisInitialized && otherInitialized -> { val thisValue = thisGetter().toDouble() val thatValue = otherGetter().toDouble() calc(if (thisValue.compareTo(thatValue).sign == sign) thisGetter() else otherGetter()) } thisInitialized && !otherInitialized -> calc((thisGetter())) !thisInitialized && otherInitialized -> calc(otherGetter()) } } operator fun component1(): X = xMin operator fun component2(): X = xMax operator fun component3(): Y = yMin operator fun component4(): Y = yMax val isInitialized get() = xMinInitialized && xMaxInitialized && yMinInitialized && yMaxInitialized } class Grid<X: Number, Y: Number>: MinMax<X, Y>() { lateinit var xOrigin: X val xOriginInitialized get() = this::xOrigin.isInitialized var xLines: ValueIterable<X> = ValueIterable.createStub() var xPainter: (Consumer<GridLine<X, Y, X>>) = Consumer { } lateinit var yOrigin: Y val yOriginInitialized get() = this::yOrigin.isInitialized var yLines: ValueIterable<Y> = ValueIterable.createStub() var yPainter: (Consumer<GridLine<X, Y, Y>>) = Consumer { } } class GridLine<X: Number, Y: Number, T: Number>(val value: T, @get:JvmName("getXY") val xy: MinMax<X, Y>, @MagicConstant val orientation: Int = SwingConstants.HORIZONTAL) { var paintLine = true var majorLine = false var label: String? = null @MagicConstant var horizontalAlignment = SwingConstants.CENTER @MagicConstant var verticalAlignment = SwingConstants.BOTTOM } abstract class ValueIterable<X: Number> : Iterable<X> { lateinit var min: X lateinit var max: X open fun prepare(min: X, max: X): ValueIterable<X> { this.min = min this.max = max return this } companion object { fun <T: Number> createStub(): ValueIterable<T> { return object: ValueIterable<T>() { val iter = object: Iterator<T> { override fun hasNext() = false override fun next(): T { error("not implemented") } } override fun iterator(): Iterator<T> = iter } } } }
apache-2.0
3483169406a0b1e5e6c29480ccddf7b3
31.487562
172
0.661689
3.788512
false
false
false
false
siosio/intellij-community
plugins/ide-features-trainer/src/training/actions/ChooseProgrammingLanguageForLearningAction.kt
2
2318
// 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 training.actions import com.intellij.lang.Language import com.intellij.lang.LanguageExtensionPoint import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.actionSystem.ex.ComboBoxAction import com.intellij.openapi.util.NlsSafe import training.lang.LangManager import training.lang.LangSupport import training.learn.LearnBundle import training.ui.LearnToolWindow import training.util.resetPrimaryLanguage import javax.swing.JComponent internal class ChooseProgrammingLanguageForLearningAction(private val learnToolWindow: LearnToolWindow) : ComboBoxAction() { override fun createPopupActionGroup(button: JComponent?): DefaultActionGroup { val allActionsGroup = DefaultActionGroup() val supportedLanguagesExtensions = LangManager.getInstance().supportedLanguagesExtensions.sortedBy { it.language } for (langSupportExt: LanguageExtensionPoint<LangSupport> in supportedLanguagesExtensions) { val languageId = langSupportExt.language val displayName = Language.findLanguageByID(languageId)?.displayName ?: continue allActionsGroup.add(SelectLanguageAction(languageId, displayName)) } return allActionsGroup } override fun update(e: AnActionEvent) { val langSupport = LangManager.getInstance().getLangSupport() if (langSupport != null) { e.presentation.text = getDisplayName(langSupport) } e.presentation.description = LearnBundle.message("learn.choose.language.description.combo.box") } private inner class SelectLanguageAction(private val languageId: String, @NlsSafe displayName: String) : AnAction(displayName) { override fun actionPerformed(e: AnActionEvent) { val ep = LangManager.getInstance().supportedLanguagesExtensions.singleOrNull { it.language == languageId } ?: return resetPrimaryLanguage(ep.instance) learnToolWindow.setModulesPanel() } } } @NlsSafe private fun getDisplayName(language: LangSupport) = Language.findLanguageByID(language.primaryLanguage)?.displayName ?: LearnBundle.message("unknown.language.name")
apache-2.0
aa959f5b3b121e6cf53e98b876d627c5
44.45098
140
0.80069
4.984946
false
false
false
false
JetBrains/kotlin-native
performance/ring/src/main/kotlin/org/jetbrains/ring/LambdaBenchmark.kt
4
2631
/* * 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.ring import org.jetbrains.benchmarksLauncher.Random var globalAddendum = 0 open class LambdaBenchmark { private inline fun <T> runLambda(x: () -> T): T = x() private fun <T> runLambdaNoInline(x: () -> T): T = x() init { globalAddendum = Random.nextInt(20) } //Benchmark fun noncapturingLambda(): Int { var x: Int = 0 for (i in 0..BENCHMARK_SIZE) { x += runLambda { globalAddendum } } return x } //Benchmark fun noncapturingLambdaNoInline(): Int { var x: Int = 0 for (i in 0..BENCHMARK_SIZE) { x += runLambdaNoInline { globalAddendum } } return x } //Benchmark fun capturingLambda(): Int { val addendum = globalAddendum + 1 var x: Int = 0 for (i in 0..BENCHMARK_SIZE) { x += runLambda { addendum } } return x } //Benchmark fun capturingLambdaNoInline(): Int { val addendum = globalAddendum + 1 var x: Int = 0 for (i in 0..BENCHMARK_SIZE) { x += runLambdaNoInline { addendum } } return x } //Benchmark fun mutatingLambda(): Int { var x: Int = 0 for (i in 0..BENCHMARK_SIZE) { runLambda { x += globalAddendum } } return x } //Benchmark fun mutatingLambdaNoInline(): Int { var x: Int = 0 for (i in 0..BENCHMARK_SIZE) { runLambdaNoInline { x += globalAddendum } } return x } //Benchmark fun methodReference(): Int { var x: Int = 0 for (i in 0..BENCHMARK_SIZE) { x += runLambda(::referenced) } return x } //Benchmark fun methodReferenceNoInline(): Int { var x: Int = 0 for (i in 0..BENCHMARK_SIZE) { x += runLambdaNoInline(::referenced) } return x } } private fun referenced(): Int { return globalAddendum }
apache-2.0
fa26e5ab0eb963e9555363448919f442
23.361111
75
0.570886
4.292007
false
false
false
false
SimpleMobileTools/Simple-Calendar
app/src/main/kotlin/com/simplemobiletools/calendar/pro/fragments/DayFragment.kt
1
5352
package com.simplemobiletools.calendar.pro.fragments import android.content.Intent import android.os.Bundle import android.os.Handler import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.RelativeLayout import androidx.fragment.app.Fragment import com.simplemobiletools.calendar.pro.R import com.simplemobiletools.calendar.pro.activities.MainActivity import com.simplemobiletools.calendar.pro.activities.SimpleActivity import com.simplemobiletools.calendar.pro.adapters.DayEventsAdapter import com.simplemobiletools.calendar.pro.extensions.config import com.simplemobiletools.calendar.pro.extensions.eventsHelper import com.simplemobiletools.calendar.pro.extensions.getViewBitmap import com.simplemobiletools.calendar.pro.extensions.printBitmap import com.simplemobiletools.calendar.pro.helpers.* import com.simplemobiletools.calendar.pro.interfaces.NavigationListener import com.simplemobiletools.calendar.pro.models.Event import com.simplemobiletools.commons.extensions.* import kotlinx.android.synthetic.main.fragment_day.view.* import kotlinx.android.synthetic.main.top_navigation.view.* class DayFragment : Fragment() { var mListener: NavigationListener? = null private var mTextColor = 0 private var mDayCode = "" private var lastHash = 0 private lateinit var mHolder: RelativeLayout override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_day, container, false) mHolder = view.day_holder mDayCode = requireArguments().getString(DAY_CODE)!! setupButtons() return view } override fun onResume() { super.onResume() updateCalendar() } private fun setupButtons() { mTextColor = requireContext().getProperTextColor() mHolder.top_left_arrow.apply { applyColorFilter(mTextColor) background = null setOnClickListener { mListener?.goLeft() } val pointerLeft = requireContext().getDrawable(R.drawable.ic_chevron_left_vector) pointerLeft?.isAutoMirrored = true setImageDrawable(pointerLeft) } mHolder.top_right_arrow.apply { applyColorFilter(mTextColor) background = null setOnClickListener { mListener?.goRight() } val pointerRight = requireContext().getDrawable(R.drawable.ic_chevron_right_vector) pointerRight?.isAutoMirrored = true setImageDrawable(pointerRight) } val day = Formatter.getDayTitle(requireContext(), mDayCode) mHolder.top_value.apply { text = day contentDescription = text setOnClickListener { (activity as MainActivity).showGoToDateDialog() } setTextColor(context.getProperTextColor()) } } fun updateCalendar() { val startTS = Formatter.getDayStartTS(mDayCode) val endTS = Formatter.getDayEndTS(mDayCode) context?.eventsHelper?.getEvents(startTS, endTS) { receivedEvents(it) } } private fun receivedEvents(events: List<Event>) { val newHash = events.hashCode() if (newHash == lastHash || !isAdded) { return } lastHash = newHash val replaceDescription = requireContext().config.replaceDescription val sorted = ArrayList(events.sortedWith(compareBy({ !it.getIsAllDay() }, { it.startTS }, { it.endTS }, { it.title }, { if (replaceDescription) it.location else it.description }))) activity?.runOnUiThread { updateEvents(sorted) } } private fun updateEvents(events: ArrayList<Event>) { if (activity == null) return DayEventsAdapter(activity as SimpleActivity, events, mHolder.day_events, mDayCode) { editEvent(it as Event) }.apply { mHolder.day_events.adapter = this } if (requireContext().areSystemAnimationsEnabled) { mHolder.day_events.scheduleLayoutAnimation() } } private fun editEvent(event: Event) { Intent(context, getActivityToOpen(event.isTask())).apply { putExtra(EVENT_ID, event.id) putExtra(EVENT_OCCURRENCE_TS, event.startTS) putExtra(IS_TASK_COMPLETED, event.isTaskCompleted()) startActivity(this) } } fun printCurrentView() { mHolder.apply { top_left_arrow.beGone() top_right_arrow.beGone() top_value.setTextColor(resources.getColor(R.color.theme_light_text_color)) (day_events.adapter as? DayEventsAdapter)?.togglePrintMode() Handler().postDelayed({ requireContext().printBitmap(day_holder.getViewBitmap()) Handler().postDelayed({ top_left_arrow.beVisible() top_right_arrow.beVisible() top_value.setTextColor(requireContext().getProperTextColor()) (day_events.adapter as? DayEventsAdapter)?.togglePrintMode() }, 1000) }, 1000) } } }
gpl-3.0
a1dc2409f5ccc55cf73169558ff719bb
33.753247
127
0.651906
4.98324
false
false
false
false
JetBrains/kotlin-native
runtime/src/main/kotlin/kotlin/sequences/Sequences.kt
4
721
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package kotlin.sequences import kotlin.comparisons.* import kotlin.native.internal.FixmeConcurrency @FixmeConcurrency internal actual class ConstrainedOnceSequence<T> actual constructor(sequence: Sequence<T>) : Sequence<T> { // TODO: not MT friendly. private var sequenceRef : Sequence<T>? = sequence override actual fun iterator(): Iterator<T> { val sequence = sequenceRef if (sequence == null) throw IllegalStateException("This sequence can be consumed only once.") sequenceRef = null return sequence.iterator() } }
apache-2.0
57de55fcea98802d3bb6a1c1c30329a2
31.772727
106
0.718447
4.317365
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/inlineMultiFile/fromJavaToKotlin/complexJavaToKotlin2/after/usage/main.kt
12
11098
package usage import javapackage.one.JavaClassOne import javapackage.one.JavaClassOne.MAGIC_CONST import javapackage.one.JavaClassOne.build class KotlinClassOne { fun update(javaClassOne: JavaClassOne) { } } class KotlinClassTwo fun usage() { val javaClass = JavaClassOne() // expect "val two = KotlinClassTwo()" after kotlinClassOne, KT-40867 val kotlinClassOne = KotlinClassOne() val kotlinOther = KotlinClassOne() kotlinClassOne.update(javaClass) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(KotlinClassTwo()) println(kotlinClassOne) System.err.println(result) build(result.convertToInt() + javaClass.hashCode() + javaClass.convertToInt() + MAGIC_CONST + build(javaClass.field).field) } val kotlinOne = KotlinClassOne() val kotlinTwo = KotlinClassTwo() fun a() { val javaClassOne = JavaClassOne() val kotlinOther = KotlinClassOne() kotlinOne.update(javaClassOne) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build( result.convertToInt() + javaClassOne.hashCode() + javaClassOne.convertToInt() + MAGIC_CONST + build( javaClassOne.field ).field ) val d = JavaClassOne() val kotlinOther = KotlinClassOne() kotlinOne.update(d) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + d.hashCode() + d.convertToInt() + MAGIC_CONST + build(d.field).field) d.let { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) } d.also { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) } with(d) { val kotlinOther = KotlinClassOne() kotlinOne.update(this) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + hashCode() + convertToInt() + MAGIC_CONST + build(field).field) } with(d) out@{ with(4) { val kotlinOther = KotlinClassOne() kotlinOne.update(this@out) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + [email protected]() + [email protected]() + MAGIC_CONST + build([email protected]).field) } } } fun a2() { val d: JavaClassOne? = null if (d != null) { val kotlinOther = KotlinClassOne() kotlinOne.update(d) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + d.hashCode() + d.convertToInt() + MAGIC_CONST + build(d.field).field) } d?.let { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) } d?.also { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) } with(d) { this?.let { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) } } with(d) out@{ with(4) { this@out?.let { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) } } } } fun a3() { val d: JavaClassOne? = null val a1 = d?.let { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) } val a2 = d?.let { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) } val a3 = d?.also { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) } val a4 = with(d) { this?.let { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) } } val a5 = with(d) out@{ with(4) { this@out?.let { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) } } } } fun a4() { val d: JavaClassOne? = null d?.let { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) }?.convertToInt()?.dec() val a2 = d?.let { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) } a2?.convertToInt()?.toLong() val also = d?.also { it.apply(kotlinOne, kotlinTwo) } if (also != null) { val kotlinOther = KotlinClassOne() kotlinOne.update(also) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + also.hashCode() + also.convertToInt() + MAGIC_CONST + build(also.field).field) } val a4 = with(d) { this?.let { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) } }?.convertToInt() val a5 = with(d) out@{ with(4) { this@out?.let { val kotlinOther = KotlinClassOne() kotlinOne.update(it) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) build(result.convertToInt() + it.hashCode() + it.convertToInt() + MAGIC_CONST + build(it.field).field) } } }?.convertToInt() val a6 = a4?.let { out -> a5?.let { out + it } } } fun JavaClassOne.b(): Int? { val kotlinOther = KotlinClassOne() kotlinOne.update(this) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) return build(result.convertToInt() + hashCode() + convertToInt() + MAGIC_CONST + build(field).field).convertToInt() } fun JavaClassOne.c(): Int { val kotlinOther = KotlinClassOne() kotlinOne.update(this) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) return build(result.convertToInt() + this.hashCode() + this.convertToInt() + MAGIC_CONST + build(this.field).field).convertToInt() } fun d(d: JavaClassOne): Int { val kotlinOther = KotlinClassOne() kotlinOne.update(d) val result = build(kotlinOther.hashCode()) kotlinOther.update(result) println(kotlinTwo) println(kotlinOne) System.err.println(result) return build(result.convertToInt() + d.hashCode() + d.convertToInt() + MAGIC_CONST + build(d.field).field).convertToInt() }
apache-2.0
d842bc9f21c1e86f76aff25b80b7bc5c
32.630303
134
0.608848
4.395248
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/decompiler/classFile/DeserializerForClassfileDecompiler.kt
2
7473
// 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.classFile import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.kotlin.builtins.DefaultBuiltIns import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.contracts.ContractDeserializerImpl import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.NotFoundClasses import org.jetbrains.kotlin.idea.caches.IDEKotlinBinaryClassCache import org.jetbrains.kotlin.idea.decompiler.textBuilder.DeserializerForDecompilerBase import org.jetbrains.kotlin.idea.decompiler.textBuilder.LoggingErrorReporter import org.jetbrains.kotlin.idea.decompiler.textBuilder.ResolveEverythingToKotlinAnyLocalClassifierResolver import org.jetbrains.kotlin.incremental.components.LookupTracker import org.jetbrains.kotlin.load.java.structure.JavaClass import org.jetbrains.kotlin.load.java.structure.classId import org.jetbrains.kotlin.load.kotlin.* import org.jetbrains.kotlin.load.kotlin.KotlinClassFinder.Result.KotlinClass import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmProtoBufUtil import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.resolve.sam.SamConversionResolverImpl import org.jetbrains.kotlin.serialization.deserialization.ClassData import org.jetbrains.kotlin.serialization.deserialization.ClassDataFinder import org.jetbrains.kotlin.serialization.deserialization.DeserializationComponents import org.jetbrains.kotlin.serialization.deserialization.DeserializationConfiguration import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedPackageMemberScope import java.io.InputStream fun DeserializerForClassfileDecompiler(classFile: VirtualFile): DeserializerForClassfileDecompiler { val kotlinClassHeaderInfo = IDEKotlinBinaryClassCache.getInstance().getKotlinBinaryClassHeaderData(classFile) ?: error("Decompiled data factory shouldn't be called on an unsupported file: $classFile") val packageFqName = kotlinClassHeaderInfo.classId.packageFqName return DeserializerForClassfileDecompiler(classFile.parent!!, packageFqName) } class DeserializerForClassfileDecompiler( packageDirectory: VirtualFile, directoryPackageFqName: FqName ) : DeserializerForDecompilerBase(directoryPackageFqName) { override val builtIns: KotlinBuiltIns get() = DefaultBuiltIns.Instance private val classFinder = DirectoryBasedClassFinder(packageDirectory, directoryPackageFqName) override val deserializationComponents: DeserializationComponents init { val classDataFinder = DirectoryBasedDataFinder(classFinder, LOG) val notFoundClasses = NotFoundClasses(storageManager, moduleDescriptor) val annotationAndConstantLoader = BinaryClassAnnotationAndConstantLoaderImpl(moduleDescriptor, notFoundClasses, storageManager, classFinder) val configuration = object : DeserializationConfiguration { override val readDeserializedContracts: Boolean = true override val preserveDeclarationsOrdering: Boolean = true } deserializationComponents = DeserializationComponents( storageManager, moduleDescriptor, configuration, classDataFinder, annotationAndConstantLoader, packageFragmentProvider, ResolveEverythingToKotlinAnyLocalClassifierResolver(builtIns), LoggingErrorReporter(LOG), LookupTracker.DO_NOTHING, JavaFlexibleTypeDeserializer, emptyList(), notFoundClasses, ContractDeserializerImpl(configuration, storageManager), extensionRegistryLite = JvmProtoBufUtil.EXTENSION_REGISTRY, samConversionResolver = SamConversionResolverImpl(storageManager, samWithReceiverResolvers = emptyList()) ) } override fun resolveDeclarationsInFacade(facadeFqName: FqName): List<DeclarationDescriptor> { val packageFqName = facadeFqName.parent() assert(packageFqName == directoryPackageFqName) { "Was called for $facadeFqName; only members of $directoryPackageFqName package are expected." } val binaryClassForPackageClass = classFinder.findKotlinClass(ClassId.topLevel(facadeFqName)) val header = binaryClassForPackageClass?.classHeader val annotationData = header?.data val strings = header?.strings if (annotationData == null || strings == null) { LOG.error("Could not read annotation data for $facadeFqName from ${binaryClassForPackageClass?.classId}") return emptyList() } val (nameResolver, packageProto) = JvmProtoBufUtil.readPackageDataFrom(annotationData, strings) val membersScope = DeserializedPackageMemberScope( createDummyPackageFragment(header.packageName?.let(::FqName) ?: facadeFqName.parent()), packageProto, nameResolver, header.metadataVersion, JvmPackagePartSource(binaryClassForPackageClass, packageProto, nameResolver), deserializationComponents ) { emptyList() } return membersScope.getContributedDescriptors().toList() } companion object { private val LOG = Logger.getInstance(DeserializerForClassfileDecompiler::class.java) } } class DirectoryBasedClassFinder( val packageDirectory: VirtualFile, val directoryPackageFqName: FqName ) : KotlinClassFinder { override fun findKotlinClassOrContent(javaClass: JavaClass) = findKotlinClassOrContent(javaClass.classId!!) override fun findKotlinClassOrContent(classId: ClassId): KotlinClassFinder.Result? { if (classId.packageFqName != directoryPackageFqName) { return null } val targetName = classId.relativeClassName.pathSegments().joinToString("$", postfix = ".class") val virtualFile = packageDirectory.findChild(targetName) if (virtualFile != null && isKotlinWithCompatibleAbiVersion(virtualFile)) { return IDEKotlinBinaryClassCache.getInstance().getKotlinBinaryClass(virtualFile)?.let(::KotlinClass) } return null } // TODO override fun findMetadata(classId: ClassId): InputStream? = null // TODO override fun hasMetadataPackage(fqName: FqName): Boolean = false // TODO: load built-ins from packageDirectory? override fun findBuiltInsData(packageFqName: FqName): InputStream? = null } class DirectoryBasedDataFinder( val classFinder: DirectoryBasedClassFinder, val log: Logger ) : ClassDataFinder { override fun findClassData(classId: ClassId): ClassData? { val binaryClass = classFinder.findKotlinClass(classId) ?: return null val classHeader = binaryClass.classHeader val data = classHeader.data if (data == null) { log.error("Annotation data missing for ${binaryClass.classId}") return null } val strings = classHeader.strings if (strings == null) { log.error("String table not found in class ${binaryClass.classId}") return null } val (nameResolver, classProto) = JvmProtoBufUtil.readClassDataFrom(data, strings) return ClassData(nameResolver, classProto, classHeader.metadataVersion, KotlinJvmBinarySourceElement(binaryClass)) } }
apache-2.0
db0383d46773256c79f04c928418e7fc
49.836735
158
0.769169
5.502946
false
false
false
false
tlaukkan/kotlin-web-vr
client/src/lib/threejs/Core.kt
1
3625
package lib.threejs @native("THREE.Geometry") open class Geometry { //Properties @native var id: Int = noImpl @native var name: String = noImpl @native var vertices: Array<Vector3> = noImpl @native var colors: Array<Color> = noImpl //@native var faces: Array<Triangle> = noImpl //@native var faceVertexUvs: Array<UV> = noImpl //@native var morphTargets: Vector3 = noImpl //@native var morphColors: Vector3 = noImpl //@native var morphNormals: Vector3 = noImpl @native var skinWeights: Vector3 = noImpl @native var skinIndices: Vector3 = noImpl //@native var boundingBox: Vector3 = noImpl @native var boundingSphere: Double = noImpl @native var hasTangents: Boolean = noImpl @native var dynamic: Boolean = noImpl @native var verticesNeedUpdate: Boolean = noImpl @native var elementsNeedUpdate: Boolean = noImpl @native var uvsNeedUpdate: Boolean = noImpl @native var normalsNeedUpdate: Boolean = noImpl @native var tangentsNeedUpdate: Boolean = noImpl @native var colorsNeedUpdate: Boolean = noImpl @native var lineDistancesNeedUpdate: Boolean = noImpl @native var buffersNeedUpdate: Boolean = noImpl @native var lineDistances: Array<Double> = noImpl //Functions fun applyMatrix(m: Matrix4): Unit = noImpl fun computeFaceNormals(): Unit = noImpl fun computeVertexNormals(): Unit = noImpl fun computeMorphNormals(): Unit = noImpl fun computeTangents(): Unit = noImpl fun computeBoundingBox(): Unit = noImpl fun computeBoundingSphere(): Unit = noImpl fun merge(geometry: Geometry, m: Matrix4, materialIndexOffset: Int): Unit = noImpl fun mergeVertices(): Unit = noImpl fun makeGroups(m: Matrix4): Unit = noImpl fun clone(m: Matrix4): Unit = noImpl fun dispose(m: Matrix4): Unit = noImpl fun computeLineDistances(m: Matrix4): Unit = noImpl } @native("THREE.PlaneGeometry") open class PlaneGeometry(width: Double, height: Double) : Geometry() { } @native("THREE.Object3D") open class Object3D( @native var parent: Object3D = noImpl, @native var children: Array<Object3D> = noImpl, @native var position: Vector3 = noImpl, @native var rotation: Euler = noImpl, @native var scale: Vector3 = noImpl ) { @native var castShadow: Boolean = noImpl @native var receiveShadow: Boolean = noImpl @native var shadow: dynamic = noImpl @native var int: Int = noImpl @native var uuid: String = noImpl @native var name: String = noImpl @native var matrix: Matrix4 = noImpl @native var matrixWorld: Matrix4 = noImpl @native var quaternion: Quaternion = noImpl @native var matrixAutoUpdate: Boolean = noImpl @native var matrixWorldNeedsUpdate: Boolean = noImpl @native var material: Material = noImpl @native var visible: Boolean //Functions fun add(obj: Object3D): Unit = noImpl fun remove(obj: Object3D): Unit = noImpl @native fun rotateX(radians: Double): Unit = noImpl @native fun rotateY(radians: Double): Unit = noImpl @native fun rotateZ(radians: Double): Unit = noImpl @native fun updateMatrix(): Unit = noImpl @native fun updateMatrixWorld(): Unit = noImpl @native fun translateOnAxis(axis: Vector3, distance: Number): Object3D = noImpl @native fun applyMatrix(matrix: Matrix4): Unit = noImpl @native fun getWorldPosition(optionalTarget: Vector3): Vector3 = noImpl @native fun getWorldQuaternion(optionalTarget: Quaternion): Quaternion = noImpl @native fun getWorldRotation(optionalTarget: Quaternion): Quaternion = noImpl @native open fun clone(recursive: Boolean): Object3D = noImpl } @native("THREE.Group") open class Group() : Object3D() { }
mit
505ab217e3203dcddb3f972bc524b843
29.216667
84
0.726621
4.045759
false
false
false
false
joaomneto/TitanCompanion
src/test/java/pt/joaomneto/titancompanion/adventure/AdventureNotesTest.kt
1
2122
package pt.joaomneto.titancompanion.adventure import android.app.AlertDialog import android.content.DialogInterface import android.widget.Button import android.widget.EditText import android.widget.ListView import org.junit.Assert.assertTrue import org.junit.Test import org.robolectric.Shadows import org.robolectric.shadows.ShadowDialog import pt.joaomneto.titancompanion.R import pt.joaomneto.titancompanion.adventure.impl.fragments.AdventureNotesFragment import java.util.Properties import kotlin.reflect.KClass abstract class AdventureNotesTest<T : Adventure, U : AdventureNotesFragment>( adventureClass: KClass<T>, fragmentClass: KClass<U>, savegame: Properties ) : TCAdventureBaseTest<T, U>( adventureClass, fragmentClass, savegame ) { @Test fun `when clicking the add note button it adds an note to the list via a dialog`() { loadActivity() fragment.findComponent<Button>(R.id.buttonAddNote).performClick() val dialog = ShadowDialog.getLatestDialog() as AlertDialog val inputField = dialog.findViewById<EditText>(R.id.alert_editText_field) inputField.setText("n1") dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick() val listView = fragment.findComponent<ListView>(R.id.noteList) val shadowListView = Shadows.shadowOf(listView) assertTrue(shadowListView.findIndexOfItemContainingText("n1") >= 0) } @Test fun `when long pressing an note item it removes an item from the list via a confirmation dialog`() { loadActivity("notes" to "n1#n2") val listView = fragment.findComponent<ListView>(R.id.noteList) val shadowListView = Shadows.shadowOf(listView) listView.onItemLongClickListener.onItemLongClick( null, null, shadowListView.findIndexOfItemContainingText("n1"), -1 ) val dialog = ShadowDialog.getLatestDialog() as AlertDialog dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick() assertTrue(shadowListView.findIndexOfItemContainingText("n1") < 0) } }
lgpl-3.0
82d2308d68a0dbe5df3521c20a5bf82a
32.68254
104
0.730914
4.653509
false
true
false
false
sky-map-team/stardroid
app/src/main/java/com/google/android/stardroid/ephemeris/SolarSystemRenderable.kt
1
5983
// Copyright 2010 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.stardroid.ephemeris import android.content.SharedPreferences import android.content.res.Resources import android.graphics.Color import com.google.android.stardroid.base.Lists import com.google.android.stardroid.control.AstronomerModel import com.google.android.stardroid.math.Vector3 import com.google.android.stardroid.math.heliocentricCoordinatesFromOrbitalElements import com.google.android.stardroid.math.updateFromRaDec import com.google.android.stardroid.renderables.* import com.google.android.stardroid.renderer.RendererObjectManager.UpdateType import com.google.android.stardroid.space.SolarSystemObject import com.google.android.stardroid.space.Universe import java.util.* /** * Implementation of the * [AstronomicalRenderable] for planets. * * @author Brent Bryan */ class SolarSystemRenderable( private val solarSystemBody: SolarSystemBody, resources: Resources, model: AstronomerModel, prefs: SharedPreferences ) : AbstractAstronomicalRenderable() { private val pointPrimitives = ArrayList<PointPrimitive>() private val imagePrimitives = ArrayList<ImagePrimitive>() private val labelPrimitives = ArrayList<TextPrimitive>() private val resources: Resources private val model: AstronomerModel private val name: String private val preferences: SharedPreferences private val currentCoords = Vector3(0f, 0f, 0f) private val solarSystemObject: SolarSystemObject private var earthCoords: Vector3 private var imageId = -1 private var lastUpdateTimeMs = 0L private val universe = Universe() override val names: List<String> get() = Lists.asList(name) override val searchLocation: Vector3 get() = currentCoords private fun updateCoords(time: Date) { lastUpdateTimeMs = time.time // TODO(johntaylor): figure out why we do this - presumably to make sure the images // are orientated correctly taking into account the Earth's orbital plane. // I'm not sure we're doing this right though. earthCoords = heliocentricCoordinatesFromOrbitalElements(SolarSystemBody.Earth.getOrbitalElements(time)) currentCoords.updateFromRaDec(universe.getRaDec(solarSystemBody, time)) for (imagePrimitives in imagePrimitives) { imagePrimitives.setUpVector(earthCoords) } } override fun initialize(): Renderable { val time = model.time updateCoords(time) imageId = solarSystemObject.getImageResourceId(time) if (solarSystemBody === SolarSystemBody.Moon) { imagePrimitives.add( ImagePrimitive( currentCoords, resources, imageId, earthCoords, solarSystemObject.getPlanetaryImageSize() ) ) } else { val usePlanetaryImages = preferences.getBoolean(SHOW_PLANETARY_IMAGES, true) if (usePlanetaryImages || solarSystemBody === SolarSystemBody.Sun) { imagePrimitives.add( ImagePrimitive( currentCoords, resources, imageId, UP, solarSystemObject.getPlanetaryImageSize() ) ) } else { pointPrimitives.add(PointPrimitive(currentCoords, PLANET_COLOR, PLANET_SIZE)) } } labelPrimitives.add(TextPrimitive(currentCoords, name, PLANET_LABEL_COLOR)) return this } override fun update(): EnumSet<UpdateType> { val updates = EnumSet.noneOf(UpdateType::class.java) val modelTime = model.time if (Math.abs(modelTime.time - lastUpdateTimeMs) > solarSystemObject.getUpdateFrequencyMs()) { updates.add(UpdateType.UpdatePositions) // update location updateCoords(modelTime) // For moon only: if (solarSystemBody === SolarSystemBody.Moon && !imagePrimitives.isEmpty()) { // Update up vector. imagePrimitives[0].setUpVector(earthCoords) // update image: val newImageId = solarSystemObject.getImageResourceId(modelTime) if (newImageId != imageId) { imageId = newImageId imagePrimitives[0].setImageId(imageId) updates.add(UpdateType.UpdateImages) } } } return updates } override val images: List<ImagePrimitive> get() = imagePrimitives override val labels: List<TextPrimitive> get() = labelPrimitives override val points: List<PointPrimitive> get() = pointPrimitives companion object { private const val PLANET_SIZE = 3 private val PLANET_COLOR = Color.argb(20, 129, 126, 246) private const val PLANET_LABEL_COLOR = 0xf67e81 private const val SHOW_PLANETARY_IMAGES = "show_planetary_images" private val UP = Vector3(0.0f, 1.0f, 0.0f) } init { solarSystemObject = universe.solarSystemObjectFor(solarSystemBody) this.resources = resources this.model = model name = resources.getString(solarSystemObject.getNameResourceId()) preferences = prefs earthCoords = heliocentricCoordinatesFromOrbitalElements( SolarSystemBody.Earth.getOrbitalElements(model.time)) } }
apache-2.0
cc448772c6d2b2b0fac10fbf9468f130
39.707483
112
0.677252
4.813355
false
false
false
false
vector-im/vector-android
vector/src/main/java/im/vector/util/BitmapUtil.kt
2
2578
/* * Copyright 2018 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.util import android.graphics.Bitmap import android.graphics.Canvas import org.matrix.androidsdk.core.Log private const val LOG_TAG = "BitmapUtil" /** * Create a centered square bitmap from another one. * * if height == width * +-------+ * |XXXXXXX| * |XXXXXXX| * |XXXXXXX| * +-------+ * * if width > height * +------+-------+------+ * | |XXXXXXX| | * | |XXXXXXX| | * | |XXXXXXX| | * +------+-------+------+ * * if height > width * +-------+ * | | * | | * +-------+ * |XXXXXXX| * |XXXXXXX| * |XXXXXXX| * +-------+ * | | * | | * +-------+ * * @param bitmap the bitmap to "square" * @return the squared bitmap */ fun Bitmap.createSquareBitmap(): Bitmap = when { width == height -> this width > height -> try { // larger than high Bitmap.createBitmap(this, (width - height) / 2, 0, height, height) } catch (e: Exception) { Log.e(LOG_TAG, "## createSquareBitmap " + e.message, e) this } else -> try { // higher than large Bitmap.createBitmap(this, 0, (height - width) / 2, width, width) } catch (e: Exception) { Log.e(LOG_TAG, "## createSquareBitmap " + e.message, e) this } } /** * Add a background color to the Bitmap */ fun Bitmap.addBackgroundColor(backgroundColor: Int): Bitmap { // Create new bitmap based on the size and config of the old val newBitmap = Bitmap.createBitmap(width, height, config ?: Bitmap.Config.ARGB_8888) // Reported by the Play Store if (newBitmap == null) { Log.e(LOG_TAG, "## unable to add background color") return this } Canvas(newBitmap).let { // Paint background it.drawColor(backgroundColor) // Draw the old bitmap on top of the new background it.drawBitmap(this, 0f, 0f, null) } return newBitmap }
apache-2.0
bf4916d26f6a7c78acd5d68ae4a336f1
24.534653
89
0.577967
3.89426
false
false
false
false
filipproch/reactor-android
library/src/test/java/cz/filipproch/reactor/util/FakeReactorView.kt
1
1909
package cz.filipproch.reactor.util import cz.filipproch.reactor.base.translator.SimpleTranslatorFactory import cz.filipproch.reactor.base.translator.TranslatorFactory import cz.filipproch.reactor.base.view.ReactorUiAction import cz.filipproch.reactor.base.view.ReactorUiEvent import cz.filipproch.reactor.base.view.ReactorUiModel import cz.filipproch.reactor.base.view.ReactorView import io.reactivex.Observable import io.reactivex.functions.Consumer /** * TODO * * @author Filip Prochazka (@filipproch) */ class FakeReactorView : ReactorView<TestTranslator> { var onEmittersInitCalled = false var onConnectModelChannelCalled = false var onConnectModelStreamCalled = false var onConnectActionChannelCalled = false var onConnectActionStreamCalled = false var registerEmitterExecutions = 0 var dispatchExecutions = 0 var consumeOnUiExecutions = 0 private var onEmittersInitCallback: (() -> Unit)? = null override val translatorFactory: TranslatorFactory<TestTranslator> get() = SimpleTranslatorFactory(TestTranslator::class.java) override fun onEmittersInit() { onEmittersInitCalled = true onEmittersInitCallback?.invoke() } override fun onConnectModelStream(modelStream: Observable<out ReactorUiModel>) { onConnectModelStreamCalled = true } override fun onConnectActionStream(actionStream: Observable<out ReactorUiAction>) { onConnectActionStreamCalled = true } override fun registerEmitter(emitter: Observable<out ReactorUiEvent>) { registerEmitterExecutions++ } override fun dispatch(event: ReactorUiEvent) { dispatchExecutions++ } override fun <T> Observable<T>.consumeOnUi(receiverAction: Consumer<T>) { consumeOnUiExecutions++ } fun setOnEmittersInitCallback(callback: () -> Unit) { onEmittersInitCallback = callback } }
mit
e5248c1ba256550f532949bf5d6c7a24
29.806452
87
0.751179
5.023684
false
false
false
false
koma-im/koma
src/main/kotlin/link/continuum/desktop/gui/icon/avatar/url.kt
1
2362
package link.continuum.desktop.gui.icon.avatar import javafx.scene.layout.Region import javafx.scene.paint.Color import koma.Server import koma.network.media.MHUrl import kotlinx.coroutines.MainScope import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import link.continuum.desktop.gui.StackPane import link.continuum.desktop.gui.StyleBuilder import link.continuum.desktop.gui.add import link.continuum.desktop.gui.component.FitImageRegion import link.continuum.desktop.gui.em import link.continuum.desktop.util.debugAssertUiThread import mu.KotlinLogging private val logger = KotlinLogging.logger {} abstract class UrlAvatar( ) { private val scope = MainScope() val root: Region = object :StackPane() { // roughly aligned with text vertically override fun getBaselineOffset(): Double = height * 0.75 } val initialIcon = InitialIcon() val imageView = FitImageRegion() init { imageView.imageProperty.onEach { val noImage = it == null initialIcon.root.apply { isVisible = noImage isManaged = noImage } }.launchIn(scope) root as StackPane root.add(initialIcon.root) root.add(imageView) } @Deprecated("") fun updateName(name: String, color: Color) { debugAssertUiThread() this.initialIcon.updateItem(name, color) } /** * null url clears the image */ fun updateUrl(url: MHUrl?, server: Server) { imageView.setMxc(url, server) } fun cancelScope() { scope.cancel() } companion object { } } /** * width and height are about two lines */ class Avatar2L: UrlAvatar() { init { root as StackPane root.style = rootStyle } companion object { private val rootStyle = StyleBuilder { fixHeight(2.2.em) fixWidth(2.2.em) }.toStyle() private val clipStyle = StyleBuilder { } } } /** * width and height are about two lines */ class AvatarInline: UrlAvatar() { init { root as StackPane root.style = rootStyle } companion object { private val rootStyle = StyleBuilder { fixHeight(1.em) fixWidth(1.em) }.toStyle() } }
gpl-3.0
1e383b34de4e2d2289d7a256e54acbf0
22.868687
64
0.640559
4.195382
false
false
false
false
android/uamp
common/src/main/java/com/example/android/uamp/media/library/BrowseTree.kt
3
6720
/* * Copyright 2019 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.uamp.media.library import android.content.Context import android.support.v4.media.MediaBrowserCompat import android.support.v4.media.MediaBrowserCompat.MediaItem import android.support.v4.media.MediaMetadataCompat import com.example.android.uamp.media.MusicService import com.example.android.uamp.media.R import com.example.android.uamp.media.extensions.album import com.example.android.uamp.media.extensions.albumArt import com.example.android.uamp.media.extensions.albumArtUri import com.example.android.uamp.media.extensions.artist import com.example.android.uamp.media.extensions.flag import com.example.android.uamp.media.extensions.id import com.example.android.uamp.media.extensions.title import com.example.android.uamp.media.extensions.trackNumber import com.example.android.uamp.media.extensions.urlEncoded /** * Represents a tree of media that's used by [MusicService.onLoadChildren]. * * [BrowseTree] maps a media id (see: [MediaMetadataCompat.METADATA_KEY_MEDIA_ID]) to one (or * more) [MediaMetadataCompat] objects, which are children of that media id. * * For example, given the following conceptual tree: * root * +-- Albums * | +-- Album_A * | | +-- Song_1 * | | +-- Song_2 * ... * +-- Artists * ... * * Requesting `browseTree["root"]` would return a list that included "Albums", "Artists", and * any other direct children. Taking the media ID of "Albums" ("Albums" in this example), * `browseTree["Albums"]` would return a single item list "Album_A", and, finally, * `browseTree["Album_A"]` would return "Song_1" and "Song_2". Since those are leaf nodes, * requesting `browseTree["Song_1"]` would return null (there aren't any children of it). */ class BrowseTree( val context: Context, musicSource: MusicSource, val recentMediaId: String? = null ) { private val mediaIdToChildren = mutableMapOf<String, MutableList<MediaMetadataCompat>>() /** * Whether to allow clients which are unknown (not on the allowed list) to use search on this * [BrowseTree]. */ val searchableByUnknownCaller = true /** * In this example, there's a single root node (identified by the constant * [UAMP_BROWSABLE_ROOT]). The root's children are each album included in the * [MusicSource], and the children of each album are the songs on that album. * (See [BrowseTree.buildAlbumRoot] for more details.) * * TODO: Expand to allow more browsing types. */ init { val rootList = mediaIdToChildren[UAMP_BROWSABLE_ROOT] ?: mutableListOf() val recommendedMetadata = MediaMetadataCompat.Builder().apply { id = UAMP_RECOMMENDED_ROOT title = context.getString(R.string.recommended_title) albumArtUri = RESOURCE_ROOT_URI + context.resources.getResourceEntryName(R.drawable.ic_recommended) flag = MediaBrowserCompat.MediaItem.FLAG_BROWSABLE }.build() val albumsMetadata = MediaMetadataCompat.Builder().apply { id = UAMP_ALBUMS_ROOT title = context.getString(R.string.albums_title) albumArtUri = RESOURCE_ROOT_URI + context.resources.getResourceEntryName(R.drawable.ic_album) flag = MediaBrowserCompat.MediaItem.FLAG_BROWSABLE }.build() rootList += recommendedMetadata rootList += albumsMetadata mediaIdToChildren[UAMP_BROWSABLE_ROOT] = rootList musicSource.forEach { mediaItem -> val albumMediaId = mediaItem.album.urlEncoded val albumChildren = mediaIdToChildren[albumMediaId] ?: buildAlbumRoot(mediaItem) albumChildren += mediaItem // Add the first track of each album to the 'Recommended' category if (mediaItem.trackNumber == 1L) { val recommendedChildren = mediaIdToChildren[UAMP_RECOMMENDED_ROOT] ?: mutableListOf() recommendedChildren += mediaItem mediaIdToChildren[UAMP_RECOMMENDED_ROOT] = recommendedChildren } // If this was recently played, add it to the recent root. if (mediaItem.id == recentMediaId) { mediaIdToChildren[UAMP_RECENT_ROOT] = mutableListOf(mediaItem) } } } /** * Provide access to the list of children with the `get` operator. * i.e.: `browseTree\[UAMP_BROWSABLE_ROOT\]` */ operator fun get(mediaId: String) = mediaIdToChildren[mediaId] /** * Builds a node, under the root, that represents an album, given * a [MediaMetadataCompat] object that's one of the songs on that album, * marking the item as [MediaItem.FLAG_BROWSABLE], since it will have child * node(s) AKA at least 1 song. */ private fun buildAlbumRoot(mediaItem: MediaMetadataCompat): MutableList<MediaMetadataCompat> { val albumMetadata = MediaMetadataCompat.Builder().apply { id = mediaItem.album.urlEncoded title = mediaItem.album artist = mediaItem.artist albumArt = mediaItem.albumArt albumArtUri = mediaItem.albumArtUri.toString() flag = MediaItem.FLAG_BROWSABLE }.build() // Adds this album to the 'Albums' category. val rootList = mediaIdToChildren[UAMP_ALBUMS_ROOT] ?: mutableListOf() rootList += albumMetadata mediaIdToChildren[UAMP_ALBUMS_ROOT] = rootList // Insert the album's root with an empty list for its children, and return the list. return mutableListOf<MediaMetadataCompat>().also { mediaIdToChildren[albumMetadata.id!!] = it } } } const val UAMP_BROWSABLE_ROOT = "/" const val UAMP_EMPTY_ROOT = "@empty@" const val UAMP_RECOMMENDED_ROOT = "__RECOMMENDED__" const val UAMP_ALBUMS_ROOT = "__ALBUMS__" const val UAMP_RECENT_ROOT = "__RECENT__" const val MEDIA_SEARCH_SUPPORTED = "android.media.browse.SEARCH_SUPPORTED" const val RESOURCE_ROOT_URI = "android.resource://com.example.android.uamp.next/drawable/"
apache-2.0
5db917f6ef0dfe05a5a1d51c52fb382c
40.226994
98
0.682589
4.474035
false
false
false
false
Litote/kmongo
kmongo-reactor-core-tests/src/main/kotlin/org/litote/kmongo/reactor/CommandTest.kt
1
2745
/* * Copyright (C) 2016/2022 Litote * * 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.litote.kmongo.reactor import kotlinx.serialization.Serializable import org.bson.Document import org.junit.Test import org.litote.kmongo.model.Friend import org.litote.kmongo.oldestMongoTestVersion import kotlin.test.assertEquals import kotlin.test.assertTrue /** * */ class CommandTest : KMongoReactorBaseTest<Friend>(oldestMongoTestVersion) { @Serializable class LocationResult(val results: List<Location>) @Serializable class Location(var dis: Double = 0.toDouble(), var obj: NestedLocation? = null) { val name: String get() = obj?.name ?: "" } @Serializable class NestedLocation(var name: String? = null) @Test fun canRunACommand() { val document = database.runCommand<Document>("{ ping: 1 }").block() ?: throw AssertionError("Document must not null!") assertEquals(1.0, document["ok"]) } @Test fun canRunACommandWithParameter() { col.insertOne("{test:1}").block() val friends = "friend" val document = database.runCommand<Document>("{ count: '$friends' }").block() ?: throw AssertionError("Document must not null!") assertEquals(1, document["n"]) } @Test fun canRunAGeoNearCommand() { col.createIndex("{loc:'2d'}").block() col.insertOne("{loc:{lat:48.690833,lng:9.140556}, name:'Paris'}").block() val document = database.runCommand<LocationResult>( "{ geoNear : 'friend', near : [48.690,9.140], spherical: true}" ).block() ?: throw AssertionError("Document must not null!") val locations = document.results assertEquals(1, locations.size) assertEquals(1.732642945641585E-5, locations.first().dis) assertEquals("Paris", locations.first().name) } @Test fun canRunAnEmptyResultCommand() { col.createIndex("{loc:'2d'}").block() val document = database.runCommand<LocationResult>( "{ geoNear : 'friend', near : [48.690,9.140], spherical: true}" ).block() ?: throw AssertionError("Document must not null!") assertTrue(document.results.isEmpty()) } }
apache-2.0
b258c74975dd15cba5adef27a825ff1e
31.294118
136
0.665209
4.152799
false
true
false
false