repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
53 values
size
stringlengths
2
6
content
stringlengths
73
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
977
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Dr-Horv/Advent-of-Code-2017
src/main/kotlin/solutions/day03/Day3.kt
1
4840
package solutions.day03 import solutions.Solver import utils.Coordinate import utils.Direction import utils.step data class Cursor(var x: Int, var y:Int) fun Cursor.manhattanDistance() : Int = Math.abs(x) + Math.abs(y) data class CircleInfo(val circle: Int, val numbers: Int) class Day3: Solver { override fun solve(input: List<String>, partTwo: Boolean): String { val target = input.first().toInt() if(target == 1) { return 0.toString() } if(partTwo) { return doPartTwo(target) } val circleInfo = determineCircle(target) val number = circleInfo.numbers + (circleInfo.circle-2) val cursor = Cursor(circleInfo.circle - 1, 0) val valueAtTopRightCorner = number + (circleInfo.circle - 1) if(target <= valueAtTopRightCorner) { val steps = (target-number) - 1 cursor.y = cursor.y + steps return cursor.manhattanDistance().toString() } cursor.y = circleInfo.circle - 1 val stepsToTraverseSide = (circleInfo.circle - 1) * 2 val valueAtTopLeftCorner = valueAtTopRightCorner + stepsToTraverseSide if(target <= valueAtTopLeftCorner) { val steps = target - valueAtTopRightCorner - 1 cursor.x = cursor.x - steps return cursor.manhattanDistance().toString() } cursor.x = cursor.x - stepsToTraverseSide val valueAtBottomLeftCorner = valueAtTopLeftCorner + stepsToTraverseSide if(target <= valueAtBottomLeftCorner) { val steps = target - valueAtTopLeftCorner - 1 cursor.y = cursor.y - steps return cursor.manhattanDistance().toString() } cursor.y = cursor.y - stepsToTraverseSide val valueAtBottomRightCorner = valueAtBottomLeftCorner + stepsToTraverseSide if(target <= valueAtBottomRightCorner) { val steps = target - valueAtBottomLeftCorner - 1 cursor.x = cursor.x + steps return cursor.manhattanDistance().toString() } cursor.x = cursor.x + stepsToTraverseSide val valueBeforeBackAtStart = valueAtBottomRightCorner + (stepsToTraverseSide / 2 - 1) if(target <= valueBeforeBackAtStart) { val steps = target - valueAtBottomRightCorner - 1 cursor.y = cursor.y + steps return cursor.manhattanDistance().toString() } throw RuntimeException("Not found") } private fun doPartTwo(target: Int): String { val memory: MutableMap<Coordinate, Int> = mutableMapOf<Coordinate, Int>().withDefault { 0 } val start = Coordinate(0, 0) memory.put(start, 1) return traverse(target, start, memory, Direction.RIGHT, 1) } private fun traverse(target: Int, curr: Coordinate, memory: MutableMap<Coordinate, Int>, direction: Direction, steps: Int): String { if(steps == 0) { val circleInfo = determineCircle(memory.size) val stepsNext = (circleInfo.circle - 1) * 2 return when(direction) { Direction.UP -> traverse(target, curr, memory, Direction.LEFT, stepsNext) Direction.LEFT -> traverse(target, curr, memory, Direction.DOWN, stepsNext) Direction.DOWN -> traverse(target, curr, memory, Direction.RIGHT, stepsNext+1) Direction.RIGHT -> traverse(target, curr, memory, Direction.UP, stepsNext-1) } } val next = curr.step(direction) val sum = getSum(next, memory) if(sum > target) { return sum.toString() } memory.put(next, sum) return traverse(target, next, memory, direction, steps-1) } private fun getSum(coordinate: Coordinate, memory: MutableMap<Coordinate, Int>): Int { return memory.getValue(coordinate.step(Direction.UP)) + memory.getValue(coordinate.step(Direction.LEFT)) + memory.getValue(coordinate.step(Direction.RIGHT)) + memory.getValue(coordinate.step(Direction.DOWN)) + memory.getValue(Coordinate(coordinate.x+1, coordinate.y+1)) + memory.getValue(Coordinate(coordinate.x-1, coordinate.y+1)) + memory.getValue(Coordinate(coordinate.x+1, coordinate.y-1)) + memory.getValue(Coordinate(coordinate.x-1, coordinate.y-1)) } private fun determineCircle(target: Int): CircleInfo { var steps = 0 if(target > 1) { steps += 1 } var circle = 2 while(true) { val nextSteps = steps + (circle-1) * 8 if(nextSteps > target) { return CircleInfo(circle, steps) } circle++ steps = nextSteps } } }
mit
01e13ba53f6a15afc1971ac4d6ac69d2
33.333333
136
0.605785
4.536082
false
false
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/viewHolders/MountViewHolder.kt
1
2643
package com.habitrpg.android.habitica.ui.viewHolders import android.content.res.Resources import android.graphics.drawable.BitmapDrawable import android.view.View import android.view.ViewGroup import androidx.core.graphics.drawable.toBitmap import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.databinding.MountOverviewItemBinding import com.habitrpg.android.habitica.extensions.inflate import com.habitrpg.android.habitica.models.inventory.Mount import com.habitrpg.android.habitica.ui.helpers.DataBindingUtils import com.habitrpg.android.habitica.ui.menu.BottomSheetMenu import com.habitrpg.android.habitica.ui.menu.BottomSheetMenuItem import io.reactivex.rxjava3.subjects.PublishSubject class MountViewHolder(parent: ViewGroup, private val equipEvents: PublishSubject<String>) : androidx.recyclerview.widget.RecyclerView.ViewHolder(parent.inflate(R.layout.mount_overview_item)), View.OnClickListener { private var binding: MountOverviewItemBinding = MountOverviewItemBinding.bind(itemView) private var owned: Boolean = false var animal: Mount? = null private var currentMount: String? = null var resources: Resources = itemView.resources init { itemView.setOnClickListener(this) } fun bind(item: Mount, owned: Boolean, currentMount: String?) { animal = item this.owned = owned this.currentMount = currentMount binding.titleTextView.visibility = View.GONE binding.ownedTextView.visibility = View.GONE val imageName = "stable_Mount_Icon_" + item.animal + "-" + item.color binding.imageView.alpha = 1.0f if (!owned) { binding.imageView.alpha = 0.2f } binding.imageView.background = null binding.activeIndicator.visibility = if (currentMount.equals(animal?.key)) View.VISIBLE else View.GONE DataBindingUtils.loadImage(itemView.context, imageName) { val drawable = if (owned) it else BitmapDrawable(itemView.context.resources, it.toBitmap().extractAlpha()) binding.imageView.background = drawable } } override fun onClick(v: View) { if (!owned) { return } val menu = BottomSheetMenu(itemView.context) menu.setTitle(animal?.text) val hasCurrentMount = currentMount.equals(animal?.key) val labelId = if (hasCurrentMount) R.string.unequip else R.string.equip menu.addMenuItem(BottomSheetMenuItem(resources.getString(labelId))) menu.setSelectionRunnable { animal?.let { equipEvents.onNext(it.key ?: "") } } menu.show() } }
gpl-3.0
d472f3665119935ca740aac4733694c1
40.952381
214
0.720772
4.502555
false
false
false
false
erickok/borefts2015
android/app/src/main/java/nl/brouwerijdemolen/borefts2013/gui/screens/BoreftsMapView.kt
1
6364
package nl.brouwerijdemolen.borefts2013.gui.screens import android.annotation.SuppressLint import android.content.Context import android.graphics.* import android.graphics.drawable.BitmapDrawable import android.util.SparseArray import androidx.annotation.ColorInt import coil.Coil import coil.api.get import com.google.android.gms.maps.GoogleMapOptions import com.google.android.gms.maps.MapView import com.google.android.gms.maps.model.* import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import nl.brouwerijdemolen.borefts2013.R import nl.brouwerijdemolen.borefts2013.api.Area import nl.brouwerijdemolen.borefts2013.api.Brewer import nl.brouwerijdemolen.borefts2013.api.Poi import nl.brouwerijdemolen.borefts2013.gui.CoroutineScope import nl.brouwerijdemolen.borefts2013.gui.components.ResourceProvider import org.koin.core.KoinComponent import org.koin.core.inject import java.io.IOException import java.util.* @SuppressLint("ViewConstructor") // Only to be created programmatically class BoreftsMapView( context: Context, mapOptions: GoogleMapOptions) : MapView(context, mapOptions), KoinComponent { private val res: ResourceProvider by inject() private var poiMarkers: MutableMap<Marker, Poi> = mutableMapOf() private var poiIds: MutableMap<String, Marker> = mutableMapOf() private var brewerMarkers: MutableMap<Marker, Brewer> = mutableMapOf() private var brewerIds: SparseArray<Marker> = SparseArray() fun showBrewers(brewers: List<Brewer>, focusBrewerId: Int? = null) { getMapAsync { map -> GlobalScope.launch(CoroutineScope.ui) { brewerMarkers = mutableMapOf() brewerIds = SparseArray() for (brewer in brewers) { if (brewer.latitude != null && brewer.longitude != null) { val brewerPin = withContext(CoroutineScope.io) { drawBrewerMarker(brewer) } val bitmapToUse: BitmapDescriptor = if (brewerPin == null) BitmapDescriptorFactory.fromResource(R.drawable.ic_marker_mask) else BitmapDescriptorFactory.fromBitmap(brewerPin) val marker = map.addMarker( MarkerOptions() .position(LatLng(brewer.latitude, brewer.longitude)) .title(brewer.shortName) .icon(bitmapToUse)) brewerMarkers[marker] = brewer brewerIds.put(brewer.id, marker) } } // Set focus on a specific marker if (focusBrewerId != null) { brewerIds.get(focusBrewerId)?.showInfoWindow() } } // DEBUG // map.setOnMapClickListener { Log.v("MAP", "Lat ${it.latitude} Long ${it.longitude}") } } } fun showAreas(areas: List<Area>) { getMapAsync { map -> for (area in areas) { map.addPolygon( PolygonOptions() .addAll(area.pointLatLngs) .strokeColor(getColor(area.color)) .strokeWidth(5f) .fillColor(getFillColor(area.color))) } } } fun showPois(pois: List<Poi>, focusPoiId: String? = null) { getMapAsync { map -> poiMarkers = HashMap() poiIds = HashMap() for (poi in pois) { val marker = map.addMarker( MarkerOptions() .position(poi.pointLatLng) .title(getPoiName(poi)) .icon(BitmapDescriptorFactory.fromResource(getDrawable(poi.marker)))) poiMarkers[marker] = poi poiIds[poi.id] = marker } // Set focus on a specific marker if (focusPoiId != null) { poiIds.get<String?, Marker>(focusPoiId)?.showInfoWindow() } } } fun handleInfoWindowClicks(onBrewerClicked: (Brewer) -> Unit) { getMapAsync { map -> map.setOnInfoWindowClickListener { marker -> brewerMarkers[marker]?.let(onBrewerClicked) } } } private suspend fun drawBrewerMarker(brewer: Brewer): Bitmap? { try { val mask = BitmapFactory.decodeResource(resources, R.drawable.ic_marker_mask) val outline = BitmapFactory.decodeResource(resources, R.drawable.ic_marker_outline) val logoDrawable = Coil.get(brewer.logoUrl) { allowHardware(false) } val logo = (logoDrawable as? BitmapDrawable)?.bitmap ?: throw IllegalStateException("Coil decoder didn't provide a BitmapDrawable") val bmp = Bitmap.createBitmap(mask.width, mask.height, Bitmap.Config.ARGB_8888) val canvas = Canvas(bmp) val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.DITHER_FLAG) canvas.drawBitmap(mask, 0f, 0f, paint) paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN) canvas.drawBitmap(logo, null, Rect(0, 0, mask.width, mask.height), paint) paint.xfermode = null canvas.drawBitmap(outline, 0f, 0f, paint) return bmp } catch (e: IOException) { return null // Should never happen, as the brewer logo always exists } } private fun getPoiName(poi: Poi): String { return if (Locale.getDefault().language == "nl") { poi.name_nl } else poi.name_en } private fun getDrawable(resName: String): Int { return resources.getIdentifier(resName, "drawable", context.packageName) } @ColorInt private fun getColor(resName: String): Int { return res.getColor(resources.getIdentifier(resName, "color", context.packageName)) } @ColorInt private fun getFillColor(resName: String): Int { return getColor(resName + "_half") } }
gpl-3.0
8b3ba2a500aad13234a2181ec8036dc4
38.283951
101
0.585481
4.948678
false
false
false
false
Niky4000/UsefulUtils
projects/tutorials-master/tutorials-master/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/HomeSensorsHandler.kt
1
1458
package com.baeldung.springreactivekotlin import org.springframework.stereotype.Component import org.springframework.web.reactive.function.BodyInserters.fromObject import org.springframework.web.reactive.function.server.ServerRequest import org.springframework.web.reactive.function.server.ServerResponse import reactor.core.publisher.Mono @Component class HomeSensorsHandler { var data = mapOf("lamp" to arrayOf(0.7, 0.65, 0.67), "fridge" to arrayOf(12.0, 11.9, 12.5)) fun setLight(request: ServerRequest): Mono<ServerResponse> = ServerResponse.ok().build() fun getLightReading(request: ServerRequest): Mono<ServerResponse> = ServerResponse.ok().body(fromObject(data["lamp"]!!)) fun getDeviceReadings(request: ServerRequest): Mono<ServerResponse> { val id = request.pathVariable("id") return ServerResponse.ok().body(fromObject(Device(id, 1.0))) } fun getAllDevices(request: ServerRequest): Mono<ServerResponse> = ServerResponse.ok().body(fromObject(arrayOf("lamp", "tv"))) fun getAllDeviceApi(request: ServerRequest): Mono<ServerResponse> = ServerResponse.ok().body(fromObject(arrayListOf("kettle", "fridge"))) fun setDeviceReadingApi(request: ServerRequest): Mono<ServerResponse> { return request.bodyToMono(Device::class.java).flatMap { it -> ServerResponse.ok().body(fromObject(Device(it.name.toUpperCase(), it.reading))) } } }
gpl-3.0
54af1620763a5e43b62c4f82b4154be0
39.527778
95
0.727023
4.300885
false
false
false
false
oleksiyp/mockk
dsl/js/src/main/kotlin/io/mockk/InternalPlatformDsl.kt
1
4279
package io.mockk import kotlin.coroutines.experimental.Continuation import kotlin.reflect.KCallable import kotlin.reflect.KClass actual object InternalPlatformDsl { actual fun identityHashCode(obj: Any): Int = Kotlin.identityHashCode(obj) actual fun <T> runCoroutine(block: suspend () -> T): T = throw UnsupportedOperationException( "Coroutines are not supported for JS MockK version" ) actual fun Any?.toStr(): String = try { when (this) { null -> "null" is BooleanArray -> this.contentToString() is ByteArray -> this.contentToString() is CharArray -> this.contentToString() is ShortArray -> this.contentToString() is IntArray -> this.contentToString() is LongArray -> this.contentToString() is FloatArray -> this.contentToString() is DoubleArray -> this.contentToString() is Array<*> -> this.contentDeepToString() is KClass<*> -> this.simpleName ?: "<null name class>" is Function<*> -> "lambda {}" else -> toString() } } catch (thr: Throwable) { "<error \"$thr\">" } actual fun deepEquals(obj1: Any?, obj2: Any?): Boolean { return if (obj1 === obj2) { true } else if (obj1 == null || obj2 == null) { obj1 === obj2 } else { arrayDeepEquals(obj1, obj2) } } private fun arrayDeepEquals(obj1: Any, obj2: Any): Boolean { return when (obj1) { is BooleanArray -> obj1 contentEquals obj2 as BooleanArray is ByteArray -> obj1 contentEquals obj2 as ByteArray is CharArray -> obj1 contentEquals obj2 as CharArray is ShortArray -> obj1 contentEquals obj2 as ShortArray is IntArray -> obj1 contentEquals obj2 as IntArray is LongArray -> obj1 contentEquals obj2 as LongArray is FloatArray -> obj1 contentEquals obj2 as FloatArray is DoubleArray -> obj1 contentEquals obj2 as DoubleArray is Array<*> -> return obj1 contentDeepEquals obj2 as Array<*> else -> obj1 == obj2 } } actual fun unboxChar(value: Any): Any = if (value is Char) { value.toInt() } else { value } actual fun Any.toArray(): Array<*> = when (this) { is BooleanArray -> this.toTypedArray() is ByteArray -> this.toTypedArray() is CharArray -> this.toTypedArray() is ShortArray -> this.toTypedArray() is IntArray -> this.toTypedArray() is LongArray -> this.toTypedArray() is FloatArray -> this.toTypedArray() is DoubleArray -> this.toTypedArray() else -> this as Array<*> } actual fun classForName(name: String): Any = throw MockKException("classForName is not support on JS platform") actual fun dynamicCall( self: Any, methodName: String, args: Array<out Any?>, anyContinuationGen: () -> Continuation<*> ): Any? = throw MockKException("dynamic call is not supported on JS platform") actual fun dynamicGet(self: Any, name: String): Any? = throw MockKException("dynamic get is not supported on JS platform") actual fun dynamicSet(self: Any, name: String, value: Any?) { throw MockKException("dynamic set is not supported on JS platform") } actual fun dynamicSetField(self: Any, name: String, value: Any?) { throw MockKException("dynamic set is not supported on JS platform") } actual fun <T> threadLocal(initializer: () -> T): InternalRef<T> { return object : InternalRef<T> { override val value = initializer() } } actual fun counter() = object : InternalCounter { override var value = 0L override fun increment() = value++ } actual fun <T> coroutineCall(lambda: suspend () -> T): CoroutineCall<T> { throw MockKException("coroutineCall is not supported") } } internal external object Kotlin { fun identityHashCode(obj: Any): Int }
apache-2.0
4f8806a71a101c85ff0adf7ab21574cf
34.658333
115
0.58495
4.952546
false
false
false
false
TUWien/DocScan
app/src/main/java/at/ac/tuwien/caa/docscan/export/PdfCreator.kt
1
12870
package at.ac.tuwien.caa.docscan.export import android.content.Context import android.net.Uri import at.ac.tuwien.caa.docscan.db.model.error.IOErrorCode import at.ac.tuwien.caa.docscan.db.model.exif.Rotation import at.ac.tuwien.caa.docscan.extensions.await import at.ac.tuwien.caa.docscan.logic.Resource import at.ac.tuwien.caa.docscan.logic.Success import at.ac.tuwien.caa.docscan.logic.asFailure import at.ac.tuwien.caa.docscan.logic.calculateImageResolution import at.ac.tuwien.caa.docscan.ui.crop.ImageMeta import com.google.mlkit.vision.common.InputImage import com.google.mlkit.vision.text.Text import com.google.mlkit.vision.text.Text.TextBlock import com.google.mlkit.vision.text.TextRecognition import com.google.mlkit.vision.text.TextRecognizer import com.google.mlkit.vision.text.latin.TextRecognizerOptions import com.itextpdf.text.* import com.itextpdf.text.pdf.BaseFont import com.itextpdf.text.pdf.ColumnText import com.itextpdf.text.pdf.PdfWriter import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.isActive import kotlinx.coroutines.withContext import java.io.File object PdfCreator { suspend fun analyzeFileWithOCR( context: Context, uri: Uri, textRecognizer: TextRecognizer = TextRecognition.getClient( TextRecognizerOptions.DEFAULT_OPTIONS ) ): Resource<Text> { @Suppress("BlockingMethodInNonBlockingContext") val image = InputImage.fromFilePath(context, uri) val task = textRecognizer.process(image) return task.await() } // suppressed, since this is expected and mitigated by making this function cooperative @Suppress("BlockingMethodInNonBlockingContext") suspend fun savePDF( context: Context, outputUri: Uri, files: List<FileWrapper>, ocrResults: List<Text>? = null ): Resource<Unit> { context.contentResolver.openOutputStream(outputUri, "rw").use { outputStream -> return withContext(Dispatchers.IO) { try { val first = files[0] var resolution = calculateImageResolution(first.file, first.rotation) val landscapeFirst = isLandscape(resolution) val firstPageSize = getPageSize(resolution, landscapeFirst) val document = Document(firstPageSize, 0F, 0F, 0F, 0F) val writer = PdfWriter.getInstance(document, outputStream) document.open() for (i in files.indices) { // check if the coroutine is still active, if not, close the document and throw a CancellationException if (!isActive) { document.close() throw CancellationException() } var file = files[i] val rotationInDegrees = file.rotation.angle //add the original image to the pdf and set the DPI of it to 600 val image = Image.getInstance(file.file.absolutePath) image.setRotationDegrees(-rotationInDegrees.toFloat()) if (rotationInDegrees == 0 || rotationInDegrees == 180) image.scaleAbsolute( document.pageSize.width, document.pageSize.height ) else image.scaleAbsolute( document.pageSize.height, document.pageSize.width ) image.setDpi(600, 600) document.add(image) if (ocrResults != null) { // the direct content where we write on // directContentUnder instead of directContent, because then the text is in the background) //PdfContentByte cb = writer.getDirectContentUnder(); val cb = writer.directContentUnder val bf = BaseFont.createFont() //sort the result based on the y-Axis so that the markup order is correct val sortedBlocks = sortBlocks(ocrResults[i]) resolution = calculateImageResolution(file.file, file.rotation) //int j = 0; for (column in sortedBlocks) { for (line in sortLinesInColumn(column)) { // one FirebaseVisionText.Line corresponds to one line // the rectangle we want to draw this line corresponds to the lines boundingBox val boundingBox = line.boundingBox ?: continue val left = boundingBox.left.toFloat() / resolution.width.toFloat() * document.pageSize.width val right = boundingBox.right.toFloat() / resolution.width.toFloat() * document.pageSize.width val top = boundingBox.top.toFloat() / resolution.height.toFloat() * document.pageSize.height val bottom = boundingBox.bottom.toFloat() / resolution.height.toFloat() * document.pageSize.height val rect = Rectangle( left, document.pageSize.height - bottom, right, document.pageSize.height - top ) val drawText = line.text // try to get max font size that fit in rectangle val textHeightInGlyphSpace = bf.getAscent(drawText) - bf.getDescent(drawText) var fontSize = 1000f * rect.height / textHeightInGlyphSpace while (bf.getWidthPoint(drawText, fontSize) < rect.width) { fontSize++ } while (bf.getWidthPoint(drawText, fontSize) > rect.width) { fontSize -= 0.1f } val phrase = Phrase(drawText, Font(bf, fontSize)) // write the text on the pdf ColumnText.showTextAligned( cb, Element.ALIGN_CENTER, phrase, // center horizontally (rect.left + rect.right) / 2, // shift baseline based on descent rect.bottom - bf.getDescentPoint(drawText, fontSize), 0f ) } } } if (i < files.size - 1) { file = files[i + 1] val pageSize = getPageSize( calculateImageResolution(file.file, file.rotation), landscapeFirst ) document.pageSize = pageSize document.newPage() } } document.close() return@withContext Success(Unit) } catch (e: Exception) { // if this has happened because of a cancellation, then this needs to be re-thrown if (e is CancellationException) { throw e } else { return@withContext IOErrorCode.EXPORT_CREATE_PDF_FAILED.asFailure(e) } } } } } private fun isLandscape(size: ImageMeta): Boolean { return size.width > size.height } private fun getPageSize(size: ImageMeta, landscape: Boolean): Rectangle { val pageSize: Rectangle = if (landscape) { val height = PageSize.A4.height / size.width * size.height Rectangle(PageSize.A4.height, height) } else { val height = PageSize.A4.width / size.width * size.height Rectangle(PageSize.A4.width, height) } return pageSize } private fun sortBlocks(ocrResult: Text?): List<MutableList<TextBlock>> { val sortedBlocks: MutableList<MutableList<TextBlock>> = ArrayList() val biggestBlocks: MutableList<TextBlock> = ArrayList() val blocksSortedByWidth = sortByWidth(ocrResult!!.textBlocks) for (block in blocksSortedByWidth) { if (block.boundingBox == null) continue if (sortedBlocks.isEmpty()) { val blocks: MutableList<TextBlock> = ArrayList() blocks.add(block) biggestBlocks.add(block) sortedBlocks.add(blocks) } else { var added = false for (checkBlock in biggestBlocks) { if (checkBlock.boundingBox == null) continue if (block.boundingBox!!.centerX() > checkBlock.boundingBox!!.left && block.boundingBox!!.centerX() < checkBlock.boundingBox!!.right ) { sortedBlocks[biggestBlocks.indexOf(checkBlock)].add(block) if (block.boundingBox!!.width() > checkBlock.boundingBox!!.width()) { biggestBlocks[biggestBlocks.indexOf(checkBlock)] = block } added = true break } } if (!added) { val blocks: MutableList<TextBlock> = ArrayList() blocks.add(block) var i = 0 while (i < biggestBlocks.size) { if (biggestBlocks[i].boundingBox == null || block.boundingBox!!.centerX() > biggestBlocks[i].boundingBox!!.centerX() ) { i++ } else { break } } biggestBlocks.add(i, block) sortedBlocks.add(i, blocks) } } } for (textBlocks in sortedBlocks) { sortedBlocks[sortedBlocks.indexOf(textBlocks)] = textBlocks } return sortedBlocks } private fun sortByWidth(result: List<TextBlock>): List<TextBlock> { val sortedBlocks: MutableList<TextBlock> = ArrayList() for (textBlock in result) { if (textBlock.boundingBox == null) continue if (sortedBlocks.isEmpty()) { sortedBlocks.add(textBlock) } else { var i = 0 while (i < sortedBlocks.size) { if (sortedBlocks[i].boundingBox == null || textBlock.boundingBox!!.width() < sortedBlocks[i].boundingBox!!.width() ) { i++ } else { break } } sortedBlocks.add(i, textBlock) } } return sortedBlocks } private fun sortLinesInColumn(result: List<TextBlock>): List<Text.Line> { val sortedLines: MutableList<Text.Line> = ArrayList() for (textBlock in result) { for (line in textBlock.lines) // if (line.getCornerPoints() == null || line.getCornerPoints().length == 0) // continue; if (sortedLines.isEmpty()) { sortedLines.add(line) } else { var i = 0 while (i < sortedLines.size) { if (line.cornerPoints!![0].y > sortedLines[i].cornerPoints!![0].y) { i++ } else { break } } sortedLines.add(i, line) } } return sortedLines } data class FileWrapper(val file: File, val rotation: Rotation) }
lgpl-3.0
93496784e47a1820e0401397ef97b40a
45.974453
134
0.490287
5.755814
false
false
false
false
lehvolk/xodus-entity-browser
entity-browser-app/src/test/kotlin/jetbrains/xodus/browser/web/search/SmartSearchQueryParserTest.kt
1
6262
package jetbrains.xodus.browser.web.search import org.junit.Assert.assertEquals import org.junit.Test class SmartSearchQueryParserTest { @Test fun testSimple() { val result = "firstName='John' and lastName='McClane' and age!=34".parse() assertEquals(3, result.size.toLong()) result[0].assertPropertyValueTerm("firstName", "John", true) result[1].assertPropertyValueTerm("lastName", "McClane", true) result[2].assertPropertyValueTerm("age", "34", false) } @Test fun testSingleParam() { val result = "firstName='John'".parse() assertEquals(1, result.size.toLong()) result[0].assertPropertyValueTerm("firstName", "John", true) } @Test fun testWithoutQuotes() { val result = "firstName=John and lastName!=McClane and age=43".parse() assertEquals(3, result.size.toLong()) result[0].assertPropertyValueTerm("firstName", "John", true) result[1].assertPropertyValueTerm("lastName", "McClane", false) result[2].assertPropertyValueTerm("age", "43", true) } @Test fun testLike() { val result = "firstName=John and lastName~McClane".parse() assertEquals(2, result.size.toLong()) result[0].assertPropertyValueTerm("firstName", "John", true) result[1].assertPropertyLikeTerm("lastName", "McClane") } @Test fun testSingleParamsWithoutQuotes() { val result = "firstName=John".parse() assertEquals(1, result.size.toLong()) result[0].assertPropertyValueTerm("firstName", "John", true) } @Test fun testEscapingQuotes() { val result = "firstName=John and lastName='Mc''Clane'".parse() assertEquals(2, result.size.toLong()) result[0].assertPropertyValueTerm("firstName", "John", true) result[1].assertPropertyValueTerm("lastName", "Mc'Clane", true) } @Test fun testOmitAndIntoQuotes() { val result = "firstName!='John and Mike' and lastName='McClane'".parse() assertEquals(2, result.size.toLong()) result[0].assertPropertyValueTerm("firstName", "John and Mike", false) result[1].assertPropertyValueTerm("lastName", "McClane", true) } @Test fun testEqualsIntoQuotes() { val result = "firstName='John=Mike' and lastName='McClane'".parse() assertEquals(2, result.size.toLong()) result[0].assertPropertyValueTerm("firstName", "John=Mike", true) result[1].assertPropertyValueTerm("lastName", "McClane", true) } @Test fun testSpacesIntoQuotes() { val result = "firstName='John Mike' and lastName='McClane'".parse() assertEquals(2, result.size.toLong()) result[0].assertPropertyValueTerm("firstName", "John Mike", true) result[1].assertPropertyValueTerm("lastName", "McClane", true) } @Test fun testSpecialSymbols() { val result = "'_!@firstName'='John Mike' and '_!@lastName'='McClane'".parse() assertEquals(2, result.size.toLong()) result[0].assertPropertyValueTerm("_!@firstName", "John Mike", true) result[1].assertPropertyValueTerm("_!@lastName", "McClane", true) } @Test fun testRange() { val result = "firstName!='John Mike' and age=[30,40]".parse() assertEquals(2, result.size.toLong()) result[0].assertPropertyValueTerm("firstName", "John Mike", false) result[1].assertPropertyRangeTerm("age", 30, 40) } @Test fun testLink() { val result = "@linkName!=MyType[3] and firstName~Jo".parse() assertEquals(2, result.size) result[0].assertLinkTerm("linkName", "MyType", 3, false) result[1].assertPropertyLikeTerm("firstName", "Jo") } @Test fun testPropNull() { val result = "firstName=null and lastName='null'".parse() assertEquals(2, result.size) result[0].assertPropertyValueTerm("firstName", null, true) result[1].assertPropertyValueTerm("lastName", "null", true) } @Test fun testLinkNull() { val result = "@user!=null and @action=MyAction[4]".parse() assertEquals(2, result.size) result[0].assertLinkTerm("user", null, null, false) result[1].assertLinkTerm("action", "MyAction", 4, true) } @Test(expected = jetbrains.xodus.browser.web.search.ParseException::class) @Throws(jetbrains.xodus.browser.web.search.ParseException::class) fun testCheckThrowsExceptionOnEmptyMap() { jetbrains.xodus.browser.web.search.SmartSearchQueryParser.check(emptyList<SearchTerm>(), "") } @Test fun testCaseInsensitive() { val result = "firstName='John Mike' AND lastName='McClane'".parse() assertEquals(2, result.size.toLong()) result[0].assertPropertyValueTerm("firstName", "John Mike", true) result[1].assertPropertyValueTerm("lastName", "McClane", true) } private fun SearchTerm.assertPropertyLikeTerm(expectedName: String, expectedValue: String) { val actual = this as PropertyLikeSearchTerm assertEquals(expectedName, actual.name) assertEquals(expectedValue, actual.value) } private fun SearchTerm.assertPropertyRangeTerm(expectedName: String, expectedStart: Long, expectedEnd: Long) { val actual = this as PropertyRangeSearchTerm assertEquals(expectedName, actual.name) assertEquals(expectedStart, actual.start) assertEquals(expectedEnd, actual.end) } private fun SearchTerm.assertPropertyValueTerm(expectedName: String, expectedValue: String?, expectedEquals: Boolean) { val actual = this as PropertyValueSearchTerm assertEquals(expectedName, actual.name) assertEquals(expectedValue, actual.value) assertEquals(expectedEquals, actual.equals) } private fun SearchTerm.assertLinkTerm(expectedName: String, expectedTypeName: String?, expectedLocalId: Long?, expectedEquals: Boolean) { val actual = this as LinkSearchTerm assertEquals(expectedName, actual.name) assertEquals(expectedTypeName, actual.oppositeEntityTypeName) assertEquals(expectedLocalId, actual.oppositeEntityLocalId) assertEquals(expectedEquals, actual.equals) } }
apache-2.0
30e7e3086a9b6d81f0127a41d20f901e
37.654321
141
0.664005
4.492109
false
true
false
false
SiimKinks/sqlitemagic
sqlitemagic-tests/app/src/androidTest/kotlin/com/siimkinks/sqlitemagic/model/persist/BulkItemsPersistWithConflictsIgnoringNullTest.kt
1
17066
@file:Suppress("UNCHECKED_CAST") package com.siimkinks.sqlitemagic.model.persist import android.database.sqlite.SQLiteDatabase import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.common.truth.Truth.assertThat import com.siimkinks.sqlitemagic.DefaultConnectionTest import com.siimkinks.sqlitemagic.Select import com.siimkinks.sqlitemagic.createVals import com.siimkinks.sqlitemagic.model.* import com.siimkinks.sqlitemagic.model.insert.BulkItemsInsertTest import com.siimkinks.sqlitemagic.model.insert.BulkItemsInsertWithConflictsTest import com.siimkinks.sqlitemagic.model.insert.assertEarlyUnsubscribeFromInsertRollbackedAllValues import com.siimkinks.sqlitemagic.model.insert.assertEarlyUnsubscribeFromInsertStoppedAnyFurtherWork import com.siimkinks.sqlitemagic.model.persist.BulkItemsPersistWithConflictsTest.* import com.siimkinks.sqlitemagic.model.update.BulkItemsUpdateTest import com.siimkinks.sqlitemagic.model.update.BulkItemsUpdateWithConflictsTest import com.siimkinks.sqlitemagic.model.update.assertEarlyUnsubscribeFromUpdateRollbackedAllValues import org.junit.Test import org.junit.runner.RunWith import java.util.* @RunWith(AndroidJUnit4::class) class BulkItemsPersistWithConflictsIgnoringNullTest : DefaultConnectionTest { @Test fun mutableModelBulkPersistWithInsertAndIgnoreConflictSetsIdsIgnoringNull() { assertThatDual { testCase { BulkItemsInsertTest.MutableModelBulkOperationSetsIds( forModel = it, setUp = { val model = it as TestModelWithNullableColumns createVals { var newRandom = it.newRandom() newRandom = it.setId(newRandom, -1) model.nullSomeColumns(newRandom) } }, operation = BulkPersistForInsertWithIgnoreConflictDualOperation( ignoreNullValues = true)) } isSuccessfulFor( simpleMutableAutoIdTestModel, complexMutableAutoIdTestModel) } } @Test fun simpleModelBulkPersistWithInsertAndIgnoreConflictIgnoringNull() { assertThatDual { testCase { BulkItemsInsertWithConflictsTest.SimpleModelBulkOperationWithIgnoreConflict( forModel = it as TestModelWithUniqueColumn, setUp = { val nullableModel = it as NullableColumns<Any> val testVals = createVals { val (random) = insertNewRandom(it) nullableModel.nullSomeColumns(random) } for (i in 0..10) { testVals.add(nullableModel.nullSomeColumns(it.newRandom())) } Collections.shuffle(testVals) testVals }, operation = BulkPersistForInsertWithIgnoreConflictDualOperation( ignoreNullValues = true)) } isSuccessfulFor(*SIMPLE_NULLABLE_FIXED_ID_MODELS) } } @Test fun simpleModelBulkPersistWithUpdateAndIgnoreConflictIgnoringNull() { assertThatDual { testCase { BulkItemsUpdateWithConflictsTest.SimpleModelBulkOperationWithIgnoreConflict( forModel = it as TestModelWithUniqueColumn, setUp = { val model = it as TestModelWithUniqueColumn BulkItemsUpdateWithConflictsTest.BulkUpdateWithIgnoreConflictTestVals( model = model, nullSomeColumns = true) }, operation = BulkPersistForUpdateWithIgnoreConflictDualOperation( ignoreNullValues = true)) } isSuccessfulFor(*SIMPLE_NULLABLE_FIXED_ID_MODELS) } } @Test fun complexBulkPersistWithInsertAndIgnoreConflictIgnoringNullWhereParentFails() { assertThatDual { testCase { BulkItemsInsertWithConflictsTest.ComplexModelBulkOperationWithIgnoreConflictWhereParentFails( forModel = it as ComplexTestModelWithUniqueColumn, setUp = { val nullableModel = it as NullableColumns<Any> val model = it as ComplexTestModelWithUniqueColumn val testVals = createVals { val (v1, _) = insertNewRandom(model) val newRandom = nullableModel.nullSomeColumns(model.newRandom()) model.transferUniqueVal(v1, newRandom) } for (i in 0..10) { testVals.add(nullableModel.nullSomeColumns(model.newRandom())) } Collections.shuffle(testVals) testVals }, operation = BulkPersistForInsertWithIgnoreConflictDualOperation( ignoreNullValues = true)) } isSuccessfulFor(*COMPLEX_NULLABLE_FIXED_ID_MODELS) } } @Test fun complexBulkPersistWithUpdateAndIgnoreConflictIgnoringNullWhereParentFails() { assertThatDual { testCase { BulkItemsUpdateWithConflictsTest.ComplexModelBulkOperationWithIgnoreConflictWhereParentFails( forModel = it as ComplexTestModelWithUniqueColumn, setUp = { BulkItemsUpdateWithConflictsTest.BulkUpdateWithIgnoreConflictTestVals( model = it as ComplexTestModelWithUniqueColumn, nullSomeColumns = true) }, operation = BulkPersistForUpdateWithIgnoreConflictDualOperation( ignoreNullValues = true)) } isSuccessfulFor(*COMPLEX_NULLABLE_FIXED_ID_MODELS) } } @Test fun complexBulkPersistWithInsertAndIgnoreConflictIgnoringNullWhereChildFails() { assertThatDual { testCase { BulkItemsInsertWithConflictsTest.ComplexModelBulkOperationWithIgnoreConflictWhereChildFails( forModel = it as ComplexTestModelWithUniqueColumn, setUp = { val nullableModel = it as NullableColumns<Any> val model = it as ComplexTestModelWithUniqueColumn val testVals = createVals { val (newRandom, _) = insertNewRandom(model) val newVal = nullableModel.nullSomeColumns(model.newRandom()) model.transferComplexColumnUniqueVal(newRandom, newVal) } for (i in 0..10) { testVals.add(nullableModel.nullSomeColumns(it.newRandom())) } Collections.shuffle(testVals) testVals }, operation = BulkPersistForInsertWithIgnoreConflictDualOperation( ignoreNullValues = true)) } isSuccessfulFor(*COMPLEX_NULLABLE_FIXED_ID_MODELS) } } @Test fun complexBulkPersistWithUpdateAndIgnoreConflictIgnoringNullWhereChildFails() { assertThatDual { testCase { BulkItemsUpdateWithConflictsTest.ComplexBulkOperationWithIgnoreConflictWhereChildFails( forModel = it as ComplexTestModelWithUniqueColumn, setUp = { BulkItemsUpdateWithConflictsTest.BulkUpdateWithIgnoreConflictTestVals( model = it as ComplexTestModelWithUniqueColumn, nullSomeColumns = true, transferUniqueVal = { model, src, target -> (model as ComplexTestModelWithUniqueColumn).transferComplexColumnUniqueVal(src, target) }) }, operation = BulkPersistForUpdateWithIgnoreConflictDualOperation( ignoreNullValues = true)) } isSuccessfulFor(*COMPLEX_NULLABLE_FIXED_ID_MODELS) } } @Test fun complexModelBulkPersistWithInsertAndIgnoreConflictIgnoringNullWhereAllChildrenFail() { assertThatDual { testCase { BulkItemsInsertWithConflictsTest.ComplexBulkOperationWithIgnoreConflictWhereAllChildrenFail( forModel = it as ComplexTestModelWithUniqueColumn, setUp = { val model = it as ComplexTestModelWithUniqueColumn val nullableModel = it as NullableColumns<Any> createVals { val (newRandom) = insertNewRandom(it) val newVal = nullableModel.nullSomeColumns(it.newRandom()) model.transferComplexColumnUniqueVal(newRandom, newVal) } }, operation = BulkPersistForInsertWithIgnoreConflictWhereAllFailDualOperation( ignoreNullValues = true)) } isSuccessfulFor(*COMPLEX_NULLABLE_FIXED_ID_MODELS) } } @Test fun complexModelBulkPersistWithUpdateAndIgnoreConflictIgnoringNullWhereAllChildrenFail() { assertThatDual { testCase { BulkItemsUpdateWithConflictsTest.ComplexBulkOperationWithIgnoreConflictWhereAllChildrenFail( forModel = it as ComplexTestModelWithUniqueColumn, setUp = { BulkItemsUpdateWithConflictsTest.BulkUpdateWithIgnoreConflictWhereAllFailTestVals( model = it as ComplexTestModelWithUniqueColumn, nullSomeColumns = true, transferUniqueVal = { model, src, target -> (model as ComplexTestModelWithUniqueColumn).transferComplexColumnUniqueVal(src, target) }) }, operation = BulkPersistForUpdateWithIgnoreConflictWhereAllFailDualOperation( ignoreNullValues = true)) } isSuccessfulFor(*COMPLEX_NULLABLE_FIXED_ID_MODELS) } } @Test fun bulkPersistWithInsertAndIgnoreConflictIgnoringNullWhereAllFail() { assertThatDual { testCase { BulkItemsInsertWithConflictsTest.BulkOperationWithIgnoreConflictWhereAllFail( forModel = it, setUp = { val model = it as TestModelWithUniqueColumn val nullableModel = it as NullableColumns<Any> createVals { val (v, _) = insertNewRandom(model) val newRandom = nullableModel.nullSomeColumns(it.newRandom()) model.transferUniqueVal(v, newRandom) } }, operation = BulkPersistForInsertWithIgnoreConflictWhereAllFailDualOperation( ignoreNullValues = true)) } isSuccessfulFor(*ALL_NULLABLE_FIXED_ID_MODELS) } } @Test fun bulkPersistWithUpdateAndIgnoreConflictIgnoringNullWhereAllFail() { assertThatDual { testCase { BulkItemsUpdateWithConflictsTest.BulkOperationWithIgnoreConflictWhereAllFail( forModel = it as TestModelWithUniqueColumn, setUp = { BulkItemsUpdateWithConflictsTest.BulkUpdateWithIgnoreConflictWhereAllFailTestVals( model = it as TestModelWithUniqueColumn, nullSomeColumns = true) }, operation = BulkPersistForUpdateWithIgnoreConflictWhereAllFailDualOperation( ignoreNullValues = true)) } isSuccessfulFor(*ALL_NULLABLE_FIXED_ID_MODELS) } } @Test fun earlyUnsubscribeFromSimpleModelPersistWithInsertAndIgnoreConflictIgnoringNull() { assertThatSingle { testCase { BulkItemsInsertWithConflictsTest.EarlyUnsubscribeWithIgnoreConflict( "Unsubscribing in-flight bulk persist with insert and ignore conflict algorithm " + "with ignoring null values on simple models rollbacks all values", forModel = it, setUp = { createVals(count = 500) { newRandomWithNulledColumns()(it) } }, test = BulkPersistEarlyUnsubscribeWithIgnoreConflict(ignoreNullValues = true), assertResults = assertEarlyUnsubscribeFromInsertRollbackedAllValues()) } isSuccessfulFor(*SIMPLE_NULLABLE_AUTO_ID_MODELS) } } @Test fun earlyUnsubscribeFromSimpleModelPersistWithUpdateAndIgnoreConflictIgnoringNull() { assertThatSingle { testCase { BulkItemsUpdateWithConflictsTest.EarlyUnsubscribeWithIgnoreConflict( "Unsubscribing in-flight bulk persist with update and ignore conflict algorithm " + "with ignoring null values on simple models rollbacks all values", forModel = it, setUp = { createVals(count = 500) { newUpdatableRandomWithNulledColumns()(it) } }, test = BulkPersistEarlyUnsubscribeWithIgnoreConflict(ignoreNullValues = true), assertResults = assertEarlyUnsubscribeFromUpdateRollbackedAllValues()) } isSuccessfulFor(*SIMPLE_NULLABLE_AUTO_ID_MODELS) } } @Test fun earlyUnsubscribeFromComplexModelPersistWithInsertAndIgnoreConflictIgnoringNull() { assertThatSingle { testCase { BulkItemsInsertWithConflictsTest.EarlyUnsubscribeWithIgnoreConflict( "Unsubscribing in-flight bulk persist with insert and ignore conflict algorithm " + "with ignoring null values on complex models stops any further work", forModel = it, setUp = { createVals(count = 500) { newRandomWithNulledColumns()(it) } }, test = BulkPersistEarlyUnsubscribeWithIgnoreConflict(ignoreNullValues = true), assertResults = assertEarlyUnsubscribeFromInsertStoppedAnyFurtherWork()) } isSuccessfulFor(*COMPLEX_NULLABLE_AUTO_ID_MODELS) } } @Test fun earlyUnsubscribeFromComplexModelPersistWithUpdateAndIgnoreConflictIgnoringNull() { assertThatSingle { testCase { BulkItemsUpdateWithConflictsTest.EarlyUnsubscribeWithIgnoreConflict( "Unsubscribing in-flight bulk persist with update and ignore conflict algorithm " + "with ignoring null values on complex models stops any further work", forModel = it, setUp = { createVals(count = 500) { newUpdatableRandomWithNulledColumns()(it) } }, test = BulkPersistEarlyUnsubscribeWithIgnoreConflict(ignoreNullValues = true), assertResults = { model, testVals, eventsCount -> val firstDbValue = Select .from(model.table) .queryDeep() .takeFirst() .execute()!! val firstTestVal = testVals .sortedBy { model.getId(it) } .first() (model as ComplexNullableColumns<Any>) .assertAllExceptNulledColumnsAreUpdated(firstDbValue, firstTestVal) assertThat(eventsCount.get()).isEqualTo(0) }) } isSuccessfulFor(*COMPLEX_NULLABLE_AUTO_ID_MODELS) } } @Test fun streamedBulkPersistWithInsertAndIgnoreConflictIgnoringNull() { assertThatSingle { testCase { BulkItemsInsertTest.StreamedBulkOperation( forModel = it, test = BulkItemsPersistTest.StreamedBulkPersistWithInsertOperation( ignoreConflict = true, ignoreNullValues = true)) } isSuccessfulFor(*ALL_AUTO_ID_MODELS) } } @Test fun streamedBulkPersistWithUpdateAndIgnoreConflictIgnoringNull() { assertThatSingle { testCase { BulkItemsUpdateTest.StreamedBulkOperation( forModel = it, test = BulkItemsPersistTest.StreamedBulkPersistWithUpdateOperation( ignoreConflict = true, ignoreNullValues = true)) } isSuccessfulFor(*ALL_AUTO_ID_MODELS) } } @Test fun bulkPersistWithUpdateByUniqueColumnAndIgnoreConflictIgnoringNull() { assertThatDual { testCase { BulkItemsPersistIgnoringNullTest.BulkOperationByUniqueColumnIgnoringNull( forModel = it, operation = BulkPersistDualOperation(ignoreNullValues = true) { model, testVals -> model.bulkPersistBuilder(testVals) .conflictAlgorithm(SQLiteDatabase.CONFLICT_IGNORE) .byColumn((model as TestModelWithUniqueColumn).uniqueColumn) }) } isSuccessfulFor(*ALL_FIXED_ID_MODELS) } } @Test fun bulkPersistWithUpdateByComplexUniqueColumnAndIgnoreConflictIgnoringNull() { assertThatDual { testCase { BulkItemsPersistIgnoringNullTest.BulkOperationByComplexUniqueColumnIgnoringNull( forModel = it, operation = BulkPersistDualOperation(ignoreNullValues = true) { model, testVals -> model.bulkPersistBuilder(testVals) .conflictAlgorithm(SQLiteDatabase.CONFLICT_IGNORE) .byColumn((model as ComplexTestModelWithUniqueColumn).complexUniqueColumn) }) } isSuccessfulFor(*COMPLEX_FIXED_ID_MODELS) } } @Test fun bulkPersistWithUpdateByComplexColumnUniqueColumnAndIgnoreConflictIgnoringNull() { assertThatDual { testCase { BulkItemsPersistIgnoringNullTest.BulkOperationByComplexColumnUniqueColumnIgnoringNull( forModel = it, operation = BulkPersistDualOperation(ignoreNullValues = true) { model, testVals -> model.bulkPersistBuilder(testVals) .conflictAlgorithm(SQLiteDatabase.CONFLICT_IGNORE) .byColumn((model as ComplexTestModelWithUniqueColumn).complexColumnUniqueColumn) }) } isSuccessfulFor(*COMPLEX_FIXED_ID_MODELS) } } }
apache-2.0
0ff3a5b160691af35e744ffb038db1e0
39.635714
107
0.668757
6.703064
false
true
false
false
y2k/JoyReactor
ios/src/main/kotlin/y2k/joyreactor/VideoViewController.kt
1
2440
package y2k.joyreactor import org.robovm.apple.avfoundation.AVLayerVideoGravity import org.robovm.apple.avfoundation.AVPlayer import org.robovm.apple.avfoundation.AVPlayerLayer import org.robovm.apple.coremedia.CMTime import org.robovm.apple.foundation.NSObject import org.robovm.apple.foundation.NSURL import org.robovm.apple.uikit.UIActivityIndicatorView import org.robovm.apple.uikit.UIViewController import org.robovm.objc.annotation.CustomClass import org.robovm.objc.annotation.IBOutlet import y2k.joyreactor.common.ServiceLocator import y2k.joyreactor.common.bindingBuilder import y2k.joyreactor.viewmodel.VideoViewModel /** * Created by y2k on 22/10/15. */ @CustomClass("VideoViewController") class VideoViewController : UIViewController() { @IBOutlet lateinit var indicatorView: UIActivityIndicatorView lateinit var player: AVPlayer var repeatObserver: NSObject? = null override fun viewDidLoad() { super.viewDidLoad() navigationController.setNavigationBarHidden(true, true) val vm = ServiceLocator.resolve<VideoViewModel>() bindingBuilder { action(vm.isBusy) { navigationItem.setHidesBackButton(it, true) if (it) indicatorView.startAnimating() else indicatorView.stopAnimating() } action(vm.videoFile) { if (it == null) return@action // TODO: вынести в отдельный контрол player = AVPlayer(NSURL(it)) repeatObserver = player.addBoundaryTimeObserver( listOf(player.currentItem.asset.duration.subtract(CMTime.create(0.1, 600))), null) { player.seekToTime(CMTime.Zero()) } val layer = AVPlayerLayer() layer.player = player layer.frame = view.frame layer.videoGravity = AVLayerVideoGravity.ResizeAspect view.layer.addSublayer(layer) player.play() } } } override fun viewWillAppear(animated: Boolean) { super.viewWillAppear(animated) navigationController.setHidesBarsOnTap(true) } override fun viewWillDisappear(animated: Boolean) { super.viewWillDisappear(animated) navigationController.setHidesBarsOnTap(false) if (repeatObserver != null) player.removeTimeObserver(repeatObserver) } }
gpl-2.0
c45885b2feb709a5bda6457d0f5aaa8c
33.528571
96
0.680877
4.416819
false
false
false
false
WonderBeat/vasilich
src/main/kotlin/com/vasilich/monitoring/Throttled.kt
1
1403
package com.vasilich.monitoring import com.google.common.cache.Cache import org.apache.commons.lang3.StringUtils import java.util.Comparator import java.util.concurrent.TimeUnit import com.google.common.cache.CacheBuilder import java.util.TreeSet fun stringDistanceComparator(criticalDistance: Int) = Comparator<String> { (one: String, another: String): Int -> val distance = StringUtils.getLevenshteinDistance(one, another) when { distance > criticalDistance -> distance else -> 0 } } /** * Monitoring can be very importunate * With this trait we can reduce it verbosity */ fun throttle<T>(cache: Cache<T, Unit> = CacheBuilder.newBuilder()!!.maximumSize(20)!! .expireAfterWrite(2, TimeUnit.MINUTES)!!.build()!!, comparator: Comparator<T>? = null): (Collection<T>) -> Collection<T> = { input -> val keyset = cache.asMap()!!.keySet() val newInstances = input.filter { when { comparator == null && !keyset.contains(it) -> true comparator == null -> false else -> { val keyComparableSet = TreeSet(comparator) keyComparableSet.addAll(keyset) !keyComparableSet.containsItem(it) } }} newInstances.forEach { cache.put(it, Unit.VALUE) } newInstances }
gpl-2.0
22897b5c27d09313a3a2d8295c1952af
34.974359
113
0.617249
4.439873
false
false
false
false
ligee/kotlin-jupyter
jupyter-lib/api/src/main/kotlin/org/jetbrains/kotlinx/jupyter/api/fieldsHandling.kt
1
1774
package org.jetbrains.kotlinx.jupyter.api import kotlin.reflect.KClass import kotlin.reflect.KProperty import kotlin.reflect.KType import kotlin.reflect.full.createType import kotlin.reflect.full.isSubtypeOf import kotlin.reflect.full.starProjectedType typealias VariableDeclarationCallback<T> = KotlinKernelHost.(T, KProperty<*>) -> Unit typealias VariableName = String typealias VariableUpdateCallback<T> = KotlinKernelHost.(T, KProperty<*>) -> VariableName? fun interface FieldHandlerExecution<T> { fun execute(host: KotlinKernelHost, value: T, property: KProperty<*>) } interface FieldHandler { /** * Returns true if this converter accepts [type], false otherwise */ fun acceptsType(type: KType): Boolean /** * Execution to handle conversion. * Should not throw if [acceptsType] returns true */ val execution: FieldHandlerExecution<*> } class FieldHandlerByClass( private val kClass: KClass<out Any>, override val execution: FieldHandlerExecution<*>, ) : FieldHandler { override fun acceptsType(type: KType) = type.isSubtypeOf(kClass.starProjectedType) } data class VariableDeclaration( val name: VariableName, val value: Any?, val type: KType, val isMutable: Boolean = false, ) { constructor( name: VariableName, value: Any?, isMutable: Boolean = false ) : this( name, value, value?.let { it::class.starProjectedType } ?: Any::class.createType(nullable = true), isMutable ) } fun KotlinKernelHost.declare(vararg variables: VariableDeclaration) = declare(variables.toList()) fun KotlinKernelHost.declare(vararg variables: Pair<VariableName, Any?>) = declare(variables.map { VariableDeclaration(it.first, it.second) })
apache-2.0
3f3dc011904b07b9d420c8ffd9760701
28.566667
142
0.718151
4.607792
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepic/droid/adaptive/util/RatingNamesGenerator.kt
2
1700
package org.stepic.droid.adaptive.util import android.content.Context import org.stepic.droid.R import org.stepic.droid.di.AppSingleton import org.stepic.droid.preferences.SharedPreferenceHelper import javax.inject.Inject @AppSingleton class RatingNamesGenerator @Inject constructor( private val context: Context, private val sharedPreferenceHelper: SharedPreferenceHelper ) { private val animalsMale by lazy { context.resources.getStringArray(R.array.animals_m) } private val animalsFemale by lazy { context.resources.getStringArray(R.array.animals_f) } private val animals by lazy { animalsMale + animalsFemale } private val adjectives by lazy { context.resources.getStringArray(R.array.adjectives) } private val adjectivesFemale by lazy { context.resources.getStringArray(R.array.adjectives_female) } fun getName(user: Long) : String = if (user == sharedPreferenceHelper.profile?.id) { context.getString(R.string.adaptive_rating_you_placeholder) } else { val hash = hash(user) val animal = animals[(hash % animals.size).toInt()] val adjIndex = (hash / animals.size).toInt() val adj = if (isFemaleNoun(animal)) { adjectivesFemale[adjIndex] } else { adjectives[adjIndex] } adj.capitalize() + ' ' + animal } private fun isFemaleNoun(noun: String) = animalsFemale.contains(noun) private fun hash(x: Long): Long { var h = x h = h.shr(16).xor(h) * 0x45d9f3b h = h.shr(16).xor(h) * 0x45d9f3b h = h.shr(16).xor(h) return h % (animals.size * adjectives.size) } }
apache-2.0
c2dad6a40662d59abbe27a42d9844893
33.714286
104
0.662941
3.971963
false
false
false
false
da1z/intellij-community
python/src/com/jetbrains/python/sdk/PySdkSettings.kt
1
3663
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.sdk import com.intellij.application.options.ReplacePathToMacroMap import com.intellij.openapi.components.* import com.intellij.openapi.util.io.FileUtil import com.intellij.util.PathUtil import com.intellij.util.SystemProperties import com.intellij.util.xmlb.XmlSerializerUtil import com.jetbrains.python.sdk.flavors.VirtualEnvSdkFlavor import org.jetbrains.annotations.SystemIndependent import org.jetbrains.jps.model.serialization.PathMacroUtil /** * @author vlan */ @State(name = "PySdkSettings", storages = arrayOf(Storage(value = "py_sdk_settings.xml", roamingType = RoamingType.DISABLED))) class PySdkSettings : PersistentStateComponent<PySdkSettings.State> { companion object { @JvmStatic val instance: PySdkSettings = ServiceManager.getService(PySdkSettings::class.java) private const val VIRTUALENV_ROOT_DIR_MACRO_NAME = "VIRTUALENV_ROOT_DIR" } private val state: State = State() var useNewEnvironmentForNewProject: Boolean get() = state.USE_NEW_ENVIRONMENT_FOR_NEW_PROJECT set(value) { state.USE_NEW_ENVIRONMENT_FOR_NEW_PROJECT = value } var preferredEnvironmentType: String? get() = state.PREFERRED_ENVIRONMENT_TYPE set(value) { state.PREFERRED_ENVIRONMENT_TYPE = value } var preferredVirtualEnvBaseSdk: String? get() = state.PREFERRED_VIRTUALENV_BASE_SDK set(value) { state.PREFERRED_VIRTUALENV_BASE_SDK = value } fun setPreferredVirtualEnvBasePath(value: @SystemIndependent String, projectPath: @SystemIndependent String) { val pathMap = ReplacePathToMacroMap().apply { addMacroReplacement(projectPath, PathMacroUtil.PROJECT_DIR_MACRO_NAME) addMacroReplacement(defaultVirtualEnvRoot, VIRTUALENV_ROOT_DIR_MACRO_NAME) } val pathToSave = when { FileUtil.isAncestor(projectPath, value, true) -> value.trimEnd { !it.isLetter() } else -> PathUtil.getParentPath(value) } state.PREFERRED_VIRTUALENV_BASE_PATH = pathMap.substitute(pathToSave, true) } fun getPreferredVirtualEnvBasePath(projectPath: @SystemIndependent String): @SystemIndependent String { val pathMap = ExpandMacroToPathMap().apply { addMacroExpand(PathMacroUtil.PROJECT_DIR_MACRO_NAME, projectPath) addMacroExpand(VIRTUALENV_ROOT_DIR_MACRO_NAME, defaultVirtualEnvRoot) } val defaultPath = when { defaultVirtualEnvRoot != userHome -> defaultVirtualEnvRoot else -> "$${PathMacroUtil.PROJECT_DIR_MACRO_NAME}$/venv" } val rawSavedPath = state.PREFERRED_VIRTUALENV_BASE_PATH ?: defaultPath val savedPath = pathMap.substitute(rawSavedPath, true) return when { FileUtil.isAncestor(projectPath, savedPath, true) -> savedPath else -> "$savedPath/${PathUtil.getFileName(projectPath)}" } } override fun getState() = state override fun loadState(state: PySdkSettings.State) { XmlSerializerUtil.copyBean(state, this.state) } @Suppress("PropertyName") class State { @JvmField var USE_NEW_ENVIRONMENT_FOR_NEW_PROJECT: Boolean = false @JvmField var PREFERRED_ENVIRONMENT_TYPE: String? = null @JvmField var PREFERRED_VIRTUALENV_BASE_PATH: String? = null @JvmField var PREFERRED_VIRTUALENV_BASE_SDK: String? = null } private val defaultVirtualEnvRoot: @SystemIndependent String get() = VirtualEnvSdkFlavor.getDefaultLocation()?.path ?: userHome private val userHome: @SystemIndependent String get() = FileUtil.toSystemIndependentName(SystemProperties.getUserHome()) }
apache-2.0
ca869908fb032ca133cf767d1df61859
36.387755
140
0.746656
4.483476
false
false
false
false
garmax1/material-flashlight
app/src/main/java/co/garmax/materialflashlight/ui/main/MainFragment.kt
1
9032
package co.garmax.materialflashlight.ui.main import android.animation.ArgbEvaluator import android.animation.ValueAnimator import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.ColorRes import androidx.core.content.ContextCompat import androidx.vectordrawable.graphics.drawable.AnimatedVectorDrawableCompat import co.garmax.materialflashlight.BuildConfig import co.garmax.materialflashlight.R import co.garmax.materialflashlight.databinding.FragmentMainBinding import co.garmax.materialflashlight.extensions.observeNotNull import co.garmax.materialflashlight.features.modes.ModeBase.Mode import co.garmax.materialflashlight.features.modules.ModuleBase.Module import co.garmax.materialflashlight.service.ForegroundService import co.garmax.materialflashlight.ui.BaseFragment import org.koin.androidx.viewmodel.ext.android.viewModel import timber.log.Timber class MainFragment : BaseFragment() { private val viewModel by viewModel<MainViewModel>() private val binding get() = _binding!! private var _binding: FragmentMainBinding? = null private var animatedDrawableDay: AnimatedVectorDrawableCompat? = null private var animatedDrawableNight: AnimatedVectorDrawableCompat? = null private var backgroundColorAnimation: ValueAnimator? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentMainBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupLayout(savedInstanceState) setupViewModel() } private fun setupLayout(savedInstanceState: Bundle?) { animatedDrawableDay = AnimatedVectorDrawableCompat.create(requireContext(), R.drawable.avc_appbar_day) animatedDrawableNight = AnimatedVectorDrawableCompat.create(requireContext(), R.drawable.avc_appbar_night) with(binding) { fab.setOnClickListener { if (viewModel.isLightTurnedOn) { ForegroundService.stopService(requireContext()) } else { ForegroundService.startService(requireContext()) } } layoutKeepScreenOn.setOnClickListener { binding.switchKeepScreenOn.toggle() } layoutAutoTurnOn.setOnClickListener { binding.switchAutoTurnOn.toggle() } layoutContent.setBackgroundColor( ContextCompat.getColor( requireContext(), if (viewModel.isLightTurnedOn) R.color.green else R.color.colorPrimaryLight ) ) if (savedInstanceState == null) { // Set module when (viewModel.lightModule) { Module.MODULE_CAMERA_FLASHLIGHT -> radioCameraFlashlight.isChecked = true Module.MODULE_SCREEN -> radioScreen.isChecked = true } when (viewModel.lightMode) { Mode.MODE_INTERVAL_STROBE -> radioIntervalStrobe.isChecked = true Mode.MODE_TORCH -> radioTorch.isChecked = true Mode.MODE_SOUND_STROBE -> radioSoundStrobe.isChecked = true Mode.MODE_SOS -> radioSos.isChecked = true } intervalStrobeOn.setText(viewModel.strobeOnPeriod.toString()) intervalStrobeOff.setText(viewModel.strobeOffPeriod.toString()) } else { setState(viewModel.isLightTurnedOn, false) } intervalStrobeTiming.visibility = if (radioIntervalStrobe.isChecked) View.VISIBLE else View.GONE switchKeepScreenOn.isChecked = viewModel.isKeepScreenOn fab.keepScreenOn = viewModel.isKeepScreenOn switchAutoTurnOn.isChecked = viewModel.isAutoTurnedOn radioSoundStrobe.setOnCheckedChangeListener { _, isChecked -> if (isChecked) viewModel.setMode(Mode.MODE_SOUND_STROBE) } radioIntervalStrobe.setOnCheckedChangeListener { _, isChecked -> if (isChecked) { viewModel.setMode(Mode.MODE_INTERVAL_STROBE) intervalStrobeTiming.visibility = View.VISIBLE } else { intervalStrobeTiming.visibility = View.GONE } } radioTorch.setOnCheckedChangeListener { _, isChecked -> if (isChecked) viewModel.setMode(Mode.MODE_TORCH) } radioSos.setOnCheckedChangeListener { _, isChecked -> if (isChecked) viewModel.setMode(Mode.MODE_SOS) } radioCameraFlashlight.setOnCheckedChangeListener { _, isChecked -> if (isChecked) viewModel.setModule(Module.MODULE_CAMERA_FLASHLIGHT) } radioScreen.setOnCheckedChangeListener { _, isChecked -> if (isChecked) viewModel.setModule(Module.MODULE_SCREEN) } switchKeepScreenOn.setOnCheckedChangeListener { _, isChecked -> viewModel.isKeepScreenOn = isChecked fab.keepScreenOn = isChecked } switchAutoTurnOn.setOnCheckedChangeListener { _, isChecked -> viewModel.isAutoTurnedOn = isChecked } val textWatcherObject = object: TextWatcher { override fun afterTextChanged(p0: Editable?) {} override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {} override fun onTextChanged(p0: CharSequence?, start: Int, before: Int, count: Int) { val strobeOnString = intervalStrobeOn.text.toString() val strobeOn = if (strobeOnString == "") 0 else Integer.parseInt(strobeOnString) val strobeOffString = intervalStrobeOff.text.toString() val strobeOff = if (strobeOffString == "") 0 else Integer.parseInt(strobeOffString) viewModel.setStrobePeriod(strobeOn, strobeOff) } } intervalStrobeOn.addTextChangedListener(textWatcherObject) intervalStrobeOff.addTextChangedListener(textWatcherObject) textVersion.text = getString(R.string.text_version, BuildConfig.VERSION_NAME) } } private fun setupViewModel() { // Handle toggle of the light observeNotNull(viewModel.liveDataLightToggle) { setState(it, true) } } private fun setState(isLightOn: Boolean, animated: Boolean) { Timber.d("Light toggle %s, animated %s", isLightOn, animated) with(binding) { if (isLightOn) { // Fab image fab.setImageResource(R.drawable.ic_power_on) // Appbar image if (animated) { imageAppbar.setImageDrawable(animatedDrawableDay) animatedDrawableDay?.start() animateBackground(R.color.colorPrimaryLight, R.color.green) } else { imageAppbar.setImageResource(R.drawable.vc_appbar_day) layoutContent.setBackgroundResource(R.color.green) } } else { // Fab image fab.setImageResource(R.drawable.ic_power_off) // Appbar image if (animated) { imageAppbar.setImageDrawable(animatedDrawableNight) animatedDrawableNight?.start() animateBackground(R.color.green, R.color.colorPrimaryLight) } else { imageAppbar.setImageResource(R.drawable.vc_appbar_night) layoutContent.setBackgroundResource(R.color.colorPrimaryLight) } } } } private fun animateBackground(@ColorRes fromColorResId: Int, @ColorRes toColorResId: Int) { val colorFrom: Int = ContextCompat.getColor(requireContext(), fromColorResId) val colorTo: Int = ContextCompat.getColor(requireContext(), toColorResId) if (backgroundColorAnimation?.isRunning == true) { backgroundColorAnimation?.cancel() } backgroundColorAnimation = ValueAnimator.ofObject(ArgbEvaluator(), colorFrom, colorTo).apply { duration = resources.getInteger(R.integer.animation_time).toLong() addUpdateListener { animator: ValueAnimator -> binding.layoutContent.setBackgroundColor( animator.animatedValue as Int ) } start() } } }
apache-2.0
d69411bd5eacdf83afdd0a30201df846
39.873303
103
0.625443
5.673367
false
false
false
false
sn3d/nomic
nomic-hive/src/main/kotlin/nomic/hive/adapter/JdbcHiveAdapter.kt
1
5019
/* * Copyright 2017 [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 nomic.hive.adapter import com.github.mustachejava.DefaultMustacheFactory import nomic.hive.InvalidHiveQueryException import java.io.Reader import java.io.StringReader import java.io.StringWriter import java.sql.Connection import java.sql.DriverManager /** * This implementation of [HiveAdapter] use JDBC for connecting to * HIVE instance. For placeholder replacing is used Mustache as * template engine * * @author [email protected] */ class JdbcHiveAdapter(jdbcUrl: String, username: String, password: String) : HiveAdapter { /// ref to JDBC connections private val connection: Connection; /// ref to Mustache template engine private val mustache: DefaultMustacheFactory; /** * initialize and create connection to Hive */ init { Class.forName("org.apache.hive.jdbc.HiveDriver"); connection = DriverManager.getConnection(jdbcUrl, username, password) mustache = DefaultMustacheFactory() } //------------------------------------------------------------------------------------------------- // implemented functions //------------------------------------------------------------------------------------------------- /** * parse script to queries,replace placeholders with fields, and execute these * queries. */ override fun exec(script: Reader, fields: Map<String, Any>):Boolean { val replacedScript = replacePlaceholders(script, fields) return exec(replacedScript) } /** * parse script to queries and execute them */ override fun exec(script: Reader):Boolean { val filteredScript = removeComments(script) val queries = splitSemiColon(filteredScript.readText()); var allRes = true; for (query: String in queries) { var res = exec(query) if (!res) { allRes = false; } } return allRes; } /** * parse string to queries,replace placeholders with fields, and execute these * queries. */ override fun exec(query: String, fields: Map<String, Any>):Boolean { val replacedQuery = replacePlaceholders(StringReader(query), fields).readText() return exec(replacedQuery) } /** * parse string to queries and execute them */ override fun exec(query: String):Boolean { val trimmed = query.trim() if (!trimmed.isBlank()) { try { val stmt = connection.prepareStatement(trimmed) return stmt.execute(); } catch (e: Exception) { throw InvalidHiveQueryException(trimmed, e) } } return true; } //------------------------------------------------------------------------------------------------- // private functions //------------------------------------------------------------------------------------------------- private fun replacePlaceholders(script: Reader, fields:Map<String, Any>): Reader { val sm = "${'$'}{" val em = "}" val template = mustache.compile(script, "", sm, em); val result = StringWriter() template.execute(result, fields) return result.toString().reader() } /** * remove lines starting with '--' */ private fun removeComments(query: Reader): Reader = query.readLines() .filter { line -> !line.startsWith("--") } .reduce {a, b -> a + " " + b } .reader() /** * "stolen" from HIVE CLI (https://github.com/apache/hive/blob/master/cli/src/java/org/apache/hadoop/hive/cli/CliDriver.java#428) * but I need exactly this functionality to keep it compatible. */ private fun splitSemiColon(line: String): List<String> { var insideSingleQuote = false var insideDoubleQuote = false var escape = false var beginIndex = 0 val ret:MutableList<String> = mutableListOf() for (index in 0..line.length - 1) { if (line[index] == '\'') { // take a look to see if it is escaped if (!escape) { // flip the boolean variable insideSingleQuote = !insideSingleQuote } } else if (line[index] == '\"') { // take a look to see if it is escaped if (!escape) { // flip the boolean variable insideDoubleQuote = !insideDoubleQuote } } else if (line[index] == ';') { if (insideSingleQuote || insideDoubleQuote) { // do not split } else { // split, do not include ; itself ret.add(line.substring(beginIndex, index)) beginIndex = index + 1 } } else { // nothing to do } // set the escape if (escape) { escape = false } else if (line[index] == '\\') { escape = true } } ret.add(line.substring(beginIndex)) return ret } }
apache-2.0
41c6c89cec763456357a3de77b4b502d
27.044693
130
0.629607
3.93956
false
false
false
false
bluelinelabs/Conductor
demo/src/main/java/com/bluelinelabs/conductor/demo/controllers/AutodisposeController.kt
1
3721
package com.bluelinelabs.conductor.demo.controllers import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.bluelinelabs.conductor.Controller import com.bluelinelabs.conductor.RouterTransaction.Companion.with import com.bluelinelabs.conductor.autodispose.ControllerScopeProvider import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler import com.bluelinelabs.conductor.demo.R import com.bluelinelabs.conductor.demo.ToolbarProvider import com.bluelinelabs.conductor.demo.controllers.base.watchForLeaks import com.bluelinelabs.conductor.demo.databinding.ControllerLifecycleBinding import com.uber.autodispose.autoDisposable import io.reactivex.Observable import java.util.concurrent.TimeUnit // Shamelessly borrowed from the official RxLifecycle demo by Trello and adapted for Conductor Controllers // instead of Activities or Fragments. class AutodisposeController : Controller() { private val scopeProvider = ControllerScopeProvider.from(this) init { watchForLeaks() Observable.interval(1, TimeUnit.SECONDS) .doOnDispose { Log.i(TAG, "Disposing from constructor") } .autoDisposable(scopeProvider) .subscribe { num: Long -> Log.i(TAG, "Started in constructor, running until onDestroy(): $num") } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle? ): View { Log.i(TAG, "onCreateView() called") val binding = ControllerLifecycleBinding.inflate(inflater, container, false) binding.title.text = binding.root.resources.getString(R.string.rxlifecycle_title, TAG) binding.nextReleaseView.setOnClickListener { retainViewMode = RetainViewMode.RELEASE_DETACH router.pushController( with(TextController("Logcat should now report that the observables from onAttach() and onViewBound() have been disposed of, while the constructor observable is still running.")) .pushChangeHandler(HorizontalChangeHandler()) .popChangeHandler(HorizontalChangeHandler()) ) } binding.nextRetainView.setOnClickListener { retainViewMode = RetainViewMode.RETAIN_DETACH router.pushController( with(TextController("Logcat should now report that the observables from onAttach() has been disposed of, while the constructor and onViewBound() observables are still running.")) .pushChangeHandler(HorizontalChangeHandler()) .popChangeHandler(HorizontalChangeHandler()) ) } Observable.interval(1, TimeUnit.SECONDS) .doOnDispose { Log.i(TAG, "Disposing from onCreateView()") } .autoDisposable(scopeProvider) .subscribe { num: Long -> Log.i(TAG, "Started in onCreateView(), running until onDestroyView(): $num") } return binding.root } override fun onAttach(view: View) { super.onAttach(view) Log.i(TAG, "onAttach() called") (activity as ToolbarProvider).toolbar.title = "Autodispose Demo" Observable.interval(1, TimeUnit.SECONDS) .doOnDispose { Log.i(TAG, "Disposing from onAttach()") } .autoDisposable(scopeProvider) .subscribe { num: Long -> Log.i(TAG, "Started in onAttach(), running until onDetach(): $num") } } override fun onDestroyView(view: View) { super.onDestroyView(view) Log.i(TAG, "onDestroyView() called") } override fun onDetach(view: View) { super.onDetach(view) Log.i(TAG, "onDetach() called") } public override fun onDestroy() { super.onDestroy() Log.i(TAG, "onDestroy() called") } companion object { private const val TAG = "AutodisposeController" } }
apache-2.0
b8dd7061e5f28086dd278b9613fd3ded
34.788462
186
0.735017
4.645443
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/reader/repository/usecases/GetDiscoverCardsUseCase.kt
1
4037
package org.wordpress.android.ui.reader.repository.usecases import dagger.Reusable import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.withContext import org.wordpress.android.datasets.ReaderBlogTableWrapper import org.wordpress.android.datasets.ReaderDiscoverCardsTableWrapper import org.wordpress.android.datasets.wrappers.ReaderPostTableWrapper import org.wordpress.android.fluxc.utils.AppLogWrapper import org.wordpress.android.models.discover.ReaderDiscoverCard import org.wordpress.android.models.discover.ReaderDiscoverCard.InterestsYouMayLikeCard import org.wordpress.android.models.discover.ReaderDiscoverCard.ReaderPostCard import org.wordpress.android.models.discover.ReaderDiscoverCard.ReaderRecommendedBlogsCard import org.wordpress.android.models.discover.ReaderDiscoverCard.WelcomeBannerCard import org.wordpress.android.models.discover.ReaderDiscoverCards import org.wordpress.android.modules.IO_THREAD import org.wordpress.android.ui.prefs.AppPrefsWrapper import org.wordpress.android.ui.reader.ReaderConstants import org.wordpress.android.util.AppLog.T.READER import javax.inject.Inject import javax.inject.Named @Reusable class GetDiscoverCardsUseCase @Inject constructor( private val parseDiscoverCardsJsonUseCase: ParseDiscoverCardsJsonUseCase, private val readerDiscoverCardsTableWrapper: ReaderDiscoverCardsTableWrapper, private val readerPostTableWrapper: ReaderPostTableWrapper, private val readerBlogTableWrapper: ReaderBlogTableWrapper, private val appLogWrapper: AppLogWrapper, private val appPrefsWrapper: AppPrefsWrapper, @Named(IO_THREAD) private val ioDispatcher: CoroutineDispatcher ) { suspend fun get(): ReaderDiscoverCards = withContext(ioDispatcher) { val cardJsonList = readerDiscoverCardsTableWrapper.loadDiscoverCardsJsons() val cards: ArrayList<ReaderDiscoverCard> = arrayListOf() if (cardJsonList.isNotEmpty()) { val jsonObjects = parseDiscoverCardsJsonUseCase.convertListOfJsonArraysIntoSingleJsonArray( cardJsonList ) forLoop@ for (i in 0 until jsonObjects.length()) { val cardJson = jsonObjects.getJSONObject(i) when (cardJson.getString(ReaderConstants.JSON_CARD_TYPE)) { ReaderConstants.JSON_CARD_INTERESTS_YOU_MAY_LIKE -> { val interests = parseDiscoverCardsJsonUseCase.parseInterestCard(cardJson) cards.add(InterestsYouMayLikeCard(interests)) } ReaderConstants.JSON_CARD_POST -> { // TODO we might want to load the data in batch val (blogId, postId) = parseDiscoverCardsJsonUseCase.parseSimplifiedPostCard(cardJson) val post = readerPostTableWrapper.getBlogPost(blogId, postId, false) if (post != null) { cards.add(ReaderPostCard(post)) } else { appLogWrapper.d(READER, "Post from /cards json not found in ReaderDatabase") continue@forLoop } } ReaderConstants.JSON_CARD_RECOMMENDED_BLOGS -> { cardJson?.let { val recommendedBlogs = parseDiscoverCardsJsonUseCase.parseSimplifiedRecommendedBlogsCard(it) .mapNotNull { (blogId, feedId) -> readerBlogTableWrapper.getReaderBlog(blogId, feedId) } cards.add(ReaderRecommendedBlogsCard(recommendedBlogs)) } } } } if (cards.isNotEmpty() && !appPrefsWrapper.readerDiscoverWelcomeBannerShown) { cards.add(0, WelcomeBannerCard) } } return@withContext ReaderDiscoverCards(cards) } }
gpl-2.0
f4f66a06810c582fddb7c791980acdb9
50.75641
120
0.670547
5.591413
false
false
false
false
benjamin-bader/thrifty
thrifty-schema/src/main/kotlin/com/microsoft/thrifty/schema/ListType.kt
1
2453
/* * Thrifty * * Copyright (c) Microsoft Corporation * * 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 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING * WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, * FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ package com.microsoft.thrifty.schema /** * Represents a Thrift `list<T>`. * * @property elementType The type of value contained within lists of this type. */ class ListType internal constructor( val elementType: ThriftType, override val annotations: Map<String, String> = emptyMap() ) : ThriftType("list<" + elementType.name + ">") { override val isList: Boolean = true override fun <T> accept(visitor: ThriftType.Visitor<T>): T = visitor.visitList(this) override fun withAnnotations(annotations: Map<String, String>): ThriftType { return ListType(elementType, mergeAnnotations(this.annotations, annotations)) } /** * Creates a [Builder] initialized with this type's values. */ fun toBuilder(): Builder { return Builder(this) } /** * An object that can build new [ListType] instances. */ class Builder( private var elementType: ThriftType, private var annotations: Map<String, String> ) { internal constructor(type: ListType) : this(type.elementType, type.annotations) /** * Use the given [elementType] for the [ListType] under construction. */ fun elementType(elementType: ThriftType): Builder = apply { this.elementType = elementType } /** * Use the given [annotations] for the [ListType] under construction. */ fun annotations(annotations: Map<String, String>): Builder = apply { this.annotations = annotations } /** * Creates a new [ListType] instance. */ fun build(): ListType { return ListType(elementType, annotations) } } }
apache-2.0
af9a0732ea5421b164a3ae5d82a0a8b5
30.050633
116
0.651447
4.628302
false
false
false
false
ingokegel/intellij-community
plugins/settings-sync/src/com/intellij/settingsSync/plugins/SettingsSyncPluginManager.kt
5
6118
package com.intellij.settingsSync.plugins import com.intellij.ide.ApplicationInitializedListener import com.intellij.ide.plugins.IdeaPluginDescriptor import com.intellij.ide.plugins.PluginStateListener import com.intellij.ide.plugins.PluginStateManager import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.* import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.PluginId import com.intellij.settingsSync.SettingsSyncSettings import com.intellij.settingsSync.config.BUNDLED_PLUGINS_ID import com.intellij.settingsSync.plugins.SettingsSyncPluginManager.Companion.FILE_SPEC import org.jetbrains.annotations.TestOnly @State(name = "SettingsSyncPlugins", storages = [Storage(FILE_SPEC)]) internal class SettingsSyncPluginManager : PersistentStateComponent<SettingsSyncPluginManager.SyncPluginsState>, Disposable { internal companion object { fun getInstance(): SettingsSyncPluginManager = ApplicationManager.getApplication().getService(SettingsSyncPluginManager::class.java) const val FILE_SPEC = "settingsSyncPlugins.xml" val LOG = logger<SettingsSyncPluginManager>() } private val pluginStateListener = object : PluginStateListener { override fun install(descriptor: IdeaPluginDescriptor) { sessionUninstalledPlugins.remove(descriptor.pluginId.idString) } override fun uninstall(descriptor: IdeaPluginDescriptor) { val idString = descriptor.pluginId.idString state.plugins[idString]?.let { it.isEnabled = false } sessionUninstalledPlugins.add(idString) } } init { PluginStateManager.addStateListener(pluginStateListener) } private var state = SyncPluginsState() private var noUpdateFromIde: Boolean = false private val sessionUninstalledPlugins = HashSet<String>() override fun getState(): SyncPluginsState { updateStateFromIde() return state } override fun loadState(state: SyncPluginsState) { this.state = state } @TestOnly fun clearState() { state.plugins.clear() } class SyncPluginsState : BaseState() { var plugins by map<String, PluginData>() } class PluginData : BaseState() { var isEnabled by property(true) var dependencies by stringSet() var category by enum(SettingsCategory.PLUGINS) } private fun updateStateFromIde() { if (noUpdateFromIde) return PluginManagerProxy.getInstance().getPlugins().forEach { val idString = it.pluginId.idString if (shouldSaveState(it)) { var pluginData = state.plugins[idString] if (pluginData == null) { pluginData = PluginData() pluginData.category = SettingsSyncPluginCategoryFinder.getPluginCategory(it) it.dependencies.forEach { dependency -> if (!dependency.isOptional) { pluginData.dependencies.add(dependency.pluginId.idString) pluginData.intIncrementModificationCount() } } state.plugins[idString] = pluginData } pluginData.isEnabled = it.isEnabled && !sessionUninstalledPlugins.contains(idString) } else { if (state.plugins.containsKey(idString)) { state.plugins.remove(idString) } } } } fun pushChangesToIde() { val pluginManagerProxy = PluginManagerProxy.getInstance() val installer = pluginManagerProxy.createInstaller() this.state.plugins.forEach { mapEntry -> val plugin = findPlugin(mapEntry.key) if (plugin != null) { if (isPluginSyncEnabled(plugin.pluginId.idString, plugin.isBundled, SettingsSyncPluginCategoryFinder.getPluginCategory(plugin))) { if (mapEntry.value.isEnabled != plugin.isEnabled) { if (mapEntry.value.isEnabled) { pluginManagerProxy.enablePlugin(plugin.pluginId) LOG.info("Disabled plugin: ${plugin.pluginId.idString}") } else { pluginManagerProxy.disablePlugin(plugin.pluginId) LOG.info("Enabled plugin: ${plugin.pluginId.idString}") } } } } else { if (mapEntry.value.isEnabled && isPluginSyncEnabled(mapEntry.key, false, mapEntry.value.category) && checkDependencies(mapEntry.key, mapEntry.value)) { val newPluginId = PluginId.getId(mapEntry.key) installer.addPluginId(newPluginId) LOG.info("New plugin installation requested: ${newPluginId.idString}") } } } installer.installPlugins() } private fun findPlugin(idString: String): IdeaPluginDescriptor? { return PluginId.findId(idString)?.let { PluginManagerProxy.getInstance().findPlugin(it) } } private fun checkDependencies(idString: String, pluginState: PluginData): Boolean { pluginState.dependencies.forEach { if (findPlugin(it) == null) { LOG.info("Skipping ${idString} plugin installation due to missing dependency: ${it}") return false } } return true } fun doWithNoUpdateFromIde(runnable: Runnable) { noUpdateFromIde = true try { runnable.run() } finally { noUpdateFromIde = false } } private fun shouldSaveState(plugin: IdeaPluginDescriptor): Boolean { return isPluginSyncEnabled(plugin.pluginId.idString, plugin.isBundled, SettingsSyncPluginCategoryFinder.getPluginCategory(plugin)) && (!plugin.isBundled || !plugin.isEnabled || state.plugins.containsKey(plugin.pluginId.idString)) } private fun isPluginSyncEnabled(idString: String, isBundled: Boolean, category: SettingsCategory): Boolean { val settings = SettingsSyncSettings.getInstance() return settings.isCategoryEnabled(category) && (category != SettingsCategory.PLUGINS || isBundled && settings.isSubcategoryEnabled(SettingsCategory.PLUGINS, BUNDLED_PLUGINS_ID) || settings.isSubcategoryEnabled(SettingsCategory.PLUGINS, idString)) } override fun dispose() { PluginStateManager.removeStateListener(pluginStateListener) } }
apache-2.0
a0f2438ef565f2932a3ec7b4169adb6c
33.965714
138
0.709709
4.986145
false
false
false
false
kelsos/mbrc
app/src/main/kotlin/com/kelsos/mbrc/commands/model/UpdateNowPlayingTrack.kt
1
1945
package com.kelsos.mbrc.commands.model import android.app.Application import com.fasterxml.jackson.databind.node.ObjectNode import com.kelsos.mbrc.di.modules.AppDispatchers import com.kelsos.mbrc.domain.TrackInfo import com.kelsos.mbrc.events.bus.RxBus import com.kelsos.mbrc.events.ui.RemoteClientMetaData import com.kelsos.mbrc.events.ui.TrackInfoChangeEvent import com.kelsos.mbrc.interfaces.ICommand import com.kelsos.mbrc.interfaces.IEvent import com.kelsos.mbrc.model.MainDataModel import com.kelsos.mbrc.repository.ModelCache import com.kelsos.mbrc.widgets.UpdateWidgets import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch import timber.log.Timber import javax.inject.Inject class UpdateNowPlayingTrack @Inject constructor( private val model: MainDataModel, private val context: Application, private val bus: RxBus, private val cache: ModelCache, dispatchers: AppDispatchers ) : ICommand { private val job = SupervisorJob() private val scope = CoroutineScope(job + dispatchers.io) override fun execute(e: IEvent) { val node = e.data as ObjectNode val artist = node.path("artist").textValue() val album = node.path("album").textValue() val title = node.path("title").textValue() val year = node.path("year").textValue() val path = node.path("path").textValue() model.trackInfo = TrackInfo(artist, title, album, year, path) save(model.trackInfo) bus.post(RemoteClientMetaData(model.trackInfo, model.coverPath, model.duration)) bus.post(TrackInfoChangeEvent(model.trackInfo)) UpdateWidgets.updateTrackInfo(context, model.trackInfo) } private fun save(info: TrackInfo) { scope.launch { try { cache.persistInfo(info) Timber.v("Playing track info successfully persisted") } catch (e: Exception) { Timber.v(e, "Failed to persist the playing track info") } } } }
gpl-3.0
41d714f7a4e9553ba8b94140d079a8a6
32.534483
84
0.756298
4.03527
false
false
false
false
DanielGrech/anko
preview/robowrapper/src/org/jetbrains/kotlin/android/robowrapper/ClassLoaderManager.kt
3
3161
/* * Copyright 2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.android.robowrapper import org.robolectric.internal.bytecode.InstrumentingClassLoader import java.lang.reflect.Field import java.net.URL import java.net.URLClassLoader public class ClassLoaderManager { public fun replaceClassLoader(packageName: String) { // Context ClassLoader is set in RobolectricTestRunner val currentClassLoader = Thread.currentThread().getContextClassLoader() if (currentClassLoader !is InstrumentingClassLoader) { throw RuntimeException("Not an InstrumentingClassLoader") } val parentClassLoader = Thread.currentThread().getContextClassLoader().getParent() val asmClazz = parentClassLoader.loadClass("org.robolectric.internal.bytecode.InstrumentingClassLoader") val configField = asmClazz.getDeclaredField("config") val urlsField = asmClazz.getDeclaredField("urls") val classesField = asmClazz.getDeclaredField("classes") configField.setAccessible(true) urlsField.setAccessible(true) classesField.setAccessible(true) val setup = configField.get(currentClassLoader) val urlClassLoader = urlsField.get(currentClassLoader) as URLClassLoader @suppress("UNCHECKED_CAST") val oldClasses = classesField.get(currentClassLoader) as Map<String, Class<Any>> val urls = urlClassLoader.getURLs() // Create new ClassLoader instance val newClassLoader = asmClazz.getConstructors()[0].newInstance(setup, urls) as InstrumentingClassLoader // Copy all Map entries from the old AsmInstrumentingClassLoader @suppress("UNCHECKED_CAST") val classes = classesField.get(newClassLoader) as MutableMap<String, Class<Any>> replicateCache(packageName, oldClasses, classes) // We're now able to get newClassLoader using Thread.currentThread().getContextClassLoader() Thread.currentThread().setContextClassLoader(newClassLoader) System.gc() } private fun replicateCache( removePackage: String, oldClasses: Map<String, Class<Any>>, newClasses: MutableMap<String, Class<Any>> ) { if (removePackage.isEmpty()) return val oldClassesList = oldClasses.toList() val checkPackageName = removePackage.isNotEmpty() for (clazz in oldClassesList) { val key = clazz.first if (checkPackageName && !key.startsWith(removePackage)) { newClasses.put(key, clazz.second) } } } }
apache-2.0
b245c5d17643eb6e5ea1b61fb91a9700
37.54878
112
0.705789
5.001582
false
false
false
false
WeltN24/WidgetAdapter
library/src/main/java/de/welt/widgetadapter/WidgetAdapter.kt
1
3666
package de.welt.widgetadapter import android.support.v7.util.DiffUtil import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import java.util.* open class WidgetAdapter( val layoutInflater: LayoutInflater ) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { var supportsCollapsableGroups: Boolean = false var widgetProviders = LinkedHashMap<Class<out Any>, () -> Widget<*>>() private var allItems = listOf<Any>() private var visibleItems = listOf<Any>() inline fun <reified T : Any> addWidget(noinline widgetProvider: () -> Widget<T>) { widgetProviders[T::class.java] = widgetProvider } fun setItems(items: List<Any>) { doSetItems(items) notifyDataSetChanged() } fun getItems() = allItems fun updateItems(items: List<Any>) { val oldItems = this.visibleItems doSetItems(items) DiffUtil.calculateDiff(SimpleDiffCallback(this.visibleItems, oldItems)) .dispatchUpdatesTo(this) } fun swapItems(fromPosition: Int, toPosition: Int) { if (supportsCollapsableGroups) throw UnsupportedOperationException("swapping items on adapters that support collapsable groups is not supported yet. Please raise an issue if you need this feature: https://github.com/WeltN24/WidgetAdapter/issues") Collections.swap(visibleItems, fromPosition, toPosition) notifyItemMoved(fromPosition, toPosition) } override fun getItemCount() = visibleItems.size override fun getItemViewType(position: Int) = widgetProviders.keys.indexOf(visibleItems[position].javaClass) override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { bindViewHolder(holder, visibleItems[position]) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val provider = widgetProviders.values.elementAt(viewType) val widget = provider() return WidgetViewHolder(widget, widget.createView(layoutInflater, parent)) } override fun onViewRecycled(holder: RecyclerView.ViewHolder) { super.onViewRecycled(holder) val viewHolder = holder as WidgetViewHolder<*> viewHolder.widget.onViewRecycled() } private fun doSetItems(items: List<Any>) { allItems = items visibleItems = if (supportsCollapsableGroups) items.visibleItems else items } private val List<Any>.visibleItems: List<Any> get() { if (widgetProviders.isEmpty()) throw IllegalStateException("You have to add widget providers before you set items.") return if (supportsCollapsableGroups) applyCollapsedState() else filter { widgetProviders.contains(it.javaClass) } } private fun List<Any>.applyCollapsedState(): List<Any> { val collapsedGroups = this .filterIsInstance<CollapsableGroupHeaderWidgetData>() .filter { it.isCollapsed } .map { it.collapsableGroupId } return this.filter { widgetProviders.contains(it.javaClass) && it.isNotCollapsed(collapsedGroups) } } private fun Any.isNotCollapsed(collapsedGroups: List<String>): Boolean { val id = (this as? CollapsableWidgetData)?.collapsableGroupId ?: return true return !collapsedGroups.contains(id) } @Suppress("UNCHECKED_CAST") private fun <T> bindViewHolder(holder: RecyclerView.ViewHolder, item: T) { (holder as WidgetViewHolder<T>).widget.apply { setData(item as T) onViewBound() } } }
mit
3dbac46007dbf318f9a03de96e78ed05
35.66
254
0.688489
4.914209
false
false
false
false
andgate/Ikou
core/src/com/andgate/ikou/actor/player/PlayerActor.kt
1
2257
package com.andgate.ikou.actor.player; import com.andgate.ikou.actor.Actor import com.andgate.ikou.actor.Scene import com.andgate.ikou.actor.messaging.Message import com.andgate.ikou.actor.player.commands.* import com.andgate.ikou.actor.player.messages.* import com.andgate.ikou.animate.Animator import com.andgate.ikou.graphics.player.PlayerModel import com.badlogic.gdx.math.Vector3 class PlayerActor(id: String, scene: Scene, val model: PlayerModel) : Actor(id, scene) { private val TAG: String = "PlayerActor" val animator = Animator(model.transform) init { // Bind to events that are coming from the maze scene.dispatcher.subscribe("SmoothSlide", channel) channel.bind("SmoothSlide", { msg -> val msg = msg as SmoothSlideMessage if(msg.playerId == id) cmd_proc.accept(SmoothSlideCommand(this, msg.start, msg.end)) }) scene.dispatcher.subscribe("StickySlide", channel) channel.bind("StickySlide", { msg -> val msg = msg as StickySlideMessage if(msg.playerId == id) cmd_proc.accept(StickySlideCommand(this, msg.start, msg.end)) }) scene.dispatcher.subscribe("DropDown", channel) channel.bind("DropDown", { msg -> val msg = msg as DropDownMessage if(msg.playerId == id) cmd_proc.accept(DropDownCommand(this, msg.start, msg.end)) }) scene.dispatcher.subscribe("HitEdge", channel) channel.bind("HitEdge", { msg -> val msg = msg as HitEdgeMessage if(msg.playerId == id) cmd_proc.accept(HitEdgeCommand(this)) }) scene.dispatcher.subscribe("FinishGame", channel) channel.bind("FinishGame", { msg -> val msg = msg as FinishGameMessage if(msg.playerId == id) cmd_proc.accept(FinishGameCommand(this)) }) } override fun receive(event: Message) { // Actor bound to all the relevant events, // no events that need to be received asynchronously } override fun update(delta_time: Float) { animator.update(delta_time) } override fun dispose() { super.dispose() model.dispose() } }
gpl-2.0
08989b4aae37859b19b02da7714c460b
30.788732
96
0.633584
4.074007
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/codeVision/ui/popup/SubCodeVisionMenu.kt
8
1738
package com.intellij.codeInsight.codeVision.ui.popup import com.intellij.codeInsight.codeVision.CodeVisionEntryExtraActionModel import com.intellij.codeInsight.codeVision.ui.model.isEnabled import com.intellij.openapi.ui.popup.ListSeparator import com.intellij.openapi.ui.popup.PopupStep import com.intellij.openapi.ui.popup.util.BaseListPopupStep import com.intellij.openapi.util.NlsContexts open class SubCodeVisionMenu(val list: List<CodeVisionEntryExtraActionModel>, val onClick: (String) -> Unit, @NlsContexts.PopupTitle title: String? = null) : BaseListPopupStep<CodeVisionEntryExtraActionModel>(title, list.filter { it.isEnabled() }) { override fun isSelectable(value: CodeVisionEntryExtraActionModel): Boolean { return value.isEnabled() } override fun isAutoSelectionEnabled(): Boolean { return false } override fun isSpeedSearchEnabled(): Boolean { return true } override fun isMnemonicsNavigationEnabled(): Boolean { return true } override fun getTextFor(value: CodeVisionEntryExtraActionModel): String { return value.displayText } override fun onChosen(value: CodeVisionEntryExtraActionModel, finalChoice: Boolean): PopupStep<*>? { value.actionId?.let { doFinalStep { onClick.invoke(value.actionId!!) } } return PopupStep.FINAL_CHOICE } override fun getSeparatorAbove(value: CodeVisionEntryExtraActionModel): ListSeparator? { val index = list.indexOf(value) val prevIndex = index - 1 if (prevIndex >= 0) { val prevValue = list[prevIndex] if (!prevValue.isEnabled()) { return ListSeparator(prevValue.displayText) } } return null } }
apache-2.0
1dac7c8eb2bba088b82c05bf9b5e8a2b
30.053571
102
0.721519
5.008646
false
false
false
false
chromeos/android-google-drive-backup-sample
app/src/main/java/com/example/drivebackupsample/DriveUploadWorker.kt
1
1613
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.drivebackupsample import android.content.Context import androidx.work.CoroutineWorker import androidx.work.WorkerParameters import com.google.api.services.drive.Drive import kotlinx.coroutines.coroutineScope class DriveUploadWorker( appContext: Context, workerParams: WorkerParameters, private val driveService: Drive ) : CoroutineWorker(appContext, workerParams) { override suspend fun doWork(): Result { val fileName = inputData.getString(KEY_NAME_ARG)!! val contents = inputData.getString(KEY_CONTENTS_ARG)!! val folderId = inputData.getString(KEY_CONTENTS_FOLDER_ID)!! return coroutineScope { val fileId = driveService.createFile(folderId, fileName) driveService.saveFile(fileId, fileName, contents) Result.success() } } companion object { const val KEY_NAME_ARG = "name" const val KEY_CONTENTS_ARG = "contents" const val KEY_CONTENTS_FOLDER_ID = "folder_id" } }
apache-2.0
2c1d126a2be19a521758c764b82a69a5
33.340426
75
0.715437
4.443526
false
false
false
false
GunoH/intellij-community
plugins/kotlin/compiler-plugins/kotlinx-serialization/common/src/org/jetbrains/kotlin/idea/compilerPlugin/kotlinxSerialization/compiler/extensions/SerializationIDEResolveExtension.kt
4
3394
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.compilerPlugin.kotlinxSerialization.compiler.extensions import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.PropertyDescriptor import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.LazyClassContext import org.jetbrains.kotlin.resolve.lazy.declarations.ClassMemberDeclarationProvider import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.idea.compilerPlugin.kotlinxSerialization.getIfEnabledOn import org.jetbrains.kotlin.idea.compilerPlugin.kotlinxSerialization.runIfEnabledOn import org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationResolveExtension import java.util.* class SerializationIDEResolveExtension : SerializationResolveExtension() { override fun getSyntheticNestedClassNames(thisDescriptor: ClassDescriptor): List<Name> = getIfEnabledOn(thisDescriptor) { super.getSyntheticNestedClassNames(thisDescriptor) } ?: emptyList() override fun getPossibleSyntheticNestedClassNames(thisDescriptor: ClassDescriptor): List<Name>? { val enabled = getIfEnabledOn(thisDescriptor) { true } ?: false return if (enabled) super.getPossibleSyntheticNestedClassNames(thisDescriptor) else emptyList() } override fun getSyntheticFunctionNames(thisDescriptor: ClassDescriptor): List<Name> = getIfEnabledOn(thisDescriptor) { super.getSyntheticFunctionNames(thisDescriptor) } ?: emptyList() override fun generateSyntheticClasses( thisDescriptor: ClassDescriptor, name: Name, ctx: LazyClassContext, declarationProvider: ClassMemberDeclarationProvider, result: MutableSet<ClassDescriptor> ) = runIfEnabledOn(thisDescriptor) { super.generateSyntheticClasses(thisDescriptor, name, ctx, declarationProvider, result) } override fun getSyntheticCompanionObjectNameIfNeeded(thisDescriptor: ClassDescriptor): Name? = getIfEnabledOn(thisDescriptor) { super.getSyntheticCompanionObjectNameIfNeeded(thisDescriptor) } override fun addSyntheticSupertypes(thisDescriptor: ClassDescriptor, supertypes: MutableList<KotlinType>) = runIfEnabledOn(thisDescriptor) { super.addSyntheticSupertypes(thisDescriptor, supertypes) } override fun generateSyntheticMethods( thisDescriptor: ClassDescriptor, name: Name, bindingContext: BindingContext, fromSupertypes: List<SimpleFunctionDescriptor>, result: MutableCollection<SimpleFunctionDescriptor> ) = runIfEnabledOn(thisDescriptor) { super.generateSyntheticMethods(thisDescriptor, name, bindingContext, fromSupertypes, result) } override fun generateSyntheticProperties( thisDescriptor: ClassDescriptor, name: Name, bindingContext: BindingContext, fromSupertypes: ArrayList<PropertyDescriptor>, result: MutableSet<PropertyDescriptor> ) = runIfEnabledOn(thisDescriptor) { super.generateSyntheticProperties(thisDescriptor, name, bindingContext, fromSupertypes, result) } }
apache-2.0
9a17d6864dd5aac5b7603126d1777540
46.802817
158
0.783147
5.527687
false
false
false
false
ktorio/ktor
ktor-server/ktor-server-host-common/jvmAndNix/src/io/ktor/server/engine/DefaultEnginePipeline.kt
1
3867
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.engine import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.engine.internal.* import io.ktor.server.engine.internal.ClosedChannelException import io.ktor.server.logging.* import io.ktor.server.plugins.* import io.ktor.server.response.* import io.ktor.util.* import io.ktor.util.cio.* import io.ktor.util.logging.* import io.ktor.util.pipeline.* import io.ktor.utils.io.* import io.ktor.utils.io.errors.* import kotlinx.coroutines.* import kotlinx.coroutines.CancellationException /** * Default engine pipeline for all engines. Use it only if you are writing your own application engine implementation. */ @OptIn(InternalAPI::class) public fun defaultEnginePipeline(environment: ApplicationEnvironment): EnginePipeline { val pipeline = EnginePipeline(environment.developmentMode) configureShutdownUrl(environment, pipeline) pipeline.intercept(EnginePipeline.Call) { try { call.application.execute(call) } catch (error: ChannelIOException) { call.application.mdcProvider.withMDCBlock(call) { call.application.environment.logFailure(call, error) } } catch (error: Throwable) { handleFailure(call, error) } finally { try { call.request.receiveChannel().discard() } catch (ignore: Throwable) { } } } return pipeline } public suspend fun handleFailure(call: ApplicationCall, error: Throwable) { logError(call, error) tryRespondError(call, defaultExceptionStatusCode(error) ?: HttpStatusCode.InternalServerError) } @OptIn(InternalAPI::class) public suspend fun logError(call: ApplicationCall, error: Throwable) { call.application.mdcProvider.withMDCBlock(call) { call.application.environment.logFailure(call, error) } } /** * Map [cause] to the corresponding status code or `null` if no default exception mapping for this [cause] type */ public fun defaultExceptionStatusCode(cause: Throwable): HttpStatusCode? { return when (cause) { is BadRequestException -> HttpStatusCode.BadRequest is NotFoundException -> HttpStatusCode.NotFound is UnsupportedMediaTypeException -> HttpStatusCode.UnsupportedMediaType is TimeoutException, is TimeoutCancellationException -> HttpStatusCode.GatewayTimeout else -> null } } private suspend fun tryRespondError(call: ApplicationCall, statusCode: HttpStatusCode) { try { if (call.response.status() == null) { call.respond(statusCode) } } catch (ignore: BaseApplicationResponse.ResponseAlreadySentException) { } } private fun ApplicationEnvironment.logFailure(call: ApplicationCall, cause: Throwable) { try { val status = call.response.status() ?: "Unhandled" val logString = try { call.request.toLogString() } catch (cause: Throwable) { "(request error: $cause)" } val infoString = "$status: $logString. Exception ${cause::class}: ${cause.message}]" when (cause) { is CancellationException, is ClosedChannelException, is ChannelIOException, is IOException, is BadRequestException, is NotFoundException, is UnsupportedMediaTypeException -> log.debug(infoString, cause) else -> log.error("$status: $logString", cause) } } catch (oom: OutOfMemoryError) { try { log.error(cause) } catch (oomAttempt2: OutOfMemoryError) { printError("OutOfMemoryError: ") printError(cause.message) printError("\n") } } }
apache-2.0
ad0b2ffdfe4512261e33838d29e66737
32.626087
119
0.672356
4.598098
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsBackupController.kt
1
13131
package eu.kanade.tachiyomi.ui.setting import android.Manifest.permission.WRITE_EXTERNAL_STORAGE import android.app.Activity import android.app.Dialog import android.content.ActivityNotFoundException import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.core.net.toUri import androidx.core.os.bundleOf import androidx.preference.PreferenceScreen import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.hippo.unifile.UniFile import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.backup.BackupConst import eu.kanade.tachiyomi.data.backup.BackupCreateService import eu.kanade.tachiyomi.data.backup.BackupCreatorJob import eu.kanade.tachiyomi.data.backup.BackupRestoreService import eu.kanade.tachiyomi.data.backup.ValidatorParseException import eu.kanade.tachiyomi.data.backup.full.FullBackupRestoreValidator import eu.kanade.tachiyomi.data.backup.full.models.BackupFull import eu.kanade.tachiyomi.data.backup.legacy.LegacyBackupRestoreValidator import eu.kanade.tachiyomi.ui.base.controller.DialogController import eu.kanade.tachiyomi.ui.base.controller.requestPermissionsSafe import eu.kanade.tachiyomi.util.preference.bindTo import eu.kanade.tachiyomi.util.preference.entriesRes import eu.kanade.tachiyomi.util.preference.infoPreference import eu.kanade.tachiyomi.util.preference.intListPreference import eu.kanade.tachiyomi.util.preference.onChange import eu.kanade.tachiyomi.util.preference.onClick import eu.kanade.tachiyomi.util.preference.preference import eu.kanade.tachiyomi.util.preference.preferenceCategory import eu.kanade.tachiyomi.util.preference.summaryRes import eu.kanade.tachiyomi.util.preference.titleRes import eu.kanade.tachiyomi.util.system.DeviceUtil import eu.kanade.tachiyomi.util.system.openInBrowser import eu.kanade.tachiyomi.util.system.toast import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach class SettingsBackupController : SettingsController() { /** * Flags containing information of what to backup. */ private var backupFlags = 0 override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) requestPermissionsSafe(arrayOf(WRITE_EXTERNAL_STORAGE), 500) } override fun setupPreferenceScreen(screen: PreferenceScreen) = screen.apply { titleRes = R.string.label_backup preference { key = "pref_create_backup" titleRes = R.string.pref_create_backup summaryRes = R.string.pref_create_backup_summ onClick { if (DeviceUtil.isMiui && DeviceUtil.isMiuiOptimizationDisabled()) { context.toast(R.string.restore_miui_warning, Toast.LENGTH_LONG) } if (!BackupCreateService.isRunning(context)) { val ctrl = CreateBackupDialog() ctrl.targetController = this@SettingsBackupController ctrl.showDialog(router) } else { context.toast(R.string.backup_in_progress) } } } preference { key = "pref_restore_backup" titleRes = R.string.pref_restore_backup summaryRes = R.string.pref_restore_backup_summ onClick { if (DeviceUtil.isMiui && DeviceUtil.isMiuiOptimizationDisabled()) { context.toast(R.string.restore_miui_warning, Toast.LENGTH_LONG) } if (!BackupRestoreService.isRunning(context)) { val intent = Intent(Intent.ACTION_GET_CONTENT).apply { addCategory(Intent.CATEGORY_OPENABLE) type = "*/*" } val title = resources?.getString(R.string.file_select_backup) val chooser = Intent.createChooser(intent, title) startActivityForResult(chooser, CODE_BACKUP_RESTORE) } else { context.toast(R.string.restore_in_progress) } } } preferenceCategory { titleRes = R.string.pref_backup_service_category intListPreference { bindTo(preferences.backupInterval()) titleRes = R.string.pref_backup_interval entriesRes = arrayOf( R.string.update_never, R.string.update_6hour, R.string.update_12hour, R.string.update_24hour, R.string.update_48hour, R.string.update_weekly ) entryValues = arrayOf("0", "6", "12", "24", "48", "168") summary = "%s" onChange { newValue -> val interval = (newValue as String).toInt() BackupCreatorJob.setupTask(context, interval) true } } preference { bindTo(preferences.backupsDirectory()) titleRes = R.string.pref_backup_directory onClick { try { val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE) startActivityForResult(intent, CODE_BACKUP_DIR) } catch (e: ActivityNotFoundException) { activity?.toast(R.string.file_picker_error) } } visibleIf(preferences.backupInterval()) { it > 0 } preferences.backupsDirectory().asFlow() .onEach { path -> val dir = UniFile.fromUri(context, path.toUri()) summary = dir.filePath + "/automatic" } .launchIn(viewScope) } intListPreference { bindTo(preferences.numberOfBackups()) titleRes = R.string.pref_backup_slots entries = arrayOf("1", "2", "3", "4", "5") entryValues = entries summary = "%s" visibleIf(preferences.backupInterval()) { it > 0 } } } infoPreference(R.string.backup_info) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.settings_backup, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_backup_help -> activity?.openInBrowser(HELP_URL) } return super.onOptionsItemSelected(item) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (data != null && resultCode == Activity.RESULT_OK) { val activity = activity ?: return val uri = data.data if (uri == null) { activity.toast(R.string.backup_restore_invalid_uri) return } when (requestCode) { CODE_BACKUP_DIR -> { // Get UriPermission so it's possible to write files val flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION activity.contentResolver.takePersistableUriPermission(uri, flags) preferences.backupsDirectory().set(uri.toString()) } CODE_BACKUP_CREATE -> { val flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION activity.contentResolver.takePersistableUriPermission(uri, flags) BackupCreateService.start( activity, uri, backupFlags, ) } CODE_BACKUP_RESTORE -> { RestoreBackupDialog(uri).showDialog(router) } } } } fun createBackup(flags: Int) { backupFlags = flags try { // Use Android's built-in file creator val intent = Intent(Intent.ACTION_CREATE_DOCUMENT) .addCategory(Intent.CATEGORY_OPENABLE) .setType("application/*") .putExtra(Intent.EXTRA_TITLE, BackupFull.getDefaultFilename()) startActivityForResult(intent, CODE_BACKUP_CREATE) } catch (e: ActivityNotFoundException) { activity?.toast(R.string.file_picker_error) } } class CreateBackupDialog(bundle: Bundle? = null) : DialogController(bundle) { override fun onCreateDialog(savedViewState: Bundle?): Dialog { val activity = activity!! val options = arrayOf( R.string.manga, R.string.categories, R.string.chapters, R.string.track, R.string.history ) .map { activity.getString(it) } val selected = options.map { true }.toBooleanArray() return MaterialAlertDialogBuilder(activity) .setTitle(R.string.backup_choice) .setMultiChoiceItems(options.toTypedArray(), selected) { dialog, which, checked -> if (which == 0) { (dialog as AlertDialog).listView.setItemChecked(which, true) } else { selected[which] = checked } } .setPositiveButton(R.string.action_create) { _, _ -> var flags = 0 selected.forEachIndexed { i, checked -> if (checked) { when (i) { 1 -> flags = flags or BackupCreateService.BACKUP_CATEGORY 2 -> flags = flags or BackupCreateService.BACKUP_CHAPTER 3 -> flags = flags or BackupCreateService.BACKUP_TRACK 4 -> flags = flags or BackupCreateService.BACKUP_HISTORY } } } (targetController as? SettingsBackupController)?.createBackup(flags) } .setNegativeButton(android.R.string.cancel, null) .create() } } class RestoreBackupDialog(bundle: Bundle? = null) : DialogController(bundle) { constructor(uri: Uri) : this( bundleOf(KEY_URI to uri) ) override fun onCreateDialog(savedViewState: Bundle?): Dialog { val activity = activity!! val uri: Uri = args.getParcelable(KEY_URI)!! return try { var type = BackupConst.BACKUP_TYPE_FULL val results = try { FullBackupRestoreValidator().validate(activity, uri) } catch (_: ValidatorParseException) { type = BackupConst.BACKUP_TYPE_LEGACY LegacyBackupRestoreValidator().validate(activity, uri) } var message = if (type == BackupConst.BACKUP_TYPE_FULL) { activity.getString(R.string.backup_restore_content_full) } else { activity.getString(R.string.backup_restore_content) } if (results.missingSources.isNotEmpty()) { message += "\n\n${activity.getString(R.string.backup_restore_missing_sources)}\n${results.missingSources.joinToString("\n") { "- $it" }}" } if (results.missingTrackers.isNotEmpty()) { message += "\n\n${activity.getString(R.string.backup_restore_missing_trackers)}\n${results.missingTrackers.joinToString("\n") { "- $it" }}" } MaterialAlertDialogBuilder(activity) .setTitle(R.string.pref_restore_backup) .setMessage(message) .setPositiveButton(R.string.action_restore) { _, _ -> BackupRestoreService.start(activity, uri, type) } .create() } catch (e: Exception) { MaterialAlertDialogBuilder(activity) .setTitle(R.string.invalid_backup_file) .setMessage(e.message) .setPositiveButton(android.R.string.cancel, null) .create() } } } } private const val KEY_URI = "RestoreBackupDialog.uri" private const val CODE_BACKUP_DIR = 503 private const val CODE_BACKUP_CREATE = 504 private const val CODE_BACKUP_RESTORE = 505 private const val HELP_URL = "https://tachiyomi.org/help/guides/backups/"
apache-2.0
e2e285a2e68e97e071ca9c2ba4ab9a8a
39.527778
159
0.570939
5.105365
false
false
false
false
jovr/imgui
core/src/main/kotlin/imgui/internal/classes/InputTextState.kt
2
41108
package imgui.internal.classes import glm_.glm import glm_.max import imgui.* import imgui.api.g import imgui.internal.api.inputText.Companion.inputTextCalcTextSizeW import imgui.internal.isBlankW import imgui.internal.textCountUtf8BytesFromStr import imgui.stb.te import imgui.stb.te.key import imgui.stb.te.makeUndoReplace import org.lwjgl.system.Platform import uno.kotlin.NUL /** Internal state of the currently focused/edited text input box * For a given item ID, access with ImGui::GetInputTextState() */ class InputTextState { /** widget id owning the text state */ var id: ID = 0 var curLenA = 0 // we need to maintain our buffer length in both UTF-8 and wchar format. UTF-8 length is valid even if TextA is not. var curLenW = 0 /** edit buffer, we need to persist but can't guarantee the persistence of the user-provided buffer. So we copy into own buffer. */ var textW = CharArray(0) /** temporary buffer for callbacks and other operations. size=capacity. */ var textA = ByteArray(0) /** backup of end-user buffer at the time of focus (in UTF-8, unaltered) */ var initialTextA = ByteArray(0) /** temporary UTF8 buffer is not initially valid before we make the widget active (until then we pull the data from user argument) */ var textAIsValid = false /** end-user buffer size */ var bufCapacityA = 0 /** horizontal scrolling/offset */ var scrollX = 0f /** state for stb_textedit.h */ val stb = te.State() /** timer for cursor blink, reset on every user action so the cursor reappears immediately */ var cursorAnim = 0f /** set when we want scrolling to follow the current cursor position (not always!) */ var cursorFollow = false /** after a double-click to select all, we ignore further mouse drags to update selection */ var selectedAllMouseLock = false /** edited this frame */ var edited = false /** Temporarily set when active */ var userFlags: InputTextFlags = 0 /** Temporarily set when active */ var userCallback: InputTextCallback? = null /** Temporarily set when active */ var userCallbackData: Any? = null fun clearText() { curLenW = 0 curLenA = 0 textW = CharArray(0) textA = ByteArray(0) cursorClamp() } fun clearFreeMemory() { textW = CharArray(0) textA = ByteArray(0) initialTextA = ByteArray(0) } val undoAvailCount: Int get() = stb.undoState.undoPoint val redoAvailCount: Int get() = te.UNDOSTATECOUNT - stb.undoState.redoPoint /** Cannot be inline because we call in code in stb_textedit.h implementation */ fun onKeyPressed(key: Int) { key(key) cursorFollow = true cursorAnimReset() } // Cursor & Selection /** After a user-input the cursor stays on for a while without blinking */ fun cursorAnimReset() { cursorAnim = -0.3f } fun cursorClamp() = with(stb) { cursor = glm.min(cursor, curLenW) selectStart = glm.min(selectStart, curLenW) selectEnd = glm.min(selectEnd, curLenW) } val hasSelection get() = stb.hasSelection fun clearSelection() { stb.selectStart = stb.cursor stb.selectEnd = stb.cursor } fun selectAll() { stb.selectStart = 0 stb.selectEnd = curLenW stb.cursor = curLenW stb.hasPreferredX = false } //------------------------------------------------------------------------- // STB libraries includes //------------------------------------------------------------------------- val GETWIDTH_NEWLINE = -1f /* ==================================================================================================================== Wrapper for stb_textedit.h to edit text (our wrapper is for: statically sized buffer, single-line, wchar characters. InputText converts between UTF-8 and wchar) ==================================================================================================================== */ val stringLen: Int get() = curLenW fun getChar(idx: Int): Char = textW[idx] fun getWidth(lineStartIdx: Int, charIdx: Int): Float = when (val c = textW[lineStartIdx + charIdx]) { '\n' -> GETWIDTH_NEWLINE else -> g.font.getCharAdvance(c) * (g.fontSize / g.font.fontSize) } fun keyToText(key: Int): Int = if (key >= 0x200000) 0 else key val NEWLINE = '\n' private var textRemaining = 0 fun layoutRow(r: te.Row, lineStartIdx: Int) { val size = inputTextCalcTextSizeW(textW, lineStartIdx, curLenW, ::textRemaining, stopOnNewLine = true) r.apply { x0 = 0f x1 = size.x baselineYDelta = size.y yMin = 0f yMax = size.y numChars = textRemaining - lineStartIdx } } val Char.isSeparator: Boolean get() = let { c -> isBlankW || c == ',' || c == ';' || c == '(' || c == ')' || c == '{' || c == '}' || c == '[' || c == ']' || c == '|' } infix fun isWordBoundaryFromRight(idx: Int): Boolean = when { idx > 0 -> textW[idx - 1].isSeparator && !textW[idx].isSeparator else -> true } infix fun isWordBoundaryFromLeft(idx: Int): Boolean = when { idx > 0 -> !textW[idx - 1].isSeparator && textW[idx].isSeparator else -> true } infix fun moveWordLeft(idx: Int): Int { var i = idx - 1 while (i >= 0 && !isWordBoundaryFromRight(i)) i-- return if (i < 0) 0 else i } infix fun moveWordRight(idx_: Int): Int { var idx = idx_ + 1 val len = curLenW fun isWordBoundary() = when (Platform.get()) { Platform.MACOSX -> isWordBoundaryFromLeft(idx) else -> isWordBoundaryFromRight(idx) } while (idx < len && !isWordBoundary()) idx++ return if (idx > len) len else idx } fun deleteChars(pos: Int, n: Int) { if (n == 0) // TODO [JVM] needed? return var dst = pos // We maintain our buffer length in both UTF-8 and wchar formats edited = true curLenA -= textCountUtf8BytesFromStr(textW, dst, dst + n) curLenW -= n // Offset remaining text (FIXME-OPT: Use memmove) var src = pos + n var c = textW[src++] while (c != NUL) { textW[dst++] = c c = textW[src++] } if (dst < textW.size) textW[dst] = NUL } fun insertChar(pos: Int, newText: Char): Boolean = insertChars(pos, charArrayOf(newText), 0, 1) fun insertChars(pos: Int, newText: CharArray, ptr: Int, newTextLen: Int): Boolean { val isResizable = userFlags has InputTextFlag.CallbackResize val textLen = curLenW assert(pos <= textLen) val newTextLenUtf8 = textCountUtf8BytesFromStr(newText, ptr, newTextLen) if (!isResizable && newTextLenUtf8 + curLenA > bufCapacityA) return false // Grow internal buffer if needed if (newTextLen + textLen > textW.size) { if (!isResizable) return false assert(textLen <= textW.size) // [JVM] <= instead < because we dont use the termination NUL val tmp = CharArray(textLen + glm.clamp(newTextLen * 4, 32, 256 max newTextLen)) System.arraycopy(textW, 0, tmp, 0, textW.size) textW = tmp } if (pos != textLen) for (i in 0 until textLen - pos) textW[textLen - 1 + newTextLen - i] = textW[textLen - 1 - i] for (i in 0 until newTextLen) textW[pos + i] = newText[ptr + i] edited = true curLenW += newTextLen curLenA += newTextLenUtf8 if (curLenW < textW.size) textW[curLenW] = NUL return true } /* We don't use an enum so we can build even with conflicting symbols (if another user of stb_textedit.h leak their STB_TEXTEDIT_K_* symbols) */ object K { /** keyboard input to move cursor left */ val LEFT = 0x200000 /** keyboard input to move cursor right */ val RIGHT = 0x200001 /** keyboard input to move cursor up */ val UP = 0x200002 /** keyboard input to move cursor down */ val DOWN = 0x200003 /** keyboard input to move cursor to start of line */ val LINESTART = 0x200004 /** keyboard input to move cursor to end of line */ val LINEEND = 0x200005 /** keyboard input to move cursor to start of text */ val TEXTSTART = 0x200006 /** keyboard input to move cursor to end of text */ val TEXTEND = 0x200007 /** keyboard input to delete selection or character under cursor */ val DELETE = 0x200008 /** keyboard input to delete selection or character left of cursor */ val BACKSPACE = 0x200009 /** keyboard input to perform undo */ val UNDO = 0x20000A /** keyboard input to perform redo */ val REDO = 0x20000B /** keyboard input to move cursor left one word */ val WORDLEFT = 0x20000C /** keyboard input to move cursor right one word */ val WORDRIGHT = 0x20000D /** keyboard input to move cursor up a page */ val PGUP = 0x20000E /** keyboard input to move cursor down a page */ val PGDOWN = 0x20000F val SHIFT = 0x400000 } /** stb_textedit internally allows for a single undo record to do addition and deletion, but somehow, calling * the stb_textedit_paste() function creates two separate records, so we perform it manually. (FIXME: Report to nothings/stb?) */ fun replace(text: CharArray, textLen: Int = text.size) { makeUndoReplace(0, curLenW, textLen) deleteChars(0, curLenW) if (textLen <= 0) return if (insertChars(0, text, 0, textLen)) { stb.cursor = textLen stb.hasPreferredX = false return } assert(false) { "Failed to insert character, normally shouldn't happen because of how we currently use stb_textedit_replace()" } } // /* // ==================================================================================================================== // stb_textedit.h - v1.9 - public domain - Sean Barrett // Development of this library was sponsored by RAD Game Tools // ==================================================================================================================== // */ // // companion object { // val UNDOSTATECOUNT = 99 // val UNDOCHARCOUNT = 999 // fun memmove(dst: CharArray, pDst: Int, src: CharArray, pSrc: Int, len: Int) { // val tmp = CharArray(len) { src[pSrc + it] } // for (i in 0 until len) dst[pDst + i] = tmp[i] // } // // fun memmove(dst: Array<UndoRecord>, pDst: Int, src: Array<UndoRecord>, pSrc: Int, len: Int) { // val tmp = Array(len) { UndoRecord(src[pSrc + it]) } // for (i in 0 until len) dst[pDst + i] = tmp[i] // } // } // // class UndoRecord { // var where = 0 // var insertLength = 0 // var deleteLength = 0 // var charStorage = 0 // // constructor() // constructor(undoRecord: UndoRecord) { // where = undoRecord.where // insertLength = undoRecord.insertLength // deleteLength = undoRecord.deleteLength // charStorage = undoRecord.charStorage // } // // infix fun put(other: UndoRecord) { // where = other.where // insertLength = other.insertLength // deleteLength = other.deleteLength // charStorage = other.charStorage // } // } // // class UndoState { // val undoRec = Array(UNDOSTATECOUNT) { UndoRecord() } // val undoChar = CharArray(UNDOCHARCOUNT) // var undoPoint = 0 // var redoPoint = 0 // var undoCharPoint = 0 // var redoCharPoint = 0 // // fun clear() { // undoPoint = 0 // undoCharPoint = 0 // redoPoint = UNDOSTATECOUNT // redoCharPoint = UNDOCHARCOUNT // } // // ///////////////////////////////////////////////////////////////////////////// // // // // Undo processing // // // // @OPTIMIZE: the undo/redo buffer should be circular // // // ///////////////////////////////////////////////////////////////////////////// // // fun flushRedo() { // redoPoint = UNDOSTATECOUNT // redoCharPoint = UNDOCHARCOUNT // } // // /** discard the oldest entry in the undo list */ // fun discardUndo() { // if (undoPoint > 0) { // // if the 0th undo state has characters, clean those up // if (undoRec[0].charStorage >= 0) { // val n = undoRec[0].insertLength // // delete n characters from all other records // undoCharPoint -= n // vsnet05 // memmove(undoChar, 0, undoChar, n, undoCharPoint) // for (i in 0 until undoPoint) // if (undoRec[i].charStorage >= 0) // // vsnet05 // @OPTIMIZE: get rid of char_storage and infer it // undoRec[i].charStorage = undoRec[i].charStorage - n // } // --undoPoint // memmove(undoRec, 0, undoRec, 1, undoPoint) // } // } // // /** discard the oldest entry in the redo list--it's bad if this ever happens, but because undo & redo have to // * store the actual characters in different cases, the redo character buffer can fill up even though the undo // * buffer didn't */ // fun discardRedo() { // // val k = UNDOSTATECOUNT - 1 // // if (redoPoint <= k) { // // if the k'th undo state has characters, clean those up // if (undoRec[k].charStorage >= 0) { // val n = undoRec[k].insertLength // // delete n characters from all other records // redoCharPoint += n // vsnet05 // memmove(undoChar, redoCharPoint, undoChar, redoCharPoint - n, UNDOCHARCOUNT - redoCharPoint) // for (i in redoPoint until k) // if (undoRec[i].charStorage >= 0) // undoRec[i].charStorage = undoRec[i].charStorage + n // vsnet05 // } // memmove(undoRec, redoPoint, undoRec, redoPoint - 1, UNDOSTATECOUNT - redoPoint) // ++redoPoint // } // } // // fun createUndoRecord(numChars: Int): UndoRecord? { // // // any time we create a new undo record, we discard redo // flushRedo() // // // if we have no free records, we have to make room, by sliding the existing records down // if (undoPoint == UNDOSTATECOUNT) // discardUndo() // // // if the characters to store won't possibly fit in the buffer, we can't undo // if (numChars > UNDOCHARCOUNT) { // undoPoint = 0 // undoCharPoint = 0 // return null // } // // // if we don't have enough free characters in the buffer, we have to make room // while (undoCharPoint + numChars > UNDOCHARCOUNT) // discardUndo() // // return undoRec[undoPoint++] // } // // fun createundo(pos: Int, insertLen: Int, deleteLen: Int): Int? { // // val r = createUndoRecord(insertLen) ?: return null // // r.where = pos // r.insertLength = insertLen // r.deleteLength = deleteLen // // if (insertLen == 0) { // r.charStorage = -1 // return null // } else { // r.charStorage = undoCharPoint // undoCharPoint += insertLen // return r.charStorage // } // } // } // // class State { // // /** position of the text cursor within the string */ // var cursor = 0 // // /* selection start and end point in characters; if equal, no selection. // note that start may be less than or greater than end (e.g. when dragging the mouse, start is where the // initial click was, and you can drag in either direction) */ // // /** selection start point */ // var selectStart = 0 // // /** selection end point */ // var selectEnd = 0 // // /** each textfield keeps its own insert mode state. to keep an app-wide insert mode, copy this value in/out of // * the app state */ // var insertMode = false // // /** not implemented yet */ // var cursorAtEndOfLine = false // var initialized = false // var hasPreferredX = false // var singleLine = false // var padding1 = NUL // var padding2 = NUL // var padding3 = NUL // // /** this determines where the cursor up/down tries to seek to along x */ // var preferredX = 0f // val undostate = UndoState() // // // /** reset the state to default */ // fun clear(isSingleLine: Boolean) { // // undostate.clear() // selectStart = 0 // selectEnd = 0 // cursor = 0 // hasPreferredX = false // preferredX = 0f // cursorAtEndOfLine = false // initialized = true // singleLine = isSingleLine // insertMode = false // } // } // // /** Result of layout query, used by stb_textedit to determine where the text in each row is. // * result of layout query */ // class Row { // /** starting x location */ // var x0 = 0f // // /** end x location (allows for align=right, etc) */ // var x1 = 0f // // /** position of baseline relative to previous row's baseline */ // var baselineYDelta = 0f // // /** height of row above baseline */ // var yMin = 0f // // /** height of row below baseline */ // var yMax = 0f // // var numChars = 0 // } // // ///////////////////////////////////////////////////////////////////////////// // // // // Mouse input handling // // // ///////////////////////////////////////////////////////////////////////////// // // /** traverse the layout to locate the nearest character to a display position */ // fun locateCoord(x: Float, y: Float): Int { // // val r = Row() // val n = curLenW // var baseY = 0f // var prevX: Float // var i = 0 // // // search rows to find one that straddles 'y' // while (i < n) { // layoutRow(r, i) // if (r.numChars <= 0) // return n // // if (i == 0 && y < baseY + r.yMin) // return 0 // // if (y < baseY + r.yMax) // break // // i += r.numChars // baseY += r.baselineYDelta // } // // // below all text, return 'after' last character // if (i >= n) // return n // // // check if it's before the beginning of the line // if (x < r.x0) // return i // // // check if it's before the end of the line // if (x < r.x1) { // // search characters in row for one that straddles 'x' // prevX = r.x0 // for (k in 0 until r.numChars) { // val w = getWidth(i, k) // if (x < prevX + w) { // return if (x < prevX + w / 2) k + i else k + i + 1 // } // prevX += w // } // // shouldn't happen, but if it does, fall through to end-of-line case // } // // // if the last character is a newline, return that. otherwise return 'after' the last character // return if (textW[i + r.numChars - 1] == '\n') i + r.numChars - 1 else i + r.numChars // } // // /** API click: on mouse down, move the cursor to the clicked location, and reset the selection */ // fun click(x: Float, y: Float) = with(stb) { // cursor = locateCoord(x, y) // selectStart = cursor // selectEnd = cursor // hasPreferredX = false // } // // /** API drag: on mouse drag, move the cursor and selection endpoint to the clicked location */ // fun drag(x: Float, y: Float) { // val p = locateCoord(x, y) // if (stb.selectStart == stb.selectEnd) // stb.selectStart = stb.cursor // stb.cursor = p // stb.selectEnd = p // } // // ///////////////////////////////////////////////////////////////////////////// // // // // Keyboard input handling // // // ///////////////////////////////////////////////////////////////////////////// // // fun undo() { // // val s = stb.undoState // if (s.undoPoint == 0) return // // // we need to do two things: apply the undo record, and create a redo record // val u = UndoRecord(s.undoRec[s.undoPoint - 1]) // var r = s.undoRec[s.redoPoint - 1] // r put u // r.charStorage = -1 // // if (u.deleteLength != 0) { // /* if the undo record says to delete characters, then the redo record will need to re-insert the characters // that get deleted, so we need to store them. // // there are three cases: // - there's enough room to store the characters // - characters stored for *redoing* don't leave room for redo // - characters stored for *undoing* don't leave room for redo // if the last is true, we have to bail */ // // if (s.undoCharPoint + u.deleteLength >= UNDOCHARCOUNT) // // the undo records take up too much character space; there's no space to store the redo characters // r.insertLength = 0 // else { // // there's definitely room to store the characters eventually // while (s.undoCharPoint + u.deleteLength > s.redoCharPoint) { // // there's currently not enough room, so discard a redo record // s.discardRedo() // // should never happen: // if (s.redoPoint == UNDOSTATECOUNT) // return // } // r = s.undoRec[s.redoPoint - 1] // // r.charStorage = s.redoCharPoint - u.deleteLength // s.redoCharPoint = s.redoCharPoint - u.deleteLength // // // now save the characters // repeat(u.deleteLength) { s.undoChar[r.charStorage + it] = getChar(u.where + it) } // } // // // now we can carry out the deletion // deleteChars(u.where, u.deleteLength) // } // // // check type of recorded action: // if (u.insertLength != 0) { // // easy case: was a deletion, so we need to insert n characters // insertChars(u.where, s.undoChar, u.charStorage, u.insertLength) // s.undoCharPoint -= u.insertLength // } // // stb.cursor = u.where + u.insertLength // // s.undoPoint-- // s.redoPoint-- // } // // fun redo() { // // val s = stb.undoState // if (s.redoPoint == UNDOSTATECOUNT) return // // // we need to do two things: apply the redo record, and create an undo record // val u = s.undoRec[s.undoPoint] // val r = UndoRecord(s.undoRec[s.redoPoint]) // // // we KNOW there must be room for the undo record, because the redo record was derived from an undo record // // u put r // u.charStorage = -1 // // if (r.deleteLength != 0) { // // the redo record requires us to delete characters, so the undo record needs to store the characters // // if (s.undoCharPoint + u.insertLength > s.redoCharPoint) { // u.insertLength = 0 // u.deleteLength = 0 // } else { // u.charStorage = s.undoCharPoint // s.undoCharPoint = s.undoCharPoint + u.insertLength // // // now save the characters // for (i in 0 until u.insertLength) // s.undoChar[u.charStorage + i] = getChar(u.where + i) // } // // deleteChars(r.where, r.deleteLength) // } // // if (r.insertLength != 0) { // // easy case: need to insert n characters // insertChars(r.where, s.undoChar, r.charStorage, r.insertLength) // s.redoCharPoint += r.insertLength // } // // stb.cursor = r.where + r.insertLength // // s.undoPoint++ // s.redoPoint++ // } // // fun makeundoInsert(where: Int, length: Int) = stb.undoState.createundo(where, 0, length) // // fun makeundoDelete(where: Int, length: Int) = stb.undoState.createundo(where, length, 0)?.let { // for (i in 0 until length) // stb.undoState.undoChar[it + i] = getChar(where + i) // } // // fun makeundoReplace(where: Int, oldLength: Int, newLength: Int) = stb.undoState.createundo(where, oldLength, newLength)?.let { // for (i in 0 until oldLength) // stb.undoState.undoChar[i] = getChar(where + i) // } // // // class FindState { // // position of n'th character // var x = 0f // var y = 0f // // /** height of line */ // var height = 0f // // /** first char of row */ // var firstChar = 0 // // /** first char length */ // var length = 0 // // /** first char of previous row */ // var prevFirst = 0 // } // // val hasSelection get() = stb.selectStart != stb.selectEnd // // /** find the x/y location of a character, and remember info about the previous row in case we get a move-up event // * (for page up, we'll have to rescan) */ // fun findCharpos(find: FindState, n: Int, singleLine: Boolean) { // val r = Row() // var prevStart = 0 // val z = curLenW // var i = 0 // var first: Int // // if (n == z) { // // if it's at the end, then find the last line -- simpler than trying to // // explicitly handle this case in the regular code // if (singleLine) { // layoutRow(r, 0) // with(find) { // y = 0f // firstChar = 0 // length = z // height = r.yMax - r.yMin // x = r.x1 // } // } else with(find) { // y = 0f // x = 0f // height = 1f // while (i < z) { // layoutRow(r, i) // prevStart = i // i += r.numChars // } // firstChar = i // length = 0 // prevFirst = prevStart // } // return // } // // // search rows to find the one that straddles character n // find.y = 0f // // while (true) { // layoutRow(r, i) // if (n < i + r.numChars) // break // prevStart = i // i += r.numChars // find.y += r.baselineYDelta // } // // with(find) { // first = i // firstChar = i // length = r.numChars // height = r.yMax - r.yMin // prevFirst = prevStart // // // now scan to find xpos // x = r.x0 // i = 0 // while (first + i < n) { // x += getWidth(first, i) // ++i // } // } // } // // /** make the selection/cursor state valid if client altered the string */ // fun clamp() { // val n = stringLen // with(stb) { // if (hasSelection) { // if (selectStart > n) selectStart = n // if (selectEnd > n) selectEnd = n // // if clamping forced them to be equal, move the cursor to match // if (selectStart == selectEnd) // cursor = selectStart // } // if (cursor > n) cursor = n // } // } // // /** delete characters while updating undo */ // fun delete(where: Int, len: Int) { // makeundoDelete(where, len) // deleteChars(where, len) // stb.hasPreferredX = false // } // // /** delete the section */ // fun deleteSelection() { // clamp() // with(stb) { // if (hasSelection) { // if (stb.selectStart < stb.selectEnd) { // delete(selectStart, selectEnd - selectStart) // cursor = selectStart // selectEnd = selectStart // } else { // delete(selectEnd, selectStart - selectEnd) // cursor = selectEnd // selectStart = selectEnd // } // hasPreferredX = false // } // } // } // // /** canoncialize the selection so start <= end */ // fun sortSelection() = with(stb) { // if (selectEnd < selectStart) { // val temp = selectEnd // selectEnd = selectStart // selectStart = temp // } // } // // /** move cursor to first character of selection */ // fun moveToFirst() = with(stb) { // if (hasSelection) { // sortSelection() // cursor = selectStart // selectEnd = selectStart // hasPreferredX = false // } // } // // /* move cursor to last character of selection */ // fun moveToLast() = with(stb) { // if (hasSelection) { // sortSelection() // clamp() // cursor = selectEnd // selectStart = selectEnd // hasPreferredX = false // } // } // // /** update selection and cursor to match each other */ // fun prepSelectionAtCursor() = with(stb) { // if (!hasSelection) { // selectStart = cursor // selectEnd = cursor // } else // cursor = selectEnd // } // // /** API cut: delete selection */ // fun cut(): Boolean = when { // hasSelection -> { // deleteSelection() // implicitly clamps // stb.hasPreferredX = false // true // } // else -> false // } // // /** API paste: replace existing selection with passed-in text */ // fun paste(text: CharArray, len: Int): Boolean { // // // if there's a selection, the paste should delete it // clamp() // deleteSelection() // // try to insert the characters // if (insertChars(stb.cursor, text, 0, len)) { // makeundoInsert(stb.cursor, len) // stb.cursor += len // stb.hasPreferredX = false // return true // } // // remove the undo since we didn't actually insert the characters // if (stb.undoState.undoPoint != 0) // --stb.undoState.undoPoint // return false // } // // /** API key: process a keyboard input */ // fun key(key: Int): Unit = with(stb) { // when (key) { // K.UNDO -> { // undo() // hasPreferredX = false // } // K.REDO -> { // redo() // hasPreferredX = false // } // K.LEFT -> { // if (hasSelection) // if currently there's a selection, move cursor to start of selection // moveToFirst() // else if (cursor > 0) // --cursor // hasPreferredX = false // } // K.RIGHT -> { // if (hasSelection) // if currently there's a selection, move cursor to end of selection // moveToLast() // else // ++cursor // clamp() // hasPreferredX = false // } // K.LEFT or K.SHIFT -> { // clamp() // prepSelectionAtCursor() // // move selection left // if (selectEnd > 0) // --selectEnd // cursor = selectEnd // hasPreferredX = false // } // K.WORDLEFT -> // if (hasSelection) moveToFirst() // else { // cursor = moveWordLeft(cursor) // clamp() // } // K.WORDLEFT or K.SHIFT -> { // if (!hasSelection) // prepSelectionAtCursor() // cursor = moveWordLeft(cursor) // selectEnd = cursor // clamp() // } // K.WORDRIGHT -> // if (hasSelection) moveToLast() // else { // cursor = moveWordRight(cursor) // clamp() // } // K.WORDRIGHT or K.SHIFT -> { // if (!hasSelection) prepSelectionAtCursor() // cursor = moveWordRight(cursor) // selectEnd = cursor // clamp() // } // K.RIGHT or K.SHIFT -> { // prepSelectionAtCursor() // ++selectEnd // move selection right // clamp() // cursor = selectEnd // hasPreferredX = false // } // K.DOWN, K.DOWN or K.SHIFT -> { // val find = FindState() // val row = Row() // val sel = key has K.SHIFT // // if (singleLine) // key(K.RIGHT or (key and K.SHIFT)) // on windows, up&down in single-line behave like left&right // // if (sel) prepSelectionAtCursor() // else if (hasSelection) moveToLast() // // // compute current position of cursor point // clamp() // findCharpos(find, cursor, singleLine) // // // now find character position down a row // if (find.length != 0) { // val goalX = if (hasPreferredX) preferredX else find.x // var x = row.x0 // val start = find.firstChar + find.length // cursor = start // layoutRow(row, cursor) // for (i in 0 until row.numChars) { // val dx = getWidth(start, i) // if (dx == GETWIDTH_NEWLINE) // break // x += dx // if (x > goalX) // break // ++cursor // } // clamp() // // hasPreferredX = true // preferredX = goalX // // if (sel) selectEnd = cursor // } // Unit // } // K.UP, K.UP or K.SHIFT -> { // val find = FindState() // val row = Row() // var i = 0 // val sel = key has K.SHIFT // // if (singleLine) // key(K.LEFT or (key and K.SHIFT)) // on windows, up&down become left&right // // if (sel) prepSelectionAtCursor() // else if (hasSelection) moveToFirst() // // // compute current position of cursor point // clamp() // findCharpos(find, cursor, singleLine) // // // can only go up if there's a previous row // if (find.prevFirst != find.firstChar) { // // now find character position up a row // val goalX = if (hasPreferredX) preferredX else find.x // cursor = find.prevFirst // layoutRow(row, cursor) // var x = row.x0 // while (i < row.numChars) { // val dx = getWidth(find.prevFirst, i++) // if (dx == GETWIDTH_NEWLINE) // break // x += dx // if (x > goalX) // break // ++cursor // } // clamp() // // hasPreferredX = true // preferredX = goalX // // if (sel) selectEnd = cursor // } // Unit // } // K.DELETE, K.DELETE or K.SHIFT -> { // if (hasSelection) deleteSelection() // else if (cursor < stringLen) // delete(cursor, 1) // hasPreferredX = false // } // K.BACKSPACE, K.BACKSPACE or K.SHIFT -> { // if (hasSelection) deleteSelection() // else { // clamp() // if (cursor > 0) { // delete(cursor - 1, 1) // --cursor // } // } // hasPreferredX = false // } // K.TEXTSTART -> { // cursor = 0 // selectStart = 0 // selectEnd = 0 // hasPreferredX = false // } // K.TEXTEND -> { // cursor = stringLen // selectStart = 0 // selectEnd = 0 // hasPreferredX = false // } // K.TEXTSTART or K.SHIFT -> { // prepSelectionAtCursor() // cursor = 0 // selectEnd = 0 // hasPreferredX = false // } // K.TEXTEND or K.SHIFT -> { // prepSelectionAtCursor() // cursor = stringLen // selectEnd = cursor // hasPreferredX = false // } // K.LINESTART -> { // clamp() // moveToFirst() // if (singleLine) // cursor = 0 // else while (cursor > 0 && getChar(cursor - 1) != '\n') // --cursor // hasPreferredX = false // } // K.LINEEND -> { // val n = stringLen // clamp() // moveToFirst() // if (singleLine) // cursor = n // else while (cursor < n && getChar(cursor) != 'n') // ++cursor // hasPreferredX = false // } // K.LINESTART or K.SHIFT -> { // clamp() // prepSelectionAtCursor() // if (singleLine) // cursor = 0 // else while (cursor > 0 && getChar(cursor - 1) != '\n') // --cursor // selectEnd = cursor // stb.hasPreferredX = false // } // K.LINEEND or K.SHIFT -> { // val n = stringLen // clamp() // prepSelectionAtCursor() // if (singleLine) // cursor = n // else while (cursor < n && getChar(cursor) != '\n') // ++cursor // selectEnd = cursor // hasPreferredX = false // } // else -> { // val c = keyToText(key) // if (c > 0) { // val ch = c.c // // can't add newline in single-line mode // if (ch == '\n' && singleLine) return@with // // if (insertMode && !hasSelection && cursor < stringLen) { // makeundoReplace(cursor, 1, 1) // deleteChars(cursor, 1) // if (insertChars(cursor, charArrayOf(ch), 0, 1)) { // ++cursor // hasPreferredX = false // } // } else { // deleteSelection() // implicitly clamps // if (insertChars(cursor, charArrayOf(ch), 0, 1)) { // makeundoInsert(cursor, 1) // ++cursor // hasPreferredX = false // } // } // } // } // } // } }
mit
8f2a45364588dfa1a1aad9f04e13cc0d
33.545378
138
0.470249
4.288785
false
false
false
false
prt2121/Ktown
app/src/main/kotlin/com/prt2121/ktown/MyActivity.kt
1
4924
package com.prt2121.ktown import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.Toolbar import android.view.Menu import com.github.salomonbrys.kotson.fromJson import com.google.gson.GsonBuilder import com.jakewharton.rxbinding.support.v4.widget.RxSwipeRefreshLayout import com.jakewharton.rxbinding.support.v7.widget.RxRecyclerView import com.jakewharton.rxbinding.support.v7.widget.RxToolbar import com.jakewharton.rxbinding.view.RxView import com.squareup.okhttp.Callback import com.squareup.okhttp.OkHttpClient import com.squareup.okhttp.Request import com.squareup.okhttp.Response import rx.Observable import rx.Subscription import rx.android.schedulers.AndroidSchedulers import timber.log.Timber import java.io.IOException import java.util.concurrent.TimeUnit /** * Created by pt2121 on 10/26/15. */ open class MyActivity : AppCompatActivity() { val client = OkHttpClient() var userList: MutableList<User> = arrayListOf() var adapter: UserListAdapter = UserListAdapter(userList) var subscription: Subscription? = null val visibleThreshold = 5 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_rx) val refreshButton = findViewById(R.id.refreshButton) as FloatingActionButton val recyclerView = findViewById(R.id.recyclerView) as RecyclerView val swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout) as SwipeRefreshLayout val toolbar = findViewById(R.id.toolbar) as Toolbar val layoutManager = LinearLayoutManager(this) setSupportActionBar(toolbar) recyclerView.adapter = adapter recyclerView.layoutManager = layoutManager val menuClickStream = RxToolbar.itemClicks(toolbar) .filter { it.itemId == R.id.action_refresh } .map { Unit } val refreshClickStream = RxView.clicks(refreshButton) .mergeWith(RxSwipeRefreshLayout.refreshes(swipeRefreshLayout)) .map { Unit } .mergeWith(menuClickStream) val requestStream = refreshClickStream .startWith(Unit) .map { it -> var randomOffset = Math.floor(Math.random() * 500); "https://api.github.com/users?since=$randomOffset"; } val responseStream: Observable<List<User>> = requestStream.flatMap { url -> getJson(url) } .map { jsonString -> GsonBuilder().create().fromJson<List<User>>(jsonString) } RxRecyclerView.scrollEvents(recyclerView) .map { event -> val view = event.view() val manager = view.layoutManager as LinearLayoutManager val totalItemCount = manager.itemCount val visibleItemCount = view.childCount val firstVisibleItem = manager.findFirstVisibleItemPosition() (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold) } .distinctUntilChanged() .filter { it }.throttleLast(2, TimeUnit.SECONDS) .map { it -> var randomOffset = Math.floor(Math.random() * 500); "https://api.github.com/users?since=$randomOffset"; } .flatMap { url -> getJson(url) } .map { jsonString -> GsonBuilder().create().fromJson<List<User>>(jsonString) } .observeOn(AndroidSchedulers.mainThread()) .subscribe({ users -> userList.addAll(users!!.toList()) adapter.notifyDataSetChanged() }, { Timber.e(it.message) }) subscription = responseStream .observeOn(AndroidSchedulers.mainThread()) .subscribe({ users -> swipeRefreshLayout.isRefreshing = false userList.clear() userList.addAll(users) adapter.notifyDataSetChanged() }, { Timber.e(it.message) }) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onDestroy() { super.onDestroy() if (subscription != null && subscription!!.isUnsubscribed) { subscription?.unsubscribe() } } private fun getJson(url: String): Observable<String> { return Observable.create { observer -> val request = Request.Builder() .url(url) .build() client.newCall(request).enqueue(object : Callback { override fun onFailure(request: Request, e: IOException) { if (!observer.isUnsubscribed) { observer.onError(e) } } override fun onResponse(response: Response) { if (!observer.isUnsubscribed) { observer.onNext(response.body().string()) observer.onCompleted() } } }) } } }
apache-2.0
553e465688ad3b061104d7ba87cfa6b8
33.683099
94
0.689074
4.702961
false
false
false
false
WilliamHester/Breadit-2
app/app/src/main/java/me/williamhester/reddit/ui/activities/LogInActivity.kt
1
1908
package me.williamhester.reddit.ui.activities import android.app.Activity import android.os.Bundle import io.realm.Realm import me.williamhester.reddit.R import me.williamhester.reddit.messages.LogInFinishedMessage import me.williamhester.reddit.models.AccessTokenJson import me.williamhester.reddit.models.Account import me.williamhester.reddit.ui.fragments.LogInProgressFragment import me.williamhester.reddit.ui.fragments.LogInWebViewFragment import org.greenrobot.eventbus.Subscribe /** Activity responsible for handing user log in and returning them to the app, logged in. */ class LogInActivity : BaseActivity() { override val layoutId = R.layout.activity_content override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val fragment = fragmentManager.findFragmentById(R.id.fragment_container) if (fragment == null) { supportFragmentManager.beginTransaction() .add(R.id.fragment_container, LogInWebViewFragment.newInstance()) .commit() } } fun startLogIn(code: String) { // Start blocking UI supportFragmentManager.beginTransaction() .replace(R.id.fragment_container, LogInProgressFragment.newInstance()) .commit() // Start request for token redditClient.logIn(code) } @Subscribe fun onLoggedIn(accessToken: AccessTokenJson) { val account = Account() account.accessToken = accessToken.accessToken account.refreshToken = accessToken.refreshToken // Get the account info redditClient.getMe(account) } @Subscribe fun onAccountDetailsReceived(logInFinished: LogInFinishedMessage) { // Set the active account accountManager.setAccount(logInFinished.account) // Save the account Realm.getDefaultInstance().executeTransaction { it.copyToRealmOrUpdate(logInFinished.account) } setResult(Activity.RESULT_OK) finish() } }
apache-2.0
5cfea1f7c237556051ba5028d22d1cc4
30.8
93
0.757338
4.586538
false
false
false
false
google/android-fhir
contrib/barcode/src/main/java/com/google/android/fhir/datacapture/contrib/views/barcode/mlkit/md/camera/WorkflowModel.kt
1
1838
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.fhir.datacapture.contrib.views.barcode.mlkit.md.camera import android.app.Application import android.content.Context import androidx.annotation.MainThread import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import com.google.mlkit.vision.barcode.Barcode import java.util.HashSet /** View model for handling application workflow based on camera preview. */ class WorkflowModel(application: Application) : AndroidViewModel(application) { val workflowState = MutableLiveData<WorkflowState>() val detectedBarcode = MutableLiveData<Barcode>() private val objectIdsToSearch = HashSet<Int>() var isCameraLive = false private set private val context: Context get() = getApplication<Application>().applicationContext /** State set of the application workflow. */ enum class WorkflowState { NOT_STARTED, DETECTING, DETECTED, CONFIRMING, CONFIRMED, SEARCHING, SEARCHED } @MainThread fun setWorkflowState(workflowState: WorkflowState) { this.workflowState.value = workflowState } fun markCameraLive() { isCameraLive = true objectIdsToSearch.clear() } fun markCameraFrozen() { isCameraLive = false } }
apache-2.0
79ca06e937c8c0588a00f17cfeecc12e
27.276923
81
0.750272
4.428916
false
false
false
false
Apolline-Lille/apolline-android
app/src/main/java/science/apolline/utils/CheckUtility.kt
1
7149
package science.apolline.utils import android.Manifest import android.annotation.SuppressLint import android.content.Context import android.content.Context.LOCATION_SERVICE import android.content.Intent import android.content.pm.PackageManager import android.location.LocationManager import android.net.ConnectivityManager import android.net.NetworkInfo import android.net.Uri import android.net.wifi.WifiManager import android.os.Build import android.os.PowerManager import android.provider.Settings import android.support.v4.content.ContextCompat import android.support.v7.app.AlertDialog import android.telephony.TelephonyManager import android.widget.Toast import es.dmoral.toasty.Toasty import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.info import java.util.* import java.text.SimpleDateFormat /** * Created by sparow on 22/12/2017. */ object CheckUtility : AnkoLogger { /** * To get device consuming netowork type is 2g,3g,4g * * @param context * @return "2g","3g","4g" as a String based on the network type */ fun getNetworkType(context: Context): String { val mTelephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager val networkType = mTelephonyManager.networkType return when (networkType) { TelephonyManager.NETWORK_TYPE_GPRS, TelephonyManager.NETWORK_TYPE_EDGE, TelephonyManager.NETWORK_TYPE_CDMA, TelephonyManager.NETWORK_TYPE_1xRTT, TelephonyManager.NETWORK_TYPE_IDEN -> "2G" TelephonyManager.NETWORK_TYPE_UMTS, TelephonyManager.NETWORK_TYPE_EVDO_0, TelephonyManager.NETWORK_TYPE_EVDO_A, TelephonyManager.NETWORK_TYPE_HSDPA, TelephonyManager.NETWORK_TYPE_HSUPA, TelephonyManager.NETWORK_TYPE_HSPA, TelephonyManager.NETWORK_TYPE_EVDO_B, TelephonyManager.NETWORK_TYPE_EHRPD, TelephonyManager.NETWORK_TYPE_HSPAP -> "3G" TelephonyManager.NETWORK_TYPE_LTE -> "4G" else -> "Notfound" } } private fun checkNetworkStatus(context: Context): String { val networkStatus: String val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager //Check Wifi val wifi = manager.activeNetworkInfo //Check for mobile data val mobile = manager.activeNetworkInfo if (wifi.type == ConnectivityManager.TYPE_WIFI) { networkStatus = "wifi" } else if (mobile.type == ConnectivityManager.TYPE_MOBILE) { networkStatus = "mobileData" } else { networkStatus = "noNetwork" } return networkStatus } /** * To check device has internet * * @param context * @return boolean as per status */ fun isNetworkConnected(context: Context): Boolean { val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val netInfo: NetworkInfo? = cm.activeNetworkInfo return netInfo != null && netInfo.isConnected } fun isWifiNetworkConnected(context: Context): Boolean { var wifiNetworkState = false val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val netInfo : NetworkInfo? = cm.activeNetworkInfo if (netInfo?.type == ConnectivityManager.TYPE_WIFI) wifiNetworkState = true return netInfo != null && wifiNetworkState } fun checkFineLocationPermission(context: Context): Boolean { return ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED } fun checkReandPhoneStatePermission(context: Context): Boolean { return ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED } fun checkWriteToExternalStoragePermissionPermission(context: Context): Boolean { return ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED } fun canGetLocation(context: Context): Boolean { var gpsEnabled = false var networkEnabled = false val lm = context.getSystemService(LOCATION_SERVICE) as LocationManager try { gpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER) } catch (ex: Exception) { } try { networkEnabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER) } catch (ex: Exception) { } return gpsEnabled || networkEnabled } fun requestLocation(context: Context): AlertDialog { val alertDialog = AlertDialog.Builder(context).create() if (!canGetLocation(context)) { alertDialog.setMessage("Your GPS seems to be disabled, do you want to enable it?") alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "No") { _, _ -> Toasty.warning(context, "Your GPS is disabled", Toast.LENGTH_SHORT, true).show() } alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Yes") { _, _ -> val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS) context.startActivity(intent) } alertDialog.show() } return alertDialog } @SuppressLint("BatteryLife") fun requestDozeMode(context: Context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val intent = Intent() val packageName = context.packageName val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager if (!pm.isIgnoringBatteryOptimizations(packageName)) { intent.action = Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS intent.data = Uri.parse("package:$packageName") context.startActivity(intent) } } } fun requestPartialWakeUp(context: Context, timeout: Long): PowerManager.WakeLock { val packageName = context.packageName val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager val wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, packageName) wl.acquire(timeout) info("Partial wake up is: " + wl.isHeld) return wl } fun requestWifiFullMode(context: Context): WifiManager.WifiLock { val packageName = context.packageName val pm = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager val wf = pm.createWifiLock(WifiManager.WIFI_MODE_FULL, packageName) wf.acquire() info("WiFi full mode is: " + wf.isHeld) return wf } fun newDate() : String { val c = Calendar.getInstance().time val df = SimpleDateFormat("dd-MMM-yyyy", Locale.FRANCE) return df.format(c) } fun dateParser(timestamp: Long): String { val c = Date(timestamp / 1000000) val df = SimpleDateFormat("dd-MMM-yyyy HH:mm:ss", Locale.FRANCE) return df.format(c) } }
gpl-3.0
fac8e1d1a88a09361228e7f2dd197833
36.046632
138
0.679116
4.734437
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/stubs/AnnotationValues.kt
13
2041
package test import test.E.E1 import kotlin.reflect.KClass annotation class Simple( val i: Int, val l: Long, val b: Byte, val d: Double, val f: Float, val c: Char, val b1: Boolean, val b2: Boolean ) @Simple( 12, 12L, 12, 3.3, f = 3.3F, c = 'a', b1 = true, b2 = false ) class WithSimple // =============================== annotation class StringLiteral( val s1: String, val s2: String, val s3: String ) const val CONSTANT = 12 @StringLiteral("some", "", "H$CONSTANT") class WithStringLiteral // =============================== enum class E { E1, E2 } annotation class EnumLiteral( val e1: E, val e2: E, val e3: E ) @EnumLiteral(E1, E.E2, e3 = test.E.E2) class WithEnumLiteral // =============================== annotation class VarArg( vararg val v: Int ) @VarArg(1, 2, 3) class WithVarArg // =============================== annotation class Arrays( val ia: IntArray, val la: LongArray, val fa: FloatArray, val da: DoubleArray, val ca: CharArray, val ba: BooleanArray ) @Arrays( [1, 2, 3], [1L], [], [2.2], ['a'], [true, false] ) class WithArrays // =============================== annotation class ClassLiteral( val c1: KClass<*>, val c2: KClass<*>, val c3: KClass<*> ) @ClassLiteral( WithClassLiteral::class, String::class, T::class // Error intentionally ) class WithClassLiteral<T> // =============================== annotation class Nested( val i: Int, val s: String ) annotation class Outer( val some: String, val nested: Nested ) @Outer("value", nested = Nested(12, "nested value")) class WithNested // ============================== annotation class ArraysSpread( vararg val ia: Int ) @ArraysSpread( *[1, 2, 3] ) class WithSpreadOperatorArrays @SomeAnno1(x = (1 + 2).toLong()) @SomeAnno2(x = 1.toLong()) @SomeAnno3(x = 1.toLong() + 2) @SomeAnno4(x = 1 + some.value + 2) class WithComplexDotQualifiedAnnotation
apache-2.0
706a173a51c8faa9c4e875b92a1e009a
13.905109
52
0.544831
3.291935
false
false
false
false
ngthtung2805/dalatlaptop
app/src/main/java/com/tungnui/abccomputer/activity/OrderDetailActivity.kt
1
5612
package com.tungnui.abccomputer.activity import android.os.Bundle import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.LinearLayoutManager import android.util.Log import android.view.MenuItem import android.view.View import android.widget.Toast import com.tungnui.abccomputer.R import com.tungnui.abccomputer.adapter.OrderDetailAdapter import com.tungnui.abccomputer.adapter.RecyclerDividerDecorator import com.tungnui.abccomputer.api.OrderServices import com.tungnui.abccomputer.api.ServiceGenerator import com.tungnui.abccomputer.data.constant.AppConstants import com.tungnui.abccomputer.model.OrderItem import com.tungnui.abccomputer.models.Order import com.tungnui.abccomputer.utils.DialogUtils import com.tungnui.abccomputer.utils.formatPrice import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.activity_order_detail.* import kotlinx.android.synthetic.main.view_common_loader.* import java.util.ArrayList class OrderDetailActivity : BaseActivity() { private var orderService : OrderServices private var orderList: ArrayList<OrderItem> init { orderList = ArrayList() orderService = ServiceGenerator.createService(OrderServices::class.java) } private lateinit var productAdapter: OrderDetailAdapter private var orderId:Int=0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val intent = intent if (intent.hasExtra(AppConstants.KEY_ORDER_DETAIL)) { orderId = intent.getIntExtra(AppConstants.KEY_ORDER_DETAIL,0) } initView() initToolbar() initListener() loadData() } private fun initView() { setContentView(R.layout.activity_order_detail) initToolbar() setToolbarTitle("Chi tiết đơn hàng") enableBackButton() order_detail_recycler.addItemDecoration(RecyclerDividerDecorator(this)) order_detail_recycler.itemAnimator = DefaultItemAnimator() order_detail_recycler.setHasFixedSize(true) order_detail_recycler.layoutManager = LinearLayoutManager(this) productAdapter = OrderDetailAdapter() order_detail_recycler.adapter = productAdapter } private fun loadData(){ val progressDialog = DialogUtils.showProgressDialog(this@OrderDetailActivity, getString(R.string.msg_loading), false) Log.e("OrderList2",orderId.toString()) var disposable = orderService.single(orderId) .subscribeOn((Schedulers.io())) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ item -> item?.let{ productAdapter.refreshItems(item.lineItems!!) tvTempPrice.text =item.total?.formatPrice() tvTotalPrice.text=item.total?.formatPrice() tvDiscount.text = item.shippingTotal?.formatPrice() tvPaymentMethod.text= item.paymentMethodTitle if(item.shippingTotal?.toDouble() == 0.0){ tvShippingMethod.text = "Nhận tại cửa hàng" tvShippingFee.text="Miễn phí" } else{ tvShippingMethod.text = "Giao hàng tận nhà" tvShippingFee.text=item.shippingTotal } if(item.status == "pending"){ footerView.visibility = View.VISIBLE }else{ footerView.visibility = View.GONE } } DialogUtils.dismissProgressDialog(progressDialog) }, { error -> Log.e("OrderList",error.message) DialogUtils.dismissProgressDialog(progressDialog) }) } private fun initListener() { btnCancelOrder.setOnClickListener { cancelOrder() } } private fun cancelOrder() { DialogUtils.showDialogPrompt(this, null, getString(R.string.cancel_order_item), getString(R.string.dialog_btn_yes), getString(R.string.dialog_btn_no), true) { // start progress dialog val progressDialog = DialogUtils.showProgressDialog(this, getString(R.string.msg_loading), false) var temp = Order(status = "cancelled") orderService.update(orderId,temp) .subscribeOn((Schedulers.io())) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ item -> DialogUtils.dismissProgressDialog(progressDialog) if (item != null) { loadData() } }, { error -> showEmptyView() info_text.text = getString(R.string.empty) Toast.makeText(applicationContext, getString(R.string.failed), Toast.LENGTH_SHORT).show() }) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { finish() return true } else -> return super.onOptionsItemSelected(item) } } }
mit
2cdd6bf079d8db5c8ada14b501400b79
39.536232
166
0.600036
5.251643
false
false
false
false
spotify/heroic
heroic-core/src/main/java/com/spotify/heroic/shell/task/parameters/MetadataLoadParameters.kt
1
1472
/* * Copyright (c) 2019 Spotify AB. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.spotify.heroic.shell.task.parameters import com.spotify.heroic.shell.AbstractShellTaskParams import org.kohsuke.args4j.Option import java.nio.file.Path import java.nio.file.Paths internal class MetadataLoadParameters : AbstractShellTaskParams() { @Option(name = "-t", aliases = ["--target"], usage = "Backend group to migrate to", metaVar = "<metadata-group>") val target: String? = null @Option(name = "-f", usage = "File to load from", required = true) val file: Path = Paths.get("series") @Option(name = "-r", usage = "Rate-limit for writing to ES. 0 means disabled") val rate = 0 }
apache-2.0
2efe1394fa7e2320994ec5227ae17d71
37.736842
117
0.726902
3.98916
false
false
false
false
cdietze/klay
klay-demo/src/main/kotlin/klay/tests/core/DepthTest.kt
1
1074
package klay.tests.core import klay.scene.ImageLayer class DepthTest(game: TestsGame) : Test(game, "Depth", "Tests that layers added with non-zero depth are inserted/rendered in proper order.") { override fun init() { val depths = intArrayOf(0, -1, 1, 3, 2, -4, -3, 4, -2) val fills = intArrayOf(0xFF99CCFF.toInt(), 0xFFFFFF33.toInt(), 0xFF9933FF.toInt(), 0xFF999999.toInt(), 0xFFFF0033.toInt(), 0xFF00CC00.toInt(), 0xFFFF9900.toInt(), 0xFF0066FF.toInt(), 0x0FFCC6666.toInt()) val width = 200f val height = 200f for (ii in depths.indices) { val depth = depths[ii] val canvas = game.graphics.createCanvas(width, height) canvas.setFillColor(fills[ii]).fillRect(0f, 0f, width, height) canvas.setFillColor(0xFF000000.toInt()).drawText(depth.toString() + "/" + ii, 5f, 15f) val layer = ImageLayer(canvas.toTexture()) layer.setDepth(depth.toFloat()).setTranslation(225f - 50f * depth, 125f + 25f * depth) game.rootLayer.add(layer) } } }
apache-2.0
004080c9b326535db7ba121bf0169eee
47.818182
211
0.634078
3.475728
false
true
false
false
dahlstrom-g/intellij-community
plugins/kotlin/compiler-plugins/parcelize/common/src/org/jetbrains/kotlin/idea/compilerPlugin/parcelize/quickfixes/ParcelMigrateToParcelizeQuickFix.kt
4
14952
// 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.compilerPlugin.parcelize.quickfixes import com.intellij.openapi.diagnostic.Logger import org.jetbrains.kotlin.builtins.StandardNames import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ConstructorDescriptor import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.getOrCreateCompanionObject import org.jetbrains.kotlin.idea.intentions.branchedTransformations.unwrapBlockOrParenthesis import org.jetbrains.kotlin.idea.util.findAnnotation import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.load.java.JvmAbi.JVM_FIELD_ANNOTATION_FQ_NAME import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.idea.compilerPlugin.parcelize.KotlinParcelizeBundle import org.jetbrains.kotlin.parcelize.ParcelizeNames import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.addRemoveModifier.setModifierList import org.jetbrains.kotlin.psi.psiUtil.containingClass import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.typeRefHelpers.setReceiverTypeReference import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.descriptorUtil.getAllSuperClassifiers import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.source.KotlinSourceElement import org.jetbrains.kotlin.types.TypeUtils class ParcelMigrateToParcelizeQuickFix(function: KtClass) : AbstractParcelizeQuickFix<KtClass>(function) { companion object { private val PARCELER_FQNAME = FqName("kotlinx.parcelize.Parceler") private val PARCELER_WRITE_FUNCTION_NAME = Name.identifier("write") private val PARCELER_CREATE_FUNCTION_NAME = Name.identifier("create") private val LOG = Logger.getInstance(ParcelMigrateToParcelizeQuickFix::class.java) private fun KtClass.findParcelerCompanionObject(): Pair<KtObjectDeclaration, ClassDescriptor>? { for (obj in companionObjects) { val objDescriptor = obj.resolveToDescriptorIfAny() ?: continue for (superClassifier in objDescriptor.getAllSuperClassifiers()) { val superClass = superClassifier as? ClassDescriptor ?: continue if (superClass.fqNameSafe == PARCELER_FQNAME) return Pair(obj, objDescriptor) } } return null } private fun KtNamedFunction.doesLookLikeWriteToParcelOverride(): Boolean { return name == "writeToParcel" && hasModifier(KtTokens.OVERRIDE_KEYWORD) && receiverTypeReference == null && valueParameters.size == 2 && typeParameters.size == 0 && valueParameters[0].typeReference?.getFqName() == ParcelizeNames.PARCEL_ID.asFqNameString() && valueParameters[1].typeReference?.getFqName() == StandardNames.FqNames._int.asString() } private fun KtNamedFunction.doesLookLikeNewArrayOverride(): Boolean { return name == "newArray" && hasModifier(KtTokens.OVERRIDE_KEYWORD) && receiverTypeReference == null && valueParameters.size == 1 && typeParameters.size == 0 && valueParameters[0].typeReference?.getFqName() == StandardNames.FqNames._int.asString() } private fun KtNamedFunction.doesLookLikeDescribeContentsOverride(): Boolean { return name == "describeContents" && hasModifier(KtTokens.OVERRIDE_KEYWORD) && receiverTypeReference == null && valueParameters.size == 0 && typeParameters.size == 0 && typeReference?.getFqName() == StandardNames.FqNames._int.asString() } private fun KtClass.findWriteToParcelOverride() = findFunction { doesLookLikeWriteToParcelOverride() } private fun KtClass.findDescribeContentsOverride() = findFunction { doesLookLikeDescribeContentsOverride() } private fun KtObjectDeclaration.findNewArrayOverride() = findFunction { doesLookLikeNewArrayOverride() } private fun KtClass.findCreatorClass(): KtClassOrObject? { for (companion in companionObjects) { if (companion.name == "CREATOR") { return companion } val creatorProperty = companion.declarations.asSequence() .filterIsInstance<KtProperty>() .firstOrNull { it.name == "CREATOR" } ?: continue creatorProperty.findAnnotation(JVM_FIELD_ANNOTATION_FQ_NAME) ?: continue val initializer = creatorProperty.initializer ?: continue when (initializer) { is KtObjectLiteralExpression -> return initializer.objectDeclaration is KtCallExpression -> { val constructedClass = (initializer.resolveToCall() ?.resultingDescriptor as? ConstructorDescriptor)?.constructedClass if (constructedClass != null) { val sourceElement = constructedClass.source as? KotlinSourceElement (sourceElement?.psi as? KtClassOrObject)?.let { return it } } } } } return null } private fun KtNamedFunction.doesLookLikeCreateFromParcelOverride(): Boolean { return name == "createFromParcel" && hasModifier(KtTokens.OVERRIDE_KEYWORD) && receiverTypeReference == null && valueParameters.size == 1 && typeParameters.size == 0 && valueParameters[0].typeReference?.getFqName() == ParcelizeNames.PARCEL_ID.asFqNameString() } private fun findCreateFromParcel(creator: KtClassOrObject) = creator.findFunction { doesLookLikeCreateFromParcelOverride() } private fun KtNamedFunction.doesLookLikeWriteImplementation(): Boolean { val containingParcelableClassFqName = containingClassOrObject?.containingClass()?.fqName?.asString() return name == PARCELER_WRITE_FUNCTION_NAME.asString() && hasModifier(KtTokens.OVERRIDE_KEYWORD) && receiverTypeReference?.getFqName() == containingParcelableClassFqName && valueParameters.size == 2 && typeParameters.size == 0 && valueParameters[0].typeReference?.getFqName() == ParcelizeNames.PARCEL_ID.asFqNameString() && valueParameters[1].typeReference?.getFqName() == StandardNames.FqNames._int.asString() } private fun KtNamedFunction.doesLookLikeCreateImplementation(): Boolean { return name == PARCELER_CREATE_FUNCTION_NAME.asString() && hasModifier(KtTokens.OVERRIDE_KEYWORD) && receiverTypeReference == null && valueParameters.size == 1 && typeParameters.size == 0 && valueParameters[0].typeReference?.getFqName() == ParcelizeNames.PARCEL_ID.asFqNameString() } private fun KtObjectDeclaration.findCreateImplementation() = findFunction { doesLookLikeCreateImplementation() } private fun KtObjectDeclaration.findWriteImplementation() = findFunction { doesLookLikeWriteImplementation() } private fun KtClassOrObject.findFunction(f: KtNamedFunction.() -> Boolean) = declarations.asSequence().filterIsInstance<KtNamedFunction>().firstOrNull(f) private fun KtTypeReference.getFqName(): String? = analyze(BodyResolveMode.PARTIAL)[BindingContext.TYPE, this] ?.constructor?.declarationDescriptor?.fqNameSafe?.asString() } object FactoryForWrite : AbstractFactory({ findElement<KtClass>()?.let { ParcelMigrateToParcelizeQuickFix(it) } }) object FactoryForCREATOR : AbstractFactory({ findElement<KtObjectDeclaration>()?.getStrictParentOfType<KtClass>() ?.let { ParcelMigrateToParcelizeQuickFix(it) } }) override fun getText() = KotlinParcelizeBundle.message("parcelize.fix.migrate.to.parceler.companion.object") @Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE") override fun invoke(ktPsiFactory: KtPsiFactory, parcelableClass: KtClass) { val parcelerObject = parcelableClass.findParcelerCompanionObject()?.first ?: parcelableClass.getOrCreateCompanionObject() val bindingContext = parcelerObject.analyze(BodyResolveMode.PARTIAL) val parcelerTypeArg = parcelableClass.name ?: run { LOG.error("Parceler class should not be an anonymous class") return } val parcelerObjectDescriptor = bindingContext[BindingContext.CLASS, parcelerObject] ?: run { LOG.error("Unable to resolve parceler object for ${parcelableClass.name ?: "<unnamed Parcelable class>"}") return } if (!parcelerObjectDescriptor.getAllSuperClassifiers().any { it.fqNameSafe == PARCELER_FQNAME }) { val entryText = PARCELER_FQNAME.asString() + "<" + parcelerTypeArg + ">" parcelerObject.addSuperTypeListEntry(ktPsiFactory.createSuperTypeEntry(entryText)).shortenReferences() } val oldWriteToParcelFunction = parcelableClass.findWriteToParcelOverride() val oldCreateFromParcelFunction = parcelableClass.findCreatorClass()?.let { findCreateFromParcel(it) } for (superTypeEntry in parcelerObject.superTypeListEntries) { val superClass = bindingContext[BindingContext.TYPE, superTypeEntry.typeReference]?.constructor?.declarationDescriptor ?: continue if (superClass.getAllSuperClassifiers().any { it.fqNameSafe == ParcelizeNames.CREATOR_FQN }) { parcelerObject.removeSuperTypeListEntry(superTypeEntry) } } if (parcelerObject.name == "CREATOR") { parcelerObject.nameIdentifier?.delete() } if (oldWriteToParcelFunction != null) { parcelerObject.findWriteImplementation()?.delete() // Remove old implementation val newFunction = oldWriteToParcelFunction.copy() as KtFunction oldWriteToParcelFunction.delete() newFunction.setName(PARCELER_WRITE_FUNCTION_NAME.asString()) newFunction.setModifierList(ktPsiFactory.createModifierList(KtTokens.OVERRIDE_KEYWORD)) newFunction.setReceiverTypeReference(ktPsiFactory.createType(parcelerTypeArg)) newFunction.valueParameterList?.apply { assert(parameters.size == 2) val parcelParameterName = parameters[0].name ?: "parcel" val flagsParameterName = parameters[1].name ?: "flags" repeat(parameters.size) { removeParameter(0) } addParameter(ktPsiFactory.createParameter("$parcelParameterName : ${ParcelizeNames.PARCEL_ID.asFqNameString()}")) addParameter(ktPsiFactory.createParameter("$flagsParameterName : Int")) } parcelerObject.addDeclaration(newFunction).valueParameterList?.shortenReferences() } else if (parcelerObject.findWriteImplementation() == null) { val writeFunction = "fun $parcelerTypeArg.write(parcel: ${ParcelizeNames.PARCEL_ID.asFqNameString()}, flags: Int) = TODO()" parcelerObject.addDeclaration(ktPsiFactory.createFunction(writeFunction)).valueParameterList?.shortenReferences() } if (oldCreateFromParcelFunction != null) { parcelerObject.findCreateImplementation()?.delete() // Remove old implementation val newFunction = oldCreateFromParcelFunction.copy() as KtFunction if (oldCreateFromParcelFunction.containingClassOrObject == parcelerObject) { oldCreateFromParcelFunction.delete() } newFunction.setName(PARCELER_CREATE_FUNCTION_NAME.asString()) newFunction.setModifierList(ktPsiFactory.createModifierList(KtTokens.OVERRIDE_KEYWORD)) newFunction.setReceiverTypeReference(null) newFunction.valueParameterList?.apply { assert(parameters.size == 1) val parcelParameterName = parameters[0].name ?: "parcel" removeParameter(0) addParameter(ktPsiFactory.createParameter("$parcelParameterName : ${ParcelizeNames.PARCEL_ID.asFqNameString()}")) } parcelerObject.addDeclaration(newFunction).valueParameterList?.shortenReferences() } else if (parcelerObject.findCreateImplementation() == null) { val createFunction = "override fun create(parcel: ${ParcelizeNames.PARCEL_ID.asFqNameString()}): $parcelerTypeArg = TODO()" parcelerObject.addDeclaration(ktPsiFactory.createFunction(createFunction)).valueParameterList?.shortenReferences() } // Always use the default newArray() implementation parcelerObject.findNewArrayOverride()?.delete() parcelableClass.findDescribeContentsOverride()?.let { describeContentsFunction -> val returnExpr = describeContentsFunction.bodyExpression?.unwrapBlockOrParenthesis() if (returnExpr is KtReturnExpression && returnExpr.getTargetLabel() == null) { val returnValue = returnExpr.analyze()[BindingContext.COMPILE_TIME_VALUE, returnExpr.returnedExpression] ?.getValue(TypeUtils.NO_EXPECTED_TYPE) if (returnValue == 0) { // There are no additional overrides in the hierarchy if (bindingContext[BindingContext.FUNCTION, describeContentsFunction]?.overriddenDescriptors?.size == 1) { describeContentsFunction.delete() } } } } for (property in parcelerObject.declarations.asSequence().filterIsInstance<KtProperty>().filter { it.name == "CREATOR" }) { if (property.findAnnotation(JVM_FIELD_ANNOTATION_FQ_NAME) != null) { property.delete() } } } }
apache-2.0
26561fae34c66e26edefb26d8c1b2d2c
53.569343
158
0.664125
6.038772
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/dialog/DlgQuickTootMenu.kt
1
5047
package jp.juggler.subwaytooter.dialog import android.annotation.SuppressLint import android.app.AlertDialog import android.app.Dialog import android.view.View import android.view.WindowManager import android.widget.Button import android.widget.EditText import jp.juggler.util.dismissSafe import java.lang.ref.WeakReference import android.view.Gravity import jp.juggler.subwaytooter.* import jp.juggler.subwaytooter.api.entity.TootVisibility import jp.juggler.subwaytooter.pref.PrefS import jp.juggler.subwaytooter.pref.put class DlgQuickTootMenu( internal val activity: ActMain, internal val callback: Callback ) : View.OnClickListener { companion object { val etTextIds = intArrayOf( R.id.etText0, R.id.etText1, R.id.etText2, R.id.etText3, R.id.etText4, R.id.etText5 ) val btnTextIds = intArrayOf( R.id.btnText0, R.id.btnText1, R.id.btnText2, R.id.btnText3, R.id.btnText4, R.id.btnText5 ) val visibilityList = arrayOf( TootVisibility.AccountSetting, TootVisibility.WebSetting, TootVisibility.Public, TootVisibility.UnlistedHome, TootVisibility.PrivateFollowers, TootVisibility.DirectSpecified ) } interface Callback { fun onMacro(text: String) var visibility: TootVisibility } private var refDialog: WeakReference<Dialog>? = null fun toggle() { val dialog = refDialog?.get() if (dialog != null && dialog.isShowing) { dialog.dismissSafe() } else { show() } } private val etText = arrayOfNulls<EditText>(6) private lateinit var btnVisibility: Button @SuppressLint("InflateParams") fun show() { val view = activity.layoutInflater.inflate(R.layout.dlg_quick_toot_menu, null, false) view.findViewById<Button>(R.id.btnCancel).setOnClickListener(this) val btnListener: View.OnClickListener = View.OnClickListener { v -> val text = etText[v.tag as? Int ?: 0]?.text?.toString() if (text != null) { refDialog?.get()?.dismissSafe() callback.onMacro(text) } } val strings = loadStrings() val size = etText.size for (i in 0 until size) { val et: EditText = view.findViewById(etTextIds[i]) val btn: Button = view.findViewById(btnTextIds[i]) btn.tag = i btn.setOnClickListener(btnListener) etText[i] = et et.setText( if (i >= strings.size) { "" } else { strings[i] } ) } btnVisibility = view.findViewById(R.id.btnVisibility) btnVisibility.setOnClickListener(this) showVisibility() val dialog = Dialog(activity) this.refDialog = WeakReference(dialog) dialog.setCanceledOnTouchOutside(true) dialog.setContentView(view) dialog.setOnDismissListener { saveStrings() } dialog.window?.apply { val wlp = attributes wlp.gravity = Gravity.BOTTOM or Gravity.START wlp.flags = wlp.flags and WindowManager.LayoutParams.FLAG_DIM_BEHIND.inv() attributes = wlp setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT) } dialog.show() } private fun loadStrings() = PrefS.spQuickTootMacro(activity.pref).split("\n") private fun saveStrings() = activity.pref .edit() .put( PrefS.spQuickTootMacro, etText.joinToString("\n") { (it?.text?.toString() ?: "").replace("\n", " ") } ) .apply() override fun onClick(v: View?) { // TODO when (v?.id) { R.id.btnCancel -> refDialog?.get()?.dismissSafe() R.id.btnVisibility -> performVisibility() } } private fun performVisibility() { val captionList = visibilityList .map { Styler.getVisibilityCaption(activity, false, it) } .toTypedArray() AlertDialog.Builder(activity) .setTitle(R.string.choose_visibility) .setItems(captionList) { _, which -> if (which in visibilityList.indices) { callback.visibility = visibilityList[which] showVisibility() } } .setNegativeButton(R.string.cancel, null) .show() } private fun showVisibility() { btnVisibility.text = Styler.getVisibilityCaption(activity, false, callback.visibility) } }
apache-2.0
e1e8269a6faf4c7e86273e219eb84a03
28.221557
103
0.563107
4.668825
false
false
false
false
MarkusAmshove/Kluent
jvm/src/main/kotlin/org/amshove/kluent/JavaTimeComparators.kt
1
5536
package org.amshove.kluent import org.amshove.kluent.internal.assertTrue import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime abstract class AbstractJavaTimeComparator<T> where T : Comparable<T> { internal var comparatorType = ComparatorType.Exactly internal lateinit var startValue: T internal fun assertAfter(theOther: T) = when (comparatorType) { ComparatorType.AtLeast -> assertAtLeastAfter(calculateComparedValue(theOther)) ComparatorType.Exactly -> assertExactlyAfter(calculateComparedValue(theOther)) ComparatorType.AtMost -> assertAtMostAfter(calculateComparedValue(theOther)) } internal fun assertBefore(theOther: T) = when (comparatorType) { ComparatorType.AtLeast -> assertAtLeastBefore(calculateComparedValue(theOther, -1)) ComparatorType.Exactly -> assertExactlyBefore(calculateComparedValue(theOther, -1)) ComparatorType.AtMost -> assertAtMostBefore(calculateComparedValue(theOther, -1)) } internal fun withStartValue(startValue: T): AbstractJavaTimeComparator<T> { this.startValue = startValue return this } internal fun withComparatorType(comparatorType: ComparatorType): AbstractJavaTimeComparator<T> { this.comparatorType = comparatorType return this } protected fun assertAtLeastAfter(theOther: T) { assertTrue( "Expected $startValue to be at least { ${getExpectedOffset()} } after $theOther", startValue >= theOther ) } protected fun assertAtMostAfter(theOther: T) { assertTrue( "Expected $startValue to be at most { ${getExpectedOffset()} } after $theOther", startValue <= theOther ) } protected fun assertExactlyAfter(theOther: T) { assertTrue("Expected $startValue to be { ${getExpectedOffset()} } after $theOther", startValue == theOther) } protected fun assertExactlyBefore(theOther: T) { assertTrue("Expected $startValue to be { ${getExpectedOffset()} } before $theOther", startValue == theOther) } protected fun assertAtLeastBefore(theOther: T) { assertTrue( "Expected $startValue to be at least { ${getExpectedOffset()} } before $theOther", startValue <= theOther ) } protected fun assertAtMostBefore(theOther: T) { assertTrue( "Expected $startValue to be at most { ${getExpectedOffset()} } before $theOther", startValue >= theOther ) } protected abstract fun calculateComparedValue(currentValue: T, multiplier: Int = 1): T internal abstract fun getExpectedOffset(): String } class DateTimeComparator( internal var dateComparator: DateComparator? = null, internal var timeComparator: TimeComparator? = null ) : AbstractJavaTimeComparator<LocalDateTime>() { internal fun assertAfter(theDate: LocalDate) = dateComparator!!.withStartValue(startValue.toLocalDate()).withComparatorType(comparatorType) .assertAfter(theDate) internal fun assertBefore(theDate: LocalDate) = dateComparator!!.withStartValue(startValue.toLocalDate()).withComparatorType(comparatorType) .assertBefore(theDate) internal fun assertAfter(theTime: LocalTime) = timeComparator!!.withStartValue(startValue.toLocalTime()).withComparatorType(comparatorType) .assertAfter(theTime) internal fun assertBefore(theTime: LocalTime) = timeComparator!!.withStartValue(startValue.toLocalTime()).withComparatorType(comparatorType) .assertBefore(theTime) override fun getExpectedOffset() = "${dateComparator?.getExpectedOffset()} ${timeComparator?.getExpectedOffset()}".trim() override fun calculateComparedValue(currentValue: LocalDateTime, multiplier: Int) = currentValue.plusYears((dateComparator?.addedYears?.toLong() ?: 0) * multiplier) .plusMonths((dateComparator?.addedMonths?.toLong() ?: 0) * multiplier) .plusDays((dateComparator?.addedDays?.toLong() ?: 0) * multiplier) .plusHours((timeComparator?.addedHours?.toLong() ?: 0) * multiplier) .plusMinutes((timeComparator?.addedMinutes?.toLong() ?: 0) * multiplier) .plusSeconds((timeComparator?.addedSeconds?.toLong() ?: 0) * multiplier) } class DateComparator( internal val addedYears: Int = 0, internal val addedMonths: Int = 0, internal val addedDays: Int = 0 ) : AbstractJavaTimeComparator<LocalDate>() { override fun calculateComparedValue(currentValue: LocalDate, multiplier: Int) = currentValue.plusYears(addedYears.toLong() * multiplier) .plusMonths(addedMonths.toLong() * multiplier) .plusDays(addedDays.toLong() * multiplier) override fun getExpectedOffset() = "$addedYears years, $addedMonths months, $addedDays days" } class TimeComparator( internal val addedHours: Int = 0, internal val addedMinutes: Int = 0, internal val addedSeconds: Int = 0 ) : AbstractJavaTimeComparator<LocalTime>() { override fun getExpectedOffset() = "$addedHours hours, $addedMinutes minutes, $addedSeconds seconds" override fun calculateComparedValue(currentValue: LocalTime, multiplier: Int) = currentValue.plusHours(addedHours.toLong() * multiplier) .plusMinutes(addedMinutes.toLong() * multiplier) .plusSeconds(addedSeconds.toLong() * multiplier) }
mit
899e035387cc219b6008daeac039a2a6
38.542857
116
0.693642
5.144981
false
false
false
false
paplorinc/intellij-community
platform/configuration-store-impl/src/DirectoryBasedStorage.kt
2
8591
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.configurationStore import com.intellij.configurationStore.schemeManager.createDir import com.intellij.configurationStore.schemeManager.getOrCreateChild import com.intellij.openapi.application.runUndoTransparentWriteAction import com.intellij.openapi.components.PathMacroSubstitutor import com.intellij.openapi.components.StateSplitter import com.intellij.openapi.components.StateSplitterEx import com.intellij.openapi.components.impl.stores.DirectoryStorageUtil import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.LineSeparator import com.intellij.util.SmartList import com.intellij.util.containers.SmartHashSet import com.intellij.util.io.systemIndependentPath import com.intellij.util.isEmpty import gnu.trove.THashMap import gnu.trove.THashSet import org.jdom.Element import java.io.IOException import java.nio.ByteBuffer import java.nio.file.Path abstract class DirectoryBasedStorageBase(@Suppress("DEPRECATION") protected val splitter: StateSplitter, protected val pathMacroSubstitutor: PathMacroSubstitutor? = null) : StateStorageBase<StateMap>() { protected var componentName: String? = null protected abstract val virtualFile: VirtualFile? public override fun loadData(): StateMap = StateMap.fromMap(DirectoryStorageUtil.loadFrom(virtualFile, pathMacroSubstitutor)) override fun createSaveSessionProducer(): SaveSessionProducer? = null override fun analyzeExternalChangesAndUpdateIfNeed(componentNames: MutableSet<in String>) { // todo reload only changed file, compute diff val newData = loadData() storageDataRef.set(newData) if (componentName != null) { componentNames.add(componentName!!) } } override fun getSerializedState(storageData: StateMap, component: Any?, componentName: String, archive: Boolean): Element? { this.componentName = componentName if (storageData.isEmpty()) { return null } // FileStorageCoreUtil on load check both component and name attributes (critical important for external store case, where we have only in-project artifacts, but not external) val state = Element(FileStorageCoreUtil.COMPONENT).setAttribute(FileStorageCoreUtil.NAME, componentName) if (splitter is StateSplitterEx) { for (fileName in storageData.keys()) { val subState = storageData.getState(fileName, archive) ?: return null splitter.mergeStateInto(state, subState.clone()) } } else { val subElements = SmartList<Element>() for (fileName in storageData.keys()) { val subState = storageData.getState(fileName, archive) ?: return null subElements.add(subState.clone()) } if (!subElements.isEmpty()) { splitter.mergeStatesInto(state, subElements.toTypedArray()) } } return state } override fun hasState(storageData: StateMap, componentName: String): Boolean = storageData.hasStates() } open class DirectoryBasedStorage(private val dir: Path, @Suppress("DEPRECATION") splitter: StateSplitter, pathMacroSubstitutor: PathMacroSubstitutor? = null) : DirectoryBasedStorageBase(splitter, pathMacroSubstitutor) { override val isUseVfsForWrite: Boolean get() = true @Volatile private var cachedVirtualFile: VirtualFile? = null override val virtualFile: VirtualFile? get() { var result = cachedVirtualFile if (result == null) { result = LocalFileSystem.getInstance().findFileByPath(dir.systemIndependentPath) cachedVirtualFile = result } return result } internal fun setVirtualDir(dir: VirtualFile?) { cachedVirtualFile = dir } override fun createSaveSessionProducer(): SaveSessionProducer? = if (checkIsSavingDisabled()) null else MySaveSession(this, getStorageData()) private class MySaveSession(private val storage: DirectoryBasedStorage, private val originalStates: StateMap) : SaveSessionBase(), SaveSession { private var copiedStorageData: MutableMap<String, Any>? = null private val dirtyFileNames = SmartHashSet<String>() private var someFileRemoved = false override fun setSerializedState(componentName: String, element: Element?) { storage.componentName = componentName val stateAndFileNameList = if (element.isEmpty()) emptyList() else storage.splitter.splitState(element!!) if (stateAndFileNameList.isEmpty()) { if (copiedStorageData != null) { copiedStorageData!!.clear() } else if (!originalStates.isEmpty()) { copiedStorageData = THashMap() } return } val existingFiles = THashSet<String>(stateAndFileNameList.size) for (pair in stateAndFileNameList) { doSetState(pair.second, pair.first) existingFiles.add(pair.second) } for (key in originalStates.keys()) { if (existingFiles.contains(key)) { continue } if (copiedStorageData == null) { copiedStorageData = originalStates.toMutableMap() } someFileRemoved = true copiedStorageData!!.remove(key) } } private fun doSetState(fileName: String, subState: Element) { if (copiedStorageData == null) { copiedStorageData = setStateAndCloneIfNeed(fileName, subState, originalStates) if (copiedStorageData != null) { dirtyFileNames.add(fileName) } } else if (updateState(copiedStorageData!!, fileName, subState)) { dirtyFileNames.add(fileName) } } override fun createSaveSession() = if (storage.checkIsSavingDisabled() || copiedStorageData == null) null else this override fun save() { val stateMap = StateMap.fromMap(copiedStorageData!!) var dir = storage.virtualFile if (copiedStorageData!!.isEmpty()) { if (dir != null && dir.exists()) { deleteFile(this, dir) } storage.setStorageData(stateMap) return } if (dir == null || !dir.isValid) { dir = createDir(storage.dir, this) storage.cachedVirtualFile = dir } if (!dirtyFileNames.isEmpty) { saveStates(dir, stateMap) } if (someFileRemoved && dir.exists()) { deleteFiles(dir) } storage.setStorageData(stateMap) } private fun saveStates(dir: VirtualFile, states: StateMap) { for (fileName in states.keys()) { if (!dirtyFileNames.contains(fileName)) { continue } try { val element = states.getElement(fileName) ?: continue val file = dir.getOrCreateChild(fileName, this) // we don't write xml prolog due to historical reasons (and should not in any case) val macroManager = if (storage.pathMacroSubstitutor == null) null else (storage.pathMacroSubstitutor as TrackingPathMacroSubstitutorImpl).macroManager val xmlDataWriter = XmlDataWriter(FileStorageCoreUtil.COMPONENT, listOf(element), mapOf(FileStorageCoreUtil.NAME to storage.componentName!!), macroManager, dir.path) writeFile(null, this, file, xmlDataWriter, getOrDetectLineSeparator(file) ?: LineSeparator.getSystemLineSeparator(), false) } catch (e: IOException) { LOG.error(e) } } } private fun deleteFiles(dir: VirtualFile) { runUndoTransparentWriteAction { for (file in dir.children) { val fileName = file.name if (fileName.endsWith(FileStorageCoreUtil.DEFAULT_EXT) && !copiedStorageData!!.containsKey(fileName)) { if (file.isWritable) { file.delete(this) } else { throw ReadOnlyModificationException(file, null) } } } } } } private fun setStorageData(newStates: StateMap) { storageDataRef.set(newStates) } } private fun getOrDetectLineSeparator(file: VirtualFile): LineSeparator? { if (!file.exists()) { return null } file.detectedLineSeparator?.let { return LineSeparator.fromString(it) } val lineSeparator = detectLineSeparators(Charsets.UTF_8.decode(ByteBuffer.wrap(file.contentsToByteArray()))) file.detectedLineSeparator = lineSeparator.separatorString return lineSeparator }
apache-2.0
37ae9e0eb7ca15598e4ab7d41a008194
35.561702
179
0.694797
5.194075
false
false
false
false
paplorinc/intellij-community
platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/sync/utils.kt
1
4434
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.intellij.build.images.sync import java.io.File import java.io.OutputStream import java.io.PrintStream import java.util.concurrent.TimeUnit import java.util.function.Consumer internal var logger: Consumer<String> = Consumer { println(it) } internal fun log(msg: String) = logger.accept(msg) internal fun String.splitWithSpace(): List<String> = this.splitNotBlank(" ") internal fun String.splitNotBlank(delimiter: String): List<String> = this.split(delimiter).filter { it.isNotBlank() } internal fun String.splitWithTab(): List<String> = this.split("\t".toRegex()) internal fun execute(workingDir: File?, vararg command: String, withTimer: Boolean = false): String { val errOutputFile = File.createTempFile("errOutput", "txt") val processCall = { val process = ProcessBuilder(*command.filter { it.isNotBlank() }.toTypedArray()) .directory(workingDir) .redirectOutput(ProcessBuilder.Redirect.PIPE) .redirectError(errOutputFile) .apply { environment()["GIT_SSH_COMMAND"] = "ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no" environment()["LANG"] = "en_US.UTF-8" }.start() val output = process.inputStream.bufferedReader().use { it.readText() } process.waitFor(1, TimeUnit.MINUTES) val error = errOutputFile.readText().trim() if (process.exitValue() != 0) { error("Command ${command.joinToString(" ")} failed in ${workingDir?.absolutePath} with ${process.exitValue()} : $output\n$error") } output } return try { if (withTimer) callWithTimer("Executing command ${command.joinToString(" ")}", processCall) else processCall() } finally { errOutputFile.delete() } } internal fun <T> List<T>.split(eachSize: Int): List<List<T>> { if (this.size < eachSize) return listOf(this) val result = mutableListOf<List<T>>() var start = 0 while (start < this.size) { val sub = this.subList(start, Math.min(start + eachSize, this.size)) if (!sub.isEmpty()) result += sub start += eachSize } return result } internal fun <T> callSafely(printStackTrace: Boolean = false, call: () -> T): T? = try { call() } catch (e: Exception) { if (printStackTrace) e.printStackTrace() else log(e.message ?: e::class.java.simpleName) null } internal fun <T> callWithTimer(msg: String? = null, call: () -> T): T { if (msg != null) log(msg) val start = System.currentTimeMillis() try { return call() } finally { log("Took ${System.currentTimeMillis() - start} ms") } } internal fun <T> retry(maxRetries: Int = 20, secondsBeforeRetry: Long = 30, doRetry: (Throwable) -> Boolean = { true }, action: () -> T): T { repeat(maxRetries) { val number = it + 1 try { return action() } catch (e: Exception) { if (number < maxRetries && doRetry(e)) { log("$number attempt of $maxRetries has failed with ${e.message}. Retrying in ${secondsBeforeRetry}s..") TimeUnit.SECONDS.sleep(secondsBeforeRetry) } else throw e } } error("Unable to complete") } internal fun guessEmail(invalidEmail: String): Collection<String> { val (username, domain) = invalidEmail.split("@") val guesses = mutableListOf( username.splitNotBlank(".").joinToString(".", transform = String::capitalize) + "@$domain", invalidEmail.toLowerCase() ) if (domain != "jetbrains.com") guesses += "[email protected]" return guesses } internal inline fun <T> protectStdErr(block: () -> T): T { val err = System.err return try { block() } finally { System.setErr(err) } } private val mutedStream = PrintStream(object : OutputStream() { override fun write(b: ByteArray) {} override fun write(b: ByteArray, off: Int, len: Int) {} override fun write(b: Int) {} }) internal inline fun <T> muteStdOut(block: () -> T): T { val out = System.out System.setOut(mutedStream) return try { block() } finally { System.setOut(out) } } internal inline fun <T> muteStdErr(block: () -> T): T = protectStdErr { System.setErr(mutedStream) return block() } internal fun File.isAncestorOf(file: File): Boolean = this == file.parentFile || file.parentFile != null && isAncestorOf(file.parentFile)
apache-2.0
4524c75bb5629828d94329f7445d0c0b
30.678571
140
0.662156
3.799486
false
false
false
false
google/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/AssignmentExpressionUnfoldingConversion.kt
6
7392
// 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.conversions import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.parenthesizeIfCompoundExpression import org.jetbrains.kotlin.nj2k.tree.* import org.jetbrains.kotlin.utils.addToStdlib.safeAs class AssignmentExpressionUnfoldingConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { val unfolded = when (element) { is JKBlock -> element.convertAssignments() is JKExpressionStatement -> element.convertAssignments() is JKJavaAssignmentExpression -> element.convertAssignments() else -> null } ?: return recurse(element) return recurse(unfolded) } private fun JKBlock.convertAssignments(): JKBlock? { val hasAssignments = statements.any { it.containsAssignment() } if (!hasAssignments) return null val newStatements = mutableListOf<JKStatement>() for (statement in statements) { when { statement is JKExpressionStatement && statement.expression is JKJavaAssignmentExpression -> { val assignment = statement.expression as JKJavaAssignmentExpression newStatements += assignment .unfoldToStatementsList(assignmentTarget = null) .withFormattingFrom(statement) } statement is JKDeclarationStatement && statement.containsAssignment() -> { val variable = statement.declaredStatements.single() as JKVariable val assignment = variable.initializer as JKJavaAssignmentExpression newStatements += assignment .unfoldToStatementsList(variable.detached(statement)) .withFormattingFrom(statement) } else -> { newStatements += statement } } } statements = newStatements return this } private fun JKExpressionStatement.convertAssignments(): JKStatement? { val assignment = expression as? JKJavaAssignmentExpression ?: return null return when { canBeConvertedToBlock() && assignment.expression is JKJavaAssignmentExpression -> JKBlockStatement(JKBlockImpl(assignment.unfoldToStatementsList(assignmentTarget = null))) else -> createKtAssignmentStatement( assignment::field.detached(), assignment::expression.detached(), assignment.operator ) }.withFormattingFrom(this) } private fun JKExpressionStatement.canBeConvertedToBlock() = when (val parent = parent) { is JKLoopStatement -> parent.body == this is JKIfElseStatement -> parent.thenBranch == this || parent.elseBranch == this is JKJavaSwitchCase -> true else -> false } private fun JKJavaAssignmentExpression.convertAssignments() = unfoldToExpressionsChain().withFormattingFrom(this) private fun JKDeclarationStatement.containsAssignment() = declaredStatements.singleOrNull()?.safeAs<JKVariable>()?.initializer is JKJavaAssignmentExpression private fun JKStatement.containsAssignment() = when (this) { is JKExpressionStatement -> expression is JKJavaAssignmentExpression is JKDeclarationStatement -> containsAssignment() else -> false } private fun JKJavaAssignmentExpression.unfold() = generateSequence(this) { assignment -> assignment.expression as? JKJavaAssignmentExpression }.toList().asReversed() private fun JKJavaAssignmentExpression.unfoldToExpressionsChain(): JKExpression { val links = unfold() val first = links.first() return links.subList(1, links.size) .fold(first.toExpressionChainLink(first::expression.detached())) { state, assignment -> assignment.toExpressionChainLink(state) } } private fun JKJavaAssignmentExpression.unfoldToStatementsList(assignmentTarget: JKVariable?): List<JKStatement> { val links = unfold() val first = links.first() val statements = links.subList(1, links.size) .foldIndexed(listOf(first.toDeclarationChainLink(first::expression.detached()))) { index, list, assignment -> list + assignment.toDeclarationChainLink(links[index].field.copyTreeAndDetach()) } return when (assignmentTarget) { null -> statements else -> { assignmentTarget.initializer = statements.last().field.copyTreeAndDetach() statements + JKDeclarationStatement(listOf(assignmentTarget)) } } } private fun JKJavaAssignmentExpression.toExpressionChainLink(receiver: JKExpression): JKExpression { val assignment = createKtAssignmentStatement( this::field.detached(), JKKtItExpression(operator.returnType), operator ).withFormattingFrom(this) return when { operator.isSimpleToken() -> JKAssignmentChainAlsoLink(receiver, assignment, field.copyTreeAndDetach()) else -> JKAssignmentChainLetLink(receiver, assignment, field.copyTreeAndDetach()) } } private fun JKJavaAssignmentExpression.toDeclarationChainLink(expression: JKExpression) = createKtAssignmentStatement(this::field.detached(), expression, this.operator) .withFormattingFrom(this) private fun createKtAssignmentStatement( field: JKExpression, expression: JKExpression, operator: JKOperator ) = when { operator.isOnlyJavaToken() -> JKKtAssignmentStatement( field, JKBinaryExpression( field.copyTreeAndDetach(), expression.parenthesizeIfCompoundExpression(), JKKtOperatorImpl( onlyJavaAssignTokensToKotlinOnes[operator.token]!!, operator.returnType ) ), JKOperatorToken.EQ ) else -> JKKtAssignmentStatement(field, expression, operator.token) } private fun JKOperator.isSimpleToken() = when { isOnlyJavaToken() -> false token == JKOperatorToken.PLUSEQ || token == JKOperatorToken.MINUSEQ || token == JKOperatorToken.MULTEQ || token == JKOperatorToken.DIVEQ -> false else -> true } private fun JKOperator.isOnlyJavaToken() = token in onlyJavaAssignTokensToKotlinOnes companion object { private val onlyJavaAssignTokensToKotlinOnes = mapOf( JKOperatorToken.ANDEQ to JKOperatorToken.AND, JKOperatorToken.OREQ to JKOperatorToken.OR, JKOperatorToken.XOREQ to JKOperatorToken.XOR, JKOperatorToken.LTLTEQ to JKOperatorToken.SHL, JKOperatorToken.GTGTEQ to JKOperatorToken.SHR, JKOperatorToken.GTGTGTEQ to JKOperatorToken.USHR ) } }
apache-2.0
8d58e4b2b60af25455e2d02dc7f4c654
41.734104
125
0.644616
6.185774
false
false
false
false
google/intellij-community
platform/lang-impl/src/com/intellij/ide/bookmark/actions/extensions.kt
3
5098
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.bookmark.actions import com.intellij.ide.bookmark.Bookmark import com.intellij.ide.bookmark.BookmarkType import com.intellij.ide.bookmark.BookmarksManager import com.intellij.ide.bookmark.providers.LineBookmarkProvider import com.intellij.ide.bookmark.ui.BookmarksView import com.intellij.ide.bookmark.ui.BookmarksViewState import com.intellij.ide.bookmark.ui.tree.GroupNode import com.intellij.ide.util.treeView.AbstractTreeNode import com.intellij.ide.util.treeView.NodeDescriptor import com.intellij.ide.util.treeView.SmartElementDescriptor import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.editor.ex.EditorGutterComponentEx import com.intellij.openapi.project.LightEditActionFactory import com.intellij.openapi.wm.ToolWindowId import com.intellij.ui.speedSearch.SpeedSearchSupply import com.intellij.util.OpenSourceUtil import com.intellij.util.ui.UIUtil import com.intellij.util.ui.tree.TreeUtil import java.awt.event.ActionListener import java.awt.event.KeyEvent import javax.swing.JComponent import javax.swing.JTree import javax.swing.KeyStroke internal val AnActionEvent.bookmarksManager get() = project?.let { BookmarksManager.getInstance(it) } internal val AnActionEvent.bookmarksViewState get() = project?.let { BookmarksViewState.getInstance(it) } internal val AnActionEvent.bookmarksView get() = getData(BookmarksView.BOOKMARKS_VIEW) internal val AnActionEvent.bookmarkNodes: List<AbstractTreeNode<*>>? get() = bookmarksView?.let { getData(PlatformDataKeys.SELECTED_ITEMS)?.asList() as? List<AbstractTreeNode<*>> } internal val AnActionEvent.selectedGroupNode get() = bookmarkNodes?.singleOrNull() as? GroupNode internal val AnActionEvent.contextBookmark: Bookmark? get() { val editor = getData(CommonDataKeys.EDITOR) ?: getData(CommonDataKeys.EDITOR_EVEN_IF_INACTIVE) val project = editor?.project ?: project ?: return null if (editor != null) { val provider = LineBookmarkProvider.find(project) ?: return null val line = getData(EditorGutterComponentEx.LOGICAL_LINE_AT_CURSOR) return provider.createBookmark(editor, line) } val manager = BookmarksManager.getInstance(project) ?: return null val window = getData(PlatformDataKeys.TOOL_WINDOW) if (window?.id == ToolWindowId.BOOKMARKS) return null val component = getData(PlatformDataKeys.CONTEXT_COMPONENT) val allowed = UIUtil.getClientProperty(component, BookmarksManager.ALLOWED) ?: (window?.id == ToolWindowId.PROJECT_VIEW) if (!allowed) return null // TODO mouse shortcuts as in gutter/LOGICAL_LINE_AT_CURSOR val items = getData(PlatformDataKeys.SELECTED_ITEMS) if (items != null && items.size > 1) return null val item = items?.firstOrNull() ?: getData(CommonDataKeys.PSI_ELEMENT) ?: getData(CommonDataKeys.VIRTUAL_FILE) return when (item) { is AbstractTreeNode<*> -> manager.createBookmark(item.value) is SmartElementDescriptor -> manager.createBookmark(item.psiElement) is NodeDescriptor<*> -> manager.createBookmark(item.element) else -> manager.createBookmark(item) } } internal val Bookmark.bookmarksManager get() = BookmarksManager.getInstance(provider.project) internal val Bookmark.firstGroupWithDescription get() = bookmarksManager?.getGroups(this)?.firstOrNull { it.getDescription(this).isNullOrBlank().not() } /** * Creates and registers an action that navigates to a bookmark by a digit or a letter, if speed search is not active. */ internal fun JComponent.registerBookmarkTypeAction(parent: Disposable, type: BookmarkType) = createBookmarkTypeAction(type) .registerCustomShortcutSet(CustomShortcutSet.fromString(type.mnemonic.toString()), this, parent) /** * Creates an action that navigates to a bookmark by its type, if speed search is not active. */ private fun createBookmarkTypeAction(type: BookmarkType) = GotoBookmarkTypeAction(type) { null == it.bookmarksView?.run { SpeedSearchSupply.getSupply(tree) } } /** * Creates an action that navigates to a selected bookmark by the EditSource shortcut. */ internal fun JComponent.registerEditSourceAction(parent: Disposable) = LightEditActionFactory .create { OpenSourceUtil.navigate(*it.getData(CommonDataKeys.NAVIGATABLE_ARRAY)) } .registerCustomShortcutSet(CommonShortcuts.getEditSource(), this, parent) internal fun JTree.registerNavigateOnEnterAction() { val enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0) // perform previous action if the specified action is failed // it is needed to expand/collapse a tree node val oldListener = getActionForKeyStroke(enter) val newListener = ActionListener { when (val node = TreeUtil.getAbstractTreeNode(selectionPath)) { null -> oldListener?.actionPerformed(it) is GroupNode -> oldListener?.actionPerformed(it) else -> node.navigate(true) } } registerKeyboardAction(newListener, enter, JComponent.WHEN_FOCUSED) }
apache-2.0
59f7234902e2ce950db62fdfaea23180
44.115044
124
0.781679
4.475856
false
false
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/ide/feedback/FeedbackForm.kt
5
11090
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.feedback import com.intellij.CommonBundle import com.intellij.icons.AllIcons import com.intellij.ide.actions.AboutDialog import com.intellij.ide.actions.SendFeedbackAction import com.intellij.notification.Notification import com.intellij.notification.NotificationListener import com.intellij.notification.NotificationType import com.intellij.openapi.application.ApplicationBundle import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.ex.ApplicationInfoEx import com.intellij.openapi.application.impl.ZenDeskForm import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.ui.CollectionComboBoxModel import com.intellij.ui.LicensingFacade import com.intellij.ui.PopupBorder import com.intellij.ui.components.JBScrollPane import com.intellij.ui.components.JBTextArea import com.intellij.ui.components.TextComponentEmptyText import com.intellij.ui.components.dialog import com.intellij.ui.dsl.builder.* import com.intellij.ui.dsl.builder.panel import com.intellij.ui.dsl.gridLayout.HorizontalAlign import com.intellij.ui.dsl.gridLayout.VerticalAlign import com.intellij.ui.layout.* import com.intellij.util.ui.JBFont import com.intellij.util.ui.JBUI import org.jetbrains.annotations.Nls import java.awt.Component import java.awt.event.ActionEvent import java.awt.event.KeyAdapter import java.awt.event.KeyEvent import java.util.function.Predicate import javax.swing.AbstractAction import javax.swing.Action import javax.swing.JComboBox import javax.swing.JComponent import javax.swing.event.HyperlinkEvent private data class ZenDeskComboOption(val displayName: @Nls String, val id: String) { override fun toString(): String = displayName } private val topicOptions = listOf( ZenDeskComboOption(ApplicationBundle.message("feedback.form.topic.bug"), "ij_bug"), ZenDeskComboOption(ApplicationBundle.message("feedback.form.topic.howto"), "ij_howto"), ZenDeskComboOption(ApplicationBundle.message("feedback.form.topic.problem"), "ij_problem"), ZenDeskComboOption(ApplicationBundle.message("feedback.form.topic.suggestion"), "ij_suggestion"), ZenDeskComboOption(ApplicationBundle.message("feedback.form.topic.misc"), "ij_misc") ) class FeedbackForm( private val project: Project?, val form: ZenDeskForm, val isEvaluation: Boolean ) : DialogWrapper(project, false) { private var details = "" private var email = LicensingFacade.INSTANCE?.getLicenseeEmail().orEmpty() private var needSupport = false private var shareSystemInformation = false private var ratingComponent: RatingComponent? = null private var missingRatingTooltip: JComponent? = null private var topic: ZenDeskComboOption? = null private lateinit var topicComboBox: JComboBox<ZenDeskComboOption?> init { title = if (isEvaluation) ApplicationBundle.message("feedback.form.title") else ApplicationBundle.message("feedback.form.prompt") init() } override fun createCenterPanel(): JComponent { return panel { if (isEvaluation) { row { label(ApplicationBundle.message("feedback.form.evaluation.prompt")).applyToComponent { font = JBFont.h1() } } row { label(ApplicationBundle.message("feedback.form.comment")) } row { label(ApplicationBundle.message("feedback.form.rating", ApplicationNamesInfo.getInstance().fullProductName)) } row { ratingComponent = RatingComponent().also { it.addPropertyChangeListener { evt -> if (evt.propertyName == RatingComponent.RATING_PROPERTY) { missingRatingTooltip?.isVisible = false } } cell(it) } missingRatingTooltip = label(ApplicationBundle.message("feedback.form.rating.required")).applyToComponent { border = JBUI.Borders.compound(PopupBorder.Factory.createColored(JBUI.CurrentTheme.Validator.errorBorderColor()), JBUI.Borders.empty(4, 8)) background = JBUI.CurrentTheme.Validator.errorBackgroundColor() isVisible = false isOpaque = true }.component } } else { row { topicComboBox = comboBox(CollectionComboBoxModel(topicOptions)) .label(ApplicationBundle.message("feedback.form.topic"), LabelPosition.TOP) .bindItem({ topic }, { topic = it}) .errorOnApply(ApplicationBundle.message("feedback.form.topic.required")) { it.selectedItem == null }.component icon(AllIcons.General.BalloonInformation) .gap(RightGap.SMALL) .visibleIf(topicComboBox.selectedValueMatches { it?.id == "ij_bug" }) text(ApplicationBundle.message("feedback.form.issue")) { SendFeedbackAction.submit(project, ApplicationInfoEx.getInstanceEx().youtrackUrl, SendFeedbackAction.getDescription(project)) }.visibleIf(topicComboBox.selectedValueMatches { it?.id == "ij_bug" }) } } row { val label = if (isEvaluation) ApplicationBundle.message("feedback.form.evaluation.details") else ApplicationBundle.message("feedback.form.details") textArea() .label(label, LabelPosition.TOP) .bindText(::details) .horizontalAlign(HorizontalAlign.FILL) .verticalAlign(VerticalAlign.FILL) .rows(5) .focused() .errorOnApply(ApplicationBundle.message("feedback.form.details.required")) { it.text.isBlank() } .applyToComponent { emptyText.text = if (isEvaluation) ApplicationBundle.message("feedback.form.evaluation.details.emptyText") else ApplicationBundle.message("feedback.form.details.emptyText") putClientProperty(TextComponentEmptyText.STATUS_VISIBLE_FUNCTION, Predicate<JBTextArea> { it.text.isEmpty() }) addKeyListener(object : KeyAdapter() { override fun keyPressed(e: KeyEvent) { if (e.keyCode == KeyEvent.VK_TAB) { if ((e.modifiersEx and KeyEvent.SHIFT_DOWN_MASK) != 0) { transferFocusBackward() } else { transferFocus() } e.consume() } } }) } }.resizableRow() row { textField() .label(ApplicationBundle.message("feedback.form.email"), LabelPosition.TOP) .bindText(::email) .columns(COLUMNS_MEDIUM) .errorOnApply(ApplicationBundle.message("feedback.form.email.required")) { it.text.isBlank() } .errorOnApply(ApplicationBundle.message("feedback.form.email.invalid")) { !it.text.matches(Regex(".+@.+\\..+")) } } row { checkBox(ApplicationBundle.message("feedback.form.need.support")) .bindSelected(::needSupport) } row { checkBox(ApplicationBundle.message("feedback.form.share.system.information")) .bindSelected(::shareSystemInformation) .gap(RightGap.SMALL) @Suppress("DialogTitleCapitalization") link(ApplicationBundle.message("feedback.form.share.system.information.link")) { showSystemInformation() } } row { comment(ApplicationBundle.message("feedback.form.consent")) } } } private fun showSystemInformation() { val systemInfo = AboutDialog(project).extendedAboutText val scrollPane = JBScrollPane(JBTextArea(systemInfo)) dialog(ApplicationBundle.message("feedback.form.system.information.title"), scrollPane, createActions = { listOf(object : AbstractAction(CommonBundle.getCloseButtonText()) { init { putValue(DEFAULT_ACTION, true) } override fun actionPerformed(event: ActionEvent) { val wrapper = findInstance(event.source as? Component) wrapper?.close(OK_EXIT_CODE) } }) }).show() } override fun getOKAction(): Action { return object : DialogWrapper.OkAction() { init { putValue(Action.NAME, ApplicationBundle.message("feedback.form.ok")) } override fun doAction(e: ActionEvent) { val ratingComponent = ratingComponent missingRatingTooltip?.isVisible = ratingComponent?.myRating == 0 if (ratingComponent == null || ratingComponent.myRating != 0) { super.doAction(e) } else { enabled = false } } } } override fun getCancelAction(): Action { return super.getCancelAction().apply { if (isEvaluation) { putValue(Action.NAME, ApplicationBundle.message("feedback.form.cancel")) } } } override fun doOKAction() { super.doOKAction() val systemInfo = if (shareSystemInformation) AboutDialog(project).extendedAboutText else "" ApplicationManager.getApplication().executeOnPooledThread { ZenDeskRequests().submit( form, email, ApplicationNamesInfo.getInstance().fullProductName + " Feedback", details.ifEmpty { "No details" }, mapOf( "systeminfo" to systemInfo, "needsupport" to needSupport ) + (ratingComponent?.let { mapOf("rating" to it.myRating) } ?: mapOf()) + (topic?.let { mapOf("topic" to it.id) } ?: emptyMap()) , onDone = { ApplicationManager.getApplication().invokeLater { var message = ApplicationBundle.message("feedback.form.thanks", ApplicationNamesInfo.getInstance().fullProductName) if (isEvaluation) { message += "<br/>" + ApplicationBundle.message("feedback.form.share.later") } Notification("feedback.form", ApplicationBundle.message("feedback.form.thanks.title"), message, NotificationType.INFORMATION).notify(project) } }, onError = { ApplicationManager.getApplication().invokeLater { Notification("feedback.form", ApplicationBundle.message("feedback.form.error.title"), ApplicationBundle.message("feedback.form.error.text"), NotificationType.ERROR ) .setListener(object : NotificationListener.Adapter() { override fun hyperlinkActivated(notification: Notification, e: HyperlinkEvent) { SendFeedbackAction.submit(project) } }) .notify(project) } }) } } override fun doCancelAction() { super.doCancelAction() if (isEvaluation) { Notification("feedback.form", ApplicationBundle.message("feedback.form.share.later"), NotificationType.INFORMATION).notify(project) } } }
apache-2.0
18216a020538b7b9a79a30141968d7b8
38.892086
155
0.665284
4.939866
false
false
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/ide/actions/EditCustomSettingsAction.kt
3
6859
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.actions import com.intellij.CommonBundle import com.intellij.diagnostic.VMOptions import com.intellij.ide.IdeBundle import com.intellij.ide.util.PsiNavigationSupport import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.fileEditor.impl.NonProjectFileWritingAccessExtension import com.intellij.openapi.fileTypes.FileTypeManager import com.intellij.openapi.project.DefaultProjectFactory import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame import com.intellij.psi.PsiManager import com.intellij.ui.EditorTextField import com.intellij.util.ui.IoErrorText import java.io.File import java.io.IOException import java.nio.charset.Charset import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Path import javax.swing.JFrame import javax.swing.ScrollPaneConstants abstract class EditCustomSettingsAction : DumbAwareAction() { protected abstract fun file(): Path? protected abstract fun template(): String protected open fun charset(): Charset = StandardCharsets.UTF_8 override fun getActionUpdateThread() = ActionUpdateThread.EDT override fun update(e: AnActionEvent) { e.presentation.isEnabled = (e.project != null || WelcomeFrame.getInstance() != null) && file() != null } override fun actionPerformed(e: AnActionEvent) { val file = file() ?: return val project = e.project if (project != null) { openInEditor(file, project) } else { val frame = WelcomeFrame.getInstance() as JFrame? if (frame != null) { openInDialog(file, frame) } } } private fun openInEditor(file: Path, project: Project) { if (!Files.exists(file)) { try { Files.write(file, template().lines(), charset()) } catch (e: IOException) { Logger.getInstance(javaClass).warn(file.toString(), e) val message = IdeBundle.message("file.write.error.details", file, IoErrorText.message(e)) Messages.showErrorDialog(project, message, CommonBundle.getErrorTitle()) return } } val vFile = LocalFileSystem.getInstance().refreshAndFindFileByNioFile(file) if (vFile != null) { vFile.refresh(false, false) val psiFile = PsiManager.getInstance(project).findFile(vFile) if (psiFile != null) { PsiNavigationSupport.getInstance().createNavigatable(project, vFile, psiFile.textLength).navigate(true) } } } private fun openInDialog(file: Path, frame: JFrame) { val lines = if (!Files.exists(file)) template().lines() else { try { Files.readAllLines(file, charset()) } catch (e: IOException) { Logger.getInstance(javaClass).warn(file.toString(), e) val message = IdeBundle.message("file.read.error.details", file, IoErrorText.message(e)) Messages.showErrorDialog(frame, message, CommonBundle.getErrorTitle()) return } } val text = lines.joinToString("\n") object : DialogWrapper(frame, true) { private val editor: EditorTextField init { title = FileUtil.getLocationRelativeToUserHome(file.toString()) setOKButtonText(IdeBundle.message("button.save")) val document = EditorFactory.getInstance().createDocument(text) val defaultProject = DefaultProjectFactory.getInstance().defaultProject val fileType = FileTypeManager.getInstance().getFileTypeByFileName(file.fileName.toString()) editor = object : EditorTextField(document, defaultProject, fileType, false, false) { override fun createEditor(): EditorEx { val editor = super.createEditor() editor.scrollPane.verticalScrollBarPolicy = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED editor.scrollPane.horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED return editor } } init() } override fun createCenterPanel() = editor override fun getPreferredFocusedComponent() = editor override fun getDimensionServiceKey() = "ide.config.custom.settings" override fun doOKAction() { try { Files.write(file, editor.text.split('\n'), charset()) close(OK_EXIT_CODE) } catch (e: IOException) { Logger.getInstance(javaClass).warn(file.toString(), e) val message = IdeBundle.message("file.write.error.details", file, IoErrorText.message(e)) Messages.showErrorDialog(this.window, message, CommonBundle.getErrorTitle()) } } }.show() } } class EditCustomPropertiesAction : EditCustomSettingsAction() { private companion object { val file: Lazy<Path?> = lazy { PathManager.getCustomOptionsDirectory()?.let { Path.of(it, PathManager.PROPERTIES_FILE_NAME) } } } override fun file(): Path? = file.value override fun template(): String = "# custom ${ApplicationNamesInfo.getInstance().fullProductName} properties (expand/override 'bin${File.separator}idea.properties')\n\n" class AccessExtension : NonProjectFileWritingAccessExtension { override fun isWritable(file: VirtualFile): Boolean = EditCustomPropertiesAction.file.value?.let { VfsUtilCore.pathEqualsTo(file, it.toString()) } ?: false } } class EditCustomVmOptionsAction : EditCustomSettingsAction() { private companion object { val file: Lazy<Path?> = lazy { VMOptions.getUserOptionsFile() } } override fun file(): Path? = file.value override fun template(): String = "# custom ${ApplicationNamesInfo.getInstance().fullProductName} VM options (expand/override 'bin${File.separator}${VMOptions.getFileName()}')\n\n" override fun charset(): Charset = VMOptions.getFileCharset() fun isEnabled(): Boolean = file() != null class AccessExtension : NonProjectFileWritingAccessExtension { override fun isWritable(file: VirtualFile): Boolean = EditCustomVmOptionsAction.file.value?.let { VfsUtilCore.pathEqualsTo(file, it.toString()) } ?: false } }
apache-2.0
4570fa4d2c1b025644b1670c1861047c
38.194286
158
0.724158
4.58796
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/tests/testData/inspections/dfa/AnyType.kt
1
281
// WITH_STDLIB fun main() { val a: Any = 0 println(<warning descr="Condition 'a is Int' is always true">a is Int</warning>) } fun main2(b: Boolean) { var a: Any = 0 if (b) a = 1 println(<warning descr="Condition 'a is Int' is always true">a is Int</warning>) }
apache-2.0
cc519a20a7275e0dff2b07ed5eb986b5
24.636364
84
0.6121
3.122222
false
false
false
false
google/iosched
shared/src/main/java/com/google/samples/apps/iosched/shared/data/userevent/FirestoreUserEventParser.kt
4
4626
/* * 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.userevent import com.google.firebase.firestore.DocumentSnapshot import com.google.samples.apps.iosched.model.reservations.ReservationRequest import com.google.samples.apps.iosched.model.reservations.ReservationRequestResult import com.google.samples.apps.iosched.model.userdata.UserEvent import com.google.samples.apps.iosched.shared.data.userevent.FirestoreUserEventDataSource.Companion.RESERVATION_REQUEST_ACTION_KEY import com.google.samples.apps.iosched.shared.data.userevent.FirestoreUserEventDataSource.Companion.RESERVATION_REQUEST_KEY import com.google.samples.apps.iosched.shared.data.userevent.FirestoreUserEventDataSource.Companion.RESERVATION_REQUEST_REQUEST_ID_KEY import com.google.samples.apps.iosched.shared.data.userevent.FirestoreUserEventDataSource.Companion.RESERVATION_RESULT_KEY import com.google.samples.apps.iosched.shared.data.userevent.FirestoreUserEventDataSource.Companion.RESERVATION_RESULT_REQ_ID_KEY import com.google.samples.apps.iosched.shared.data.userevent.FirestoreUserEventDataSource.Companion.RESERVATION_RESULT_RESULT_KEY import com.google.samples.apps.iosched.shared.data.userevent.FirestoreUserEventDataSource.Companion.RESERVATION_RESULT_TIME_KEY import com.google.samples.apps.iosched.shared.data.userevent.FirestoreUserEventDataSource.Companion.RESERVATION_STATUS_KEY import timber.log.Timber /** * Parse a user event that includes information about the reservation status. */ fun parseUserEvent(snapshot: DocumentSnapshot): UserEvent { val reservationRequestResult: ReservationRequestResult? = generateReservationRequestResult(snapshot) val reservationRequest = parseReservationRequest(snapshot) val reservationStatus = (snapshot[RESERVATION_STATUS_KEY] as? String)?.let { UserEvent.ReservationStatus.getIfPresent(it) } return UserEvent( id = snapshot.id, reservationRequestResult = reservationRequestResult, reservationStatus = reservationStatus, isStarred = snapshot[FirestoreUserEventDataSource.IS_STARRED] as? Boolean ?: false, reservationRequest = reservationRequest, isReviewed = snapshot[FirestoreUserEventDataSource.REVIEWED] as? Boolean ?: false ) } /** * Parse the result of a reservation request. */ private fun generateReservationRequestResult( snapshot: DocumentSnapshot ): ReservationRequestResult? { (snapshot[RESERVATION_RESULT_KEY] as? Map<*, *>)?.let { reservation -> val requestResult = (reservation[RESERVATION_RESULT_RESULT_KEY] as? String) ?.let { ReservationRequestResult.ReservationRequestStatus.getIfPresent(it) } val requestId = (reservation[RESERVATION_RESULT_REQ_ID_KEY] as? String) val timestamp = reservation[RESERVATION_RESULT_TIME_KEY] as? Long ?: -1 // Mandatory fields or fail: if (requestResult == null || requestId == null) { Timber.e("Error parsing reservation request result: some fields null") return null } return ReservationRequestResult( requestResult = requestResult, requestId = requestId, timestamp = timestamp ) } // If there's no reservation: return null } /** * Parse the reservation request. */ private fun parseReservationRequest(snapshot: DocumentSnapshot): ReservationRequest? { (snapshot[RESERVATION_REQUEST_KEY] as? Map<*, *>)?.let { request -> val action = (request[RESERVATION_REQUEST_ACTION_KEY] as? String)?.let { ReservationRequest.ReservationRequestEntityAction.getIfPresent(it) } val requestId = (request[RESERVATION_REQUEST_REQUEST_ID_KEY] as? String) // Mandatory fields or fail: if (action == null || requestId == null) { Timber.e("Error parsing reservation request from Firestore") return null } return ReservationRequest(action, requestId) } // If there's no reservation request: return null }
apache-2.0
a7ea77858aeb3b83cb18b1ad60da7e79
41.833333
134
0.746001
4.808732
false
false
false
false
JetBrains/intellij-community
plugins/git4idea/src/git4idea/ui/branch/GitBranchesTreePopup.kt
1
25467
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package git4idea.ui.branch import com.intellij.dvcs.branch.DvcsBranchManager import com.intellij.dvcs.branch.GroupingKey import com.intellij.dvcs.ui.DvcsBundle import com.intellij.icons.AllIcons import com.intellij.ide.DataManager import com.intellij.ide.util.treeView.TreeState import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.actionSystem.impl.SimpleDataContext import com.intellij.openapi.application.runInEdt import com.intellij.openapi.components.service import com.intellij.openapi.ide.CopyPasteManager import com.intellij.openapi.keymap.KeymapUtil import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.* import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Key import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.WindowStateService import com.intellij.openapi.util.registry.Registry import com.intellij.ui.* import com.intellij.ui.popup.NextStepHandler import com.intellij.ui.popup.PopupFactoryImpl import com.intellij.ui.popup.WizardPopup import com.intellij.ui.popup.util.PopupImplUtil import com.intellij.ui.render.RenderingUtil import com.intellij.ui.scale.JBUIScale import com.intellij.ui.speedSearch.SpeedSearchUtil import com.intellij.ui.tree.ui.Control import com.intellij.ui.tree.ui.DefaultControl import com.intellij.ui.tree.ui.DefaultTreeUI import com.intellij.ui.treeStructure.Tree import com.intellij.util.text.nullize import com.intellij.util.ui.JBDimension import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.intellij.util.ui.tree.TreeUtil import git4idea.GitBranch import git4idea.actions.branch.GitBranchActionsUtil import git4idea.branch.GitBranchType import git4idea.i18n.GitBundle import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryChangeListener import git4idea.repo.GitRepositoryManager import git4idea.ui.branch.GitBranchesTreePopupStep.Companion.SPEED_SEARCH_DEFAULT_ACTIONS_GROUP import git4idea.ui.branch.GitBranchesTreeUtil.overrideBuiltInAction import git4idea.ui.branch.GitBranchesTreeUtil.selectFirstLeaf import git4idea.ui.branch.GitBranchesTreeUtil.selectLastLeaf import git4idea.ui.branch.GitBranchesTreeUtil.selectNextLeaf import git4idea.ui.branch.GitBranchesTreeUtil.selectPrevLeaf import kotlinx.coroutines.* import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.drop import java.awt.AWTEvent import java.awt.Component import java.awt.Cursor import java.awt.Point import java.awt.datatransfer.DataFlavor import java.awt.event.* import java.util.function.Function import java.util.function.Supplier import javax.swing.* import javax.swing.tree.TreeCellRenderer import javax.swing.tree.TreeModel import javax.swing.tree.TreePath import javax.swing.tree.TreeSelectionModel import kotlin.math.min class GitBranchesTreePopup(project: Project, step: GitBranchesTreePopupStep, parent: JBPopup? = null, parentValue: Any? = null) : WizardPopup(project, parent, step), TreePopup, NextStepHandler { private lateinit var tree: BranchesTree private var showingChildPath: TreePath? = null private var pendingChildPath: TreePath? = null private val treeStep: GitBranchesTreePopupStep get() = step as GitBranchesTreePopupStep private lateinit var searchPatternStateFlow: MutableStateFlow<String?> internal var userResized: Boolean private set init { setParentValue(parentValue) setMinimumSize(JBDimension(300, 200)) dimensionServiceKey = if (isChild()) null else GitBranchPopup.DIMENSION_SERVICE_KEY userResized = !isChild() && WindowStateService.getInstance(project).getSizeFor(project, dimensionServiceKey) != null installGeneralShortcutActions() installShortcutActions(step.treeModel) if (!isChild()) { setSpeedSearchAlwaysShown() installHeaderToolbar() installRepoListener() installResizeListener() warnThatBranchesDivergedIfNeeded() } installBranchSettingsListener() DataManager.registerDataProvider(component, DataProvider { dataId -> when { POPUP_KEY.`is`(dataId) -> this GitBranchActionsUtil.REPOSITORIES_KEY.`is`(dataId) -> treeStep.repositories else -> null } }) } private fun warnThatBranchesDivergedIfNeeded() { if (treeStep.isBranchesDiverged()) { setWarning(DvcsBundle.message("branch.popup.warning.branches.have.diverged")) } } override fun createContent(): JComponent { tree = BranchesTree(treeStep.treeModel).also { configureTreePresentation(it) overrideTreeActions(it) addTreeMouseControlsListeners(it) Disposer.register(this) { it.model = null } val topBorder = if (step.title.isNullOrEmpty()) JBUIScale.scale(5) else 0 it.border = JBUI.Borders.empty(topBorder, JBUIScale.scale(10), 0, 0) } searchPatternStateFlow = MutableStateFlow(null) speedSearch.installSupplyTo(tree, false) @OptIn(FlowPreview::class) with(uiScope(this)) { launch { searchPatternStateFlow.drop(1).debounce(100).collectLatest { pattern -> applySearchPattern(pattern) } } } return tree } private fun isChild() = parent != null private fun applySearchPattern(pattern: String? = speedSearch.enteredPrefix.nullize(true)) { treeStep.setSearchPattern(pattern) val haveBranches = haveBranchesToShow() if (haveBranches) { selectPreferred() } super.updateSpeedSearchColors(!haveBranches) if (!pattern.isNullOrBlank()) { tree.emptyText.text = GitBundle.message("git.branches.popup.tree.no.branches", pattern) } } private fun haveBranchesToShow(): Boolean { val model = tree.model val root = model.root return (0 until model.getChildCount(root)) .asSequence() .map { model.getChild(root, it) } .filterIsInstance<GitBranchType>() .any { !model.isLeaf(it) } } internal fun restoreDefaultSize() { userResized = false WindowStateService.getInstance(project).putSizeFor(project, dimensionServiceKey, null) pack(true, true) } private fun installRepoListener() { project.messageBus.connect(this).subscribe(GitRepository.GIT_REPO_CHANGE, GitRepositoryChangeListener { runInEdt { val state = TreeState.createOn(tree) applySearchPattern() state.applyTo(tree) } }) } private fun installResizeListener() { addResizeListener({ userResized = true }, this) } private fun installBranchSettingsListener() { project.messageBus.connect(this) .subscribe(DvcsBranchManager.DVCS_BRANCH_SETTINGS_CHANGED, object : DvcsBranchManager.DvcsBranchManagerListener { override fun branchGroupingSettingsChanged(key: GroupingKey, state: Boolean) { runInEdt { treeStep.setPrefixGrouping(state) } } override fun branchFavoriteSettingsChanged() { runInEdt { tree.repaint() } } }) } override fun storeDimensionSize() { if (userResized) { super.storeDimensionSize() } } private fun toggleFavorite(branch: GitBranch) { val branchType = GitBranchType.of(branch) val branchManager = project.service<GitBranchManager>() val anyNotFavorite = treeStep.repositories.any { repository -> !branchManager.isFavorite(branchType, repository, branch.name) } treeStep.repositories.forEach { repository -> branchManager.setFavorite(branchType, repository, branch.name, anyNotFavorite) } } private fun installGeneralShortcutActions() { registerAction("toggle_favorite", KeyStroke.getKeyStroke("SPACE"), object : AbstractAction() { override fun actionPerformed(e: ActionEvent?) { (tree.lastSelectedPathComponent?.let(TreeUtil::getUserObject) as? GitBranch)?.run(::toggleFavorite) } }) } private fun installSpeedSearchActions() { val updateSpeedSearch = { val textInEditor = mySpeedSearchPatternField.textEditor.text speedSearch.updatePattern(textInEditor) applySearchPattern(textInEditor) } val editorActionsContext = mapOf(PlatformCoreDataKeys.CONTEXT_COMPONENT to mySpeedSearchPatternField.textEditor) (ActionManager.getInstance() .getAction(SPEED_SEARCH_DEFAULT_ACTIONS_GROUP) as ActionGroup) .getChildren(null) .forEach { action -> registerAction(ActionManager.getInstance().getId(action), KeymapUtil.getKeyStroke(action.shortcutSet), createShortcutAction(action, editorActionsContext, updateSpeedSearch, false)) } } private fun installShortcutActions(model: TreeModel) { val root = model.root (0 until model.getChildCount(root)) .asSequence() .map { model.getChild(root, it) } .filterIsInstance<PopupFactoryImpl.ActionItem>() .map(PopupFactoryImpl.ActionItem::getAction) .forEach { action -> registerAction(ActionManager.getInstance().getId(action), KeymapUtil.getKeyStroke(action.shortcutSet), createShortcutAction<Any>(action)) } } private fun installHeaderToolbar() { val settingsGroup = ActionManager.getInstance().getAction(GitBranchesTreePopupStep.HEADER_SETTINGS_ACTION_GROUP) val toolbarGroup = DefaultActionGroup(GitBranchPopupFetchAction(javaClass), settingsGroup) val toolbar = ActionManager.getInstance() .createActionToolbar(GitBranchesTreePopupStep.ACTION_PLACE, toolbarGroup, true) .apply { targetComponent = [email protected] setReservePlaceAutoPopupIcon(false) component.isOpaque = false } title.setButtonComponent(object : ActiveComponent.Adapter() { override fun getComponent(): JComponent = toolbar.component }, JBUI.Borders.emptyRight(2)) } private fun <T> createShortcutAction(action: AnAction, actionContext: Map<DataKey<T>, T> = emptyMap(), afterActionPerformed: (() -> Unit)? = null, closePopup: Boolean = true) = object : AbstractAction() { override fun actionPerformed(e: ActionEvent?) { if (closePopup) { cancel() } val stepContext = GitBranchesTreePopupStep.createDataContext(project, treeStep.repositories) val resultContext = with(SimpleDataContext.builder().setParent(stepContext)) { actionContext.forEach { (key, value) -> add(key, value) } build() } ActionUtil.invokeAction(action, resultContext, GitBranchesTreePopupStep.ACTION_PLACE, null, afterActionPerformed) } } private fun configureTreePresentation(tree: JTree) = with(tree) { ClientProperty.put(this, RenderingUtil.CUSTOM_SELECTION_BACKGROUND, Supplier { JBUI.CurrentTheme.Tree.background(true, true) }) ClientProperty.put(this, RenderingUtil.CUSTOM_SELECTION_FOREGROUND, Supplier { JBUI.CurrentTheme.Tree.foreground(true, true) }) val renderer = Renderer(treeStep) ClientProperty.put(this, Control.CUSTOM_CONTROL, Function { renderer.getLeftTreeIconRenderer(it) }) selectionModel.selectionMode = TreeSelectionModel.SINGLE_TREE_SELECTION isRootVisible = false showsRootHandles = true visibleRowCount = min(calculateTopLevelVisibleRows(), 20) cellRenderer = renderer accessibleContext.accessibleName = GitBundle.message("git.branches.popup.tree.accessible.name") ClientProperty.put(this, DefaultTreeUI.LARGE_MODEL_ALLOWED, true) rowHeight = treeRowHeight isLargeModel = true expandsSelectedPaths = true } /** * Local branches would be expanded by [GitBranchesTreePopupStep.getPreferredSelection]. */ private fun JTree.calculateTopLevelVisibleRows() = model.getChildCount(model.root) + model.getChildCount(GitBranchType.LOCAL) private fun overrideTreeActions(tree: JTree) = with(tree) { overrideBuiltInAction("toggle") { val path = selectionPath if (path != null && model.getChildCount(path.lastPathComponent) == 0) { handleSelect(true, null) true } else false } overrideBuiltInAction(TreeActions.Left.ID) { if (isChild()) { cancel() true } else false } overrideBuiltInAction(TreeActions.Right.ID) { val path = selectionPath if (path != null && (path.lastPathComponent is GitRepository || model.getChildCount(path.lastPathComponent) == 0)) { handleSelect(false, null) true } else false } overrideBuiltInAction(TreeActions.Down.ID) { if (speedSearch.isHoldingFilter) selectNextLeaf() else false } overrideBuiltInAction(TreeActions.Up.ID) { if (speedSearch.isHoldingFilter) selectPrevLeaf() else false } overrideBuiltInAction(TreeActions.Home.ID) { if (speedSearch.isHoldingFilter) selectFirstLeaf() else false } overrideBuiltInAction(TreeActions.End.ID) { if (speedSearch.isHoldingFilter) selectLastLeaf() else false } overrideBuiltInAction(TransferHandler.getPasteAction().getValue(Action.NAME) as String) { speedSearch.type(CopyPasteManager.getInstance().getContents(DataFlavor.stringFlavor)) speedSearch.update() true } } private fun addTreeMouseControlsListeners(tree: JTree) = with(tree) { addMouseMotionListener(SelectionMouseMotionListener()) addMouseListener(SelectOnClickListener()) } override fun getActionMap(): ActionMap = tree.actionMap override fun getInputMap(): InputMap = tree.inputMap private val selectAllKeyStroke = KeymapUtil.getKeyStroke(ActionManager.getInstance().getAction(IdeActions.ACTION_SELECT_ALL).shortcutSet) override fun process(e: KeyEvent?) { if (e == null) return val eventStroke = KeyStroke.getKeyStroke(e.keyCode, e.modifiersEx, e.id == KeyEvent.KEY_RELEASED) if (selectAllKeyStroke == eventStroke) { return } tree.processEvent(e) } override fun afterShow() { selectPreferred() if (treeStep.isSpeedSearchEnabled) { installSpeedSearchActions() } } override fun updateSpeedSearchColors(error: Boolean) {} // update colors only after branches tree model update private fun selectPreferred() { val preferredSelection = treeStep.getPreferredSelection() if (preferredSelection != null) { tree.makeVisible(preferredSelection) tree.selectionPath = preferredSelection TreeUtil.scrollToVisible(tree, preferredSelection, true) } else TreeUtil.promiseSelectFirstLeaf(tree) } override fun isResizable(): Boolean = true private inner class SelectionMouseMotionListener : MouseMotionAdapter() { private var lastMouseLocation: Point? = null /** * this method should be changed only in par with * [com.intellij.ui.popup.list.ListPopupImpl.MyMouseMotionListener.isMouseMoved] */ private fun isMouseMoved(location: Point): Boolean { if (lastMouseLocation == null) { lastMouseLocation = location return false } val prev = lastMouseLocation lastMouseLocation = location return prev != location } override fun mouseMoved(e: MouseEvent) { if (!isMouseMoved(e.locationOnScreen)) return val path = getPath(e) if (path != null) { tree.selectionPath = path notifyParentOnChildSelection() if (treeStep.isSelectable(TreeUtil.getUserObject(path.lastPathComponent))) { tree.cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) if (pendingChildPath == null || pendingChildPath != path) { pendingChildPath = path restartTimer() } return } } tree.cursor = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR) } } private inner class SelectOnClickListener : MouseAdapter() { override fun mousePressed(e: MouseEvent) { if (e.button != MouseEvent.BUTTON1) return val path = getPath(e) ?: return val selected = path.lastPathComponent if (treeStep.isSelectable(TreeUtil.getUserObject(selected))) { handleSelect(true, e) } } } private fun getPath(e: MouseEvent): TreePath? = tree.getClosestPathForLocation(e.point.x, e.point.y) private fun handleSelect(handleFinalChoices: Boolean, e: MouseEvent?) { val selectionPath = tree.selectionPath val pathIsAlreadySelected = showingChildPath != null && showingChildPath == selectionPath if (pathIsAlreadySelected) return pendingChildPath = null val selected = tree.lastSelectedPathComponent if (selected != null) { val userObject = TreeUtil.getUserObject(selected) val point = e?.point if (point != null && userObject is GitBranch && isMainIconAt(point, userObject)) { toggleFavorite(userObject) return } if (treeStep.isSelectable(userObject)) { disposeChildren() val hasNextStep = myStep.hasSubstep(userObject) if (!hasNextStep && !handleFinalChoices) { showingChildPath = null return } val queriedStep = PopupImplUtil.prohibitFocusEventsInHandleSelect().use { myStep.onChosen(userObject, handleFinalChoices) } if (queriedStep == PopupStep.FINAL_CHOICE || !hasNextStep) { setFinalRunnable(myStep.finalRunnable) setOk(true) disposeAllParents(e) } else { showingChildPath = selectionPath handleNextStep(queriedStep, selected) showingChildPath = null } } } } private fun isMainIconAt(point: Point, selected: Any): Boolean { val row = tree.getRowForLocation(point.x, point.y) val rowBounds = tree.getRowBounds(row) ?: return false point.translate(-rowBounds.x, -rowBounds.y) val rowComponent = tree.cellRenderer .getTreeCellRendererComponent(tree, selected, true, false, true, row, false) as? JComponent ?: return false val iconComponent = UIUtil.uiTraverser(rowComponent) .filter { ClientProperty.get(it, Renderer.MAIN_ICON) == true } .firstOrNull() ?: return false // todo: implement more precise check return iconComponent.bounds.width >= point.x } override fun handleNextStep(nextStep: PopupStep<*>?, parentValue: Any) { val selectionPath = tree.selectionPath ?: return val pathBounds = tree.getPathBounds(selectionPath) ?: return val point = Point(pathBounds.x, pathBounds.y) SwingUtilities.convertPointToScreen(point, tree) myChild = if (nextStep is GitBranchesTreePopupStep) GitBranchesTreePopup(project, nextStep, this, parentValue) else createPopup(this, nextStep, parentValue) myChild.show(content, content.locationOnScreen.x + content.width - STEP_X_PADDING, point.y, true) } override fun onSpeedSearchPatternChanged() { with(uiScope(this)) { launch { searchPatternStateFlow.emit(speedSearch.enteredPrefix.nullize(true)) } } } override fun getPreferredFocusableComponent(): JComponent = tree override fun onChildSelectedFor(value: Any) { val path = treeStep.createTreePathFor(value) ?: return if (tree.selectionPath != path) { tree.selectionPath = path } } companion object { internal val POPUP_KEY = DataKey.create<GitBranchesTreePopup>("GIT_BRANCHES_TREE_POPUP") private val treeRowHeight = if (ExperimentalUI.isNewUI()) JBUI.CurrentTheme.List.rowHeight() else JBUIScale.scale(22) @JvmStatic fun isEnabled() = Registry.`is`("git.branches.popup.tree", false) && !ExperimentalUI.isNewUI() @JvmStatic fun show(project: Project) { create(project).showCenteredInCurrentWindow(project) } @JvmStatic fun create(project: Project): JBPopup { val repositories = GitRepositoryManager.getInstance(project).repositories return GitBranchesTreePopup(project, GitBranchesTreePopupStep(project, repositories, true)) } @JvmStatic internal fun createTreeSeparator(text: @NlsContexts.Separator String? = null) = SeparatorWithText().apply { caption = text border = JBUI.Borders.emptyTop( if (text == null) treeRowHeight / 2 else JBUIScale.scale(SeparatorWithText.DEFAULT_H_GAP)) } private fun uiScope(parent: Disposable) = CoroutineScope(SupervisorJob() + Dispatchers.Main).also { Disposer.register(parent) { it.cancel() } } private class BranchesTree(model: TreeModel): Tree(model) { init { background = JBUI.CurrentTheme.Popup.BACKGROUND } //Change visibility of processEvent to be able to delegate key events dispatched in WizardPopup directly to tree //This will allow to handle events like "copy-paste" in AbstractPopup.speedSearch public override fun processEvent(e: AWTEvent?) { e?.source = this super.processEvent(e) } } private class Renderer(private val step: GitBranchesTreePopupStep) : TreeCellRenderer { fun getLeftTreeIconRenderer(path: TreePath): Control? { val lastComponent = path.lastPathComponent val defaultIcon = step.getNodeIcon(lastComponent, false) ?: return null val selectedIcon = step.getNodeIcon(lastComponent, true) ?: return null return DefaultControl(defaultIcon, defaultIcon, selectedIcon, selectedIcon) } private val mainIconComponent = JLabel().apply { ClientProperty.put(this, MAIN_ICON, true) border = JBUI.Borders.emptyRight(4) // 6 px in spec, but label width is differed } private val mainTextComponent = SimpleColoredComponent().apply { isOpaque = false border = JBUI.Borders.empty() } private val secondaryLabel = JLabel().apply { border = JBUI.Borders.emptyLeft(10) horizontalAlignment = SwingConstants.RIGHT } private val arrowLabel = JLabel().apply { border = JBUI.Borders.emptyLeft(4) // 6 px in spec, but label width is differed } private val incomingOutgoingLabel = JLabel().apply { border = JBUI.Borders.emptyLeft(10) } private val textPanel = JBUI.Panels.simplePanel() .addToLeft(JBUI.Panels.simplePanel(mainTextComponent) .addToLeft(mainIconComponent) .addToRight(incomingOutgoingLabel) .andTransparent()) .addToCenter(secondaryLabel) .andTransparent() private val mainPanel = JBUI.Panels.simplePanel() .addToCenter(textPanel) .addToRight(arrowLabel) .andTransparent() .withBorder(JBUI.Borders.emptyRight(JBUI.CurrentTheme.ActionsList.cellPadding().right)) override fun getTreeCellRendererComponent(tree: JTree?, value: Any?, selected: Boolean, expanded: Boolean, leaf: Boolean, row: Int, hasFocus: Boolean): Component { val userObject = TreeUtil.getUserObject(value) mainIconComponent.apply { icon = step.getIcon(userObject, selected) isVisible = icon != null } mainTextComponent.apply { background = JBUI.CurrentTheme.Tree.background(selected, true) foreground = JBUI.CurrentTheme.Tree.foreground(selected, true) clear() append(step.getText(userObject).orEmpty()) } val (inOutIcon, inOutTooltip) = step.getIncomingOutgoingIconWithTooltip(userObject) tree?.toolTipText = inOutTooltip incomingOutgoingLabel.apply { icon = inOutIcon isVisible = icon != null } arrowLabel.apply { isVisible = step.hasSubstep(userObject) icon = if (selected) AllIcons.Icons.Ide.MenuArrowSelected else AllIcons.Icons.Ide.MenuArrow } secondaryLabel.apply { text = step.getSecondaryText(userObject) //todo: LAF color foreground = if (selected) JBUI.CurrentTheme.Tree.foreground(true, true) else JBColor.GRAY border = if (!arrowLabel.isVisible && ExperimentalUI.isNewUI()) { JBUI.Borders.empty(0, 10, 0, JBUI.CurrentTheme.Popup.Selection.innerInsets().right) } else { JBUI.Borders.emptyLeft(10) } } if (tree != null && value != null) { SpeedSearchUtil.applySpeedSearchHighlightingFiltered(tree, value, mainTextComponent, true, selected) } return mainPanel } companion object { @JvmField internal val MAIN_ICON = Key.create<Boolean>("MAIN_ICON") } } } }
apache-2.0
617f1145b76fd38c102b916c1c856d81
34.718093
139
0.689166
4.798756
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/presentation/comment/CommentsPresenter.kt
1
12404
package org.stepik.android.presentation.comment import io.reactivex.Scheduler import io.reactivex.Single import io.reactivex.rxkotlin.Singles import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.subscribeBy import io.reactivex.subjects.PublishSubject import org.stepic.droid.di.qualifiers.BackgroundScheduler import org.stepic.droid.di.qualifiers.MainScheduler import ru.nobird.android.domain.rx.emptyOnErrorStub import org.stepik.android.domain.comment.interactor.CommentInteractor import org.stepik.android.domain.comment.interactor.ComposeCommentInteractor import org.stepik.android.domain.comment.model.CommentsData import org.stepik.android.domain.discussion_proxy.interactor.DiscussionProxyInteractor import org.stepik.android.domain.discussion_proxy.model.DiscussionOrder import org.stepik.android.domain.profile.interactor.ProfileGuestInteractor import org.stepik.android.model.Step import org.stepik.android.model.Submission import org.stepik.android.model.comments.Comment import org.stepik.android.model.comments.DiscussionProxy import org.stepik.android.model.comments.Vote import org.stepik.android.presentation.base.PresenterBase import org.stepik.android.presentation.comment.mapper.CommentsStateMapper import org.stepik.android.presentation.comment.model.CommentItem import org.stepik.android.view.injection.step.StepDiscussionBus import ru.nobird.app.core.model.PaginationDirection import javax.inject.Inject class CommentsPresenter @Inject constructor( private val commentInteractor: CommentInteractor, private val composeCommentInteractor: ComposeCommentInteractor, private val discussionProxyInteractor: DiscussionProxyInteractor, private val profileGuestInteractor: ProfileGuestInteractor, private val commentsStateMapper: CommentsStateMapper, @StepDiscussionBus private val stepDiscussionSubject: PublishSubject<Long>, @BackgroundScheduler private val backgroundScheduler: Scheduler, @MainScheduler private val mainScheduler: Scheduler ) : PresenterBase<CommentsView>() { private var state: CommentsView.State = CommentsView.State.Idle set(value) { field = value view?.setState(value) } override fun attachView(view: CommentsView) { super.attachView(view) view.setState(state) } /** * Data initialization variants */ fun onDiscussion(discussionProxyId: String, discussionId: Long?, forceUpdate: Boolean = false) { if (state != CommentsView.State.Idle && !((state == CommentsView.State.NetworkError || state is CommentsView.State.DiscussionLoaded) && forceUpdate) ) { return } val discussionOrderSource = (state as? CommentsView.State.DiscussionLoaded) ?.discussionOrder ?.let { Single.just(it) } ?: discussionProxyInteractor.getDiscussionOrder() compositeDisposable.clear() state = CommentsView.State.Loading compositeDisposable += Singles .zip( profileGuestInteractor.isGuest(), discussionProxyInteractor.getDiscussionProxy(discussionProxyId), discussionOrderSource ) .observeOn(mainScheduler) .subscribeOn(backgroundScheduler) .subscribeBy( onSuccess = { (isGuest, discussionProxy, discussionOrder) -> fetchComments(isGuest, discussionProxy, discussionOrder, discussionId) }, onError = { state = CommentsView.State.NetworkError } ) } private fun fetchComments( isGuest: Boolean, discussionProxy: DiscussionProxy, discussionOrder: DiscussionOrder, discussionId: Long?, keepCachedComments: Boolean = false ) { if (discussionProxy.discussions.isEmpty()) { state = CommentsView.State.DiscussionLoaded(isGuest, discussionProxy, discussionOrder, discussionId, CommentsView.CommentsState.EmptyComments) } else { val cachedComments: List<CommentItem.Data> = ((state as? CommentsView.State.DiscussionLoaded) ?.commentsState as? CommentsView.CommentsState.Loaded) ?.commentDataItems ?.takeIf { keepCachedComments } ?: emptyList() val newState = CommentsView.State.DiscussionLoaded(isGuest, discussionProxy, discussionOrder, discussionId, CommentsView.CommentsState.Loading) state = newState compositeDisposable += commentInteractor .getComments(discussionProxy, discussionOrder, discussionId, cachedComments) .observeOn(mainScheduler) .subscribeOn(backgroundScheduler) .subscribeBy( onSuccess = { state = newState.copy(commentsState = CommentsView.CommentsState.Loaded(it, commentsStateMapper.mapCommentDataItemsToRawItems(it))) if (discussionId != null) { view?.focusDiscussion(discussionId) } }, onError = { state = CommentsView.State.NetworkError } ) } } /** * Discussion ordering */ fun changeDiscussionOrder(discussionOrder: DiscussionOrder) { val oldState = (state as? CommentsView.State.DiscussionLoaded) ?: return compositeDisposable += discussionProxyInteractor .saveDiscussionOrder(discussionOrder) .observeOn(mainScheduler) .subscribeOn(backgroundScheduler) .subscribeBy(onError = emptyOnErrorStub) fetchComments(oldState.isGuest, oldState.discussionProxy, discussionOrder, oldState.discussionId, keepCachedComments = true) } /** * Load more logic in both directions */ fun onLoadMore(direction: PaginationDirection) { val oldState = (state as? CommentsView.State.DiscussionLoaded) ?: return val commentsState = (oldState.commentsState as? CommentsView.CommentsState.Loaded) ?: return val commentDataItems = commentsState.commentDataItems val lastCommentId = when (direction) { PaginationDirection.PREV -> commentDataItems .takeIf { it.hasPrev } .takeIf { commentsState.commentItems.first() !is CommentItem.Placeholder } ?.first() ?.id ?: return PaginationDirection.NEXT -> commentDataItems .takeIf { it.hasNext } .takeIf { commentsState.commentItems.last() !is CommentItem.Placeholder } ?.last { it.comment.parent == null } ?.id ?: return } state = oldState.copy(commentsState = commentsStateMapper.mapToLoadMoreState(commentsState, direction)) compositeDisposable += commentInteractor .getMoreComments(oldState.discussionProxy, oldState.discussionOrder, direction, lastCommentId) .observeOn(mainScheduler) .subscribeOn(backgroundScheduler) .subscribeBy( onSuccess = { state = commentsStateMapper.mapFromLoadMoreToSuccess(state, it, direction) }, onError = { state = commentsStateMapper.mapFromLoadMoreToError(state, direction); view?.showNetworkError() } ) } /** * Load more comments logic */ fun onLoadMoreReplies(loadMoreReplies: CommentItem.LoadMoreReplies) { val oldState = (state as? CommentsView.State.DiscussionLoaded) ?: return val commentsState = (oldState.commentsState as? CommentsView.CommentsState.Loaded) ?: return state = oldState.copy(commentsState = commentsStateMapper.mapToLoadMoreRepliesState(commentsState, loadMoreReplies)) compositeDisposable += commentInteractor .getMoreReplies(loadMoreReplies.parentComment, loadMoreReplies.lastCommentId) .observeOn(mainScheduler) .subscribeOn(backgroundScheduler) .subscribeBy( onSuccess = { state = commentsStateMapper.mapFromLoadMoreRepliesToSuccess(state, it, loadMoreReplies) }, onError = { state = commentsStateMapper.mapFromLoadMoreRepliesToError(state, loadMoreReplies); view?.showNetworkError() } ) } /** * Vote logic * * if [voteValue] is equal to current value new value will be null */ fun onChangeVote(commentDataItem: CommentItem.Data, voteValue: Vote.Value) { if (commentDataItem.voteStatus !is CommentItem.Data.VoteStatus.Resolved || commentDataItem.comment.actions?.vote != true) { return } val oldState = (state as? CommentsView.State.DiscussionLoaded) ?: return val commentsState = (oldState.commentsState as? CommentsView.CommentsState.Loaded) ?: return val newVote = commentDataItem.voteStatus.vote .copy(value = voteValue.takeIf { it != commentDataItem.voteStatus.vote.value }) state = oldState.copy(commentsState = commentsStateMapper.mapToVotePending(commentsState, commentDataItem)) compositeDisposable += commentInteractor .changeCommentVote(commentDataItem.id, newVote) .observeOn(mainScheduler) .subscribeOn(backgroundScheduler) .subscribeBy( onSuccess = { state = commentsStateMapper.mapFromVotePendingToSuccess(state, it) }, onError = { state = commentsStateMapper.mapFromVotePendingToError(state, commentDataItem.voteStatus.vote); view?.showNetworkError() } ) } fun onComposeCommentClicked(step: Step, parent: Long? = null, comment: Comment? = null, submission: Submission? = null) { val oldState = (state as? CommentsView.State.DiscussionLoaded) ?: return if (oldState.isGuest) { view?.showAuthRequired() } else { view?.showCommentComposeDialog(step, parent, comment, submission) } } /** * Edit logic */ fun onCommentCreated(commentsData: CommentsData) { val commentDataItem = commentInteractor .mapCommentsDataToCommentItem(commentsData) ?: return state = if (commentDataItem.comment.parent != null) { commentsStateMapper.insertCommentReply(state, commentDataItem) } else { stepDiscussionSubject.onNext(commentDataItem.comment.target) commentsStateMapper.insertComment(state, commentDataItem) } view?.focusDiscussion(commentDataItem.id) } fun onCommentUpdated(commentsData: CommentsData) { val commentDataItem = commentInteractor .mapCommentsDataToCommentItem(commentsData) ?: return state = commentsStateMapper.mapFromVotePendingToSuccess(state, commentDataItem) } fun removeComment(commentId: Long) { val oldState = (state as? CommentsView.State.DiscussionLoaded) ?: return val commentsState = (oldState.commentsState as? CommentsView.CommentsState.Loaded) ?: return val commentDataItem = commentsState.commentDataItems.find { it.id == commentId } ?: return state = oldState.copy(commentsState = commentsStateMapper.mapToRemovePending(commentsState, commentDataItem)) compositeDisposable += composeCommentInteractor .removeComment(commentDataItem.id) .observeOn(mainScheduler) .subscribeOn(backgroundScheduler) .doOnComplete { if (commentDataItem.comment.parent == null) { stepDiscussionSubject.onNext(commentDataItem.comment.target) } } .subscribeBy( onComplete = { state = commentsStateMapper.mapFromRemovePendingToSuccess(state, commentId) }, onError = { state = commentsStateMapper.mapFromRemovePendingToError(state, commentDataItem); view?.showNetworkError() } ) } }
apache-2.0
c7c0f415cb6379b592f0199bb544b086
40.627517
155
0.657288
5.627949
false
false
false
false
chrislo27/RhythmHeavenRemixEditor2
core/src/main/kotlin/io/github/chrislo27/toolboks/ui/TextField.kt
2
15366
package io.github.chrislo27.toolboks.ui import com.badlogic.gdx.Gdx import com.badlogic.gdx.Input import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.g2d.BitmapFont import com.badlogic.gdx.graphics.g2d.GlyphLayout import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.graphics.glutils.ShapeRenderer import com.badlogic.gdx.utils.Align import io.github.chrislo27.toolboks.ToolboksScreen import io.github.chrislo27.toolboks.util.gdxutils.* /** * A single-line text field. Supports carets but not selection. */ open class TextField<S : ToolboksScreen<*, *>>(override var palette: UIPalette, parent: UIElement<S>, parameterStage: Stage<S>) : UIElement<S>(parent, parameterStage), Palettable, Backgrounded { companion object { const val BACKSPACE: Char = 8.toChar() const val ENTER_DESKTOP = '\r' const val ENTER_ANDROID = '\n' const val TAB = '\t' const val DELETE: Char = 127.toChar() const val BULLET: Char = 149.toChar() const val CARET_BLINK_RATE: Float = 0.5f const val CARET_WIDTH: Float = 2f const val CARET_MOVE_TIMER: Float = 0.05f const val INITIAL_CARET_TIMER: Float = 0.4f const val NEWLINE_WRAP: Char = '\uE056' } override var background: Boolean = false var text: String = "" set(value) { val old = field field = value if (old != value) { renderedText = (if (isPassword) BULLET.toString().repeat(text.length) else text).replace("\r\n", "$NEWLINE_WRAP").replace('\r', NEWLINE_WRAP).replace('\n', NEWLINE_WRAP) val font = getFont() val wasMarkup = font.data.markupEnabled font.data.markupEnabled = false font.scaleMul(palette.fontScale) layout.setText(font, renderedText) font.data.markupEnabled = wasMarkup calculateTextPositions() onTextChange(old) font.scaleMul(1f / palette.fontScale) } caret = caret.coerceIn(0, text.length) } private var renderedText: String = "" private val textPositions: List<Float> = mutableListOf() private val layout = GlyphLayout() private var xOffset: Float = 0f var textWhenEmpty: String = "" var textWhenEmptyColor: Color = palette.textColor var textAlign: Int = Align.left /** * 0 = start, the number is the index and then behind that */ var caret: Int = 0 set(value) { caretTimer = 0f field = value.coerceIn(0, text.length) if (layout.width > location.realWidth) { val caretX: Float = textPositions[caret] if (caretX < xOffset) { xOffset = Math.max(0f, caretX) } else if (caretX > xOffset + location.realWidth) { xOffset = Math.min(layout.width - location.realWidth, caretX - location.realWidth + CARET_WIDTH) } } else { xOffset = 0f } } var hasFocus: Boolean = false set(value) { field = value caretTimer = 0f } var canTypeText: (Char) -> Boolean = { true } var characterLimit: Int = -1 private var caretTimer: Float = 0f private var caretMoveTimer: Float = -1f var isPassword: Boolean = false set(value) { field = value text = text } override var visible: Boolean = super.visible set(value) { field = value if (!value) { hasFocus = false } } var canPaste = true var canInputNewlines = false open fun getFont(): BitmapFont = palette.font protected fun calculateTextPositions() { textPositions as MutableList textPositions.clear() val advances = layout.runs.firstOrNull()?.xAdvances ?: run { textPositions as MutableList textPositions.addAll(arrayOf(0f, 0f)) return } for (i in 0 until advances.size) { textPositions += if (i == 0) { advances[i] } else { advances[i] + textPositions[i - 1] } } } open fun onTextChange(oldText: String) { } open fun onEnterPressed(): Boolean { return false } override fun render(screen: S, batch: SpriteBatch, shapeRenderer: ShapeRenderer) { if (background) { val old = batch.packedColor batch.color = palette.backColor batch.fillRect(location.realX, location.realY, location.realWidth, location.realHeight) batch.packedColor = old } caretTimer += Gdx.graphics.deltaTime val labelWidth = location.realWidth val labelHeight = location.realHeight val font = getFont() val isUsingEmpty = !hasFocus && renderedText.isEmpty() val text = if (!isUsingEmpty) renderedText else textWhenEmpty val textHeight = font.getTextHeight(text, labelWidth, false) val y: Float y = location.realY + location.realHeight / 2 + textHeight / 2 val oldColor = font.color val oldScale = font.scaleX val wasMarkupEnabled = font.data.markupEnabled font.color = if (isUsingEmpty) textWhenEmptyColor else palette.textColor font.data.setScale(palette.fontScale) font.data.markupEnabled = false shapeRenderer.prepareStencilMask(batch) { this.projectionMatrix = batch.projectionMatrix this.setColor(1f, 1f, 1f, 1f) this.begin(ShapeRenderer.ShapeType.Filled) this.rect(location.realX, location.realY, location.realWidth, location.realHeight) this.end() }.useStencilMask { val layout: GlyphLayout = font.draw(batch, text, location.realX - xOffset, y, labelWidth, textAlign, false) val caretBlink: Boolean = !isUsingEmpty && hasFocus && (caretTimer % (CARET_BLINK_RATE * 2)) <= 0.5f if (caretBlink) { val oldColor = batch.packedColor batch.color = font.color val glyphX = if (textPositions.isNotEmpty()) textPositions[caret.coerceIn(0, (textPositions.size - 1).coerceAtLeast(0))] else 0f val xWithAlign: Float = when { textAlign and Align.center == Align.center -> { glyphX + location.realWidth / 2 - layout.width / 2 } textAlign and Align.right == Align.right -> { location.realWidth - layout.width + glyphX } else -> { glyphX } } batch.fillRect( location.realX - xOffset + xWithAlign, y - font.capHeight - CARET_WIDTH, CARET_WIDTH, (font.capHeight + CARET_WIDTH * 2)) batch.packedColor = oldColor } } font.color = oldColor font.data.setScale(oldScale) font.data.markupEnabled = wasMarkupEnabled if (caretMoveTimer > 0) { caretMoveTimer -= Gdx.graphics.deltaTime caretMoveTimer = Math.max(caretMoveTimer, 0f) if (caretMoveTimer == 0f) { caretMoveTimer = CARET_MOVE_TIMER if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) { caret-- } else if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) { caret++ } } } } override fun frameUpdate(screen: S) { super.frameUpdate(screen) if (hasFocus) { val control = Gdx.input.isControlDown() val alt = Gdx.input.isAltDown() val shift = Gdx.input.isShiftDown() if (Gdx.input.isKeyJustPressed(Input.Keys.V) && control && !alt && !shift) { try { var data: String = Gdx.app.clipboard.contents?.replace("\r", "") ?: return if (!canInputNewlines) { data = data.replace("\n", "") } if (data.all(canTypeText) && canPaste) { text = text.substring(0, caret) + data + text.substring(caret) if (characterLimit > 0 && text.length > characterLimit) { text = text.substring(0, characterLimit) caret = text.length } else { caret += data.length } caretMoveTimer = 0f } } catch (ignored: Exception) { } } } } override fun keyTyped(character: Char): Boolean { if (!hasFocus) return false val control = Gdx.input.isControlDown() val alt = Gdx.input.isAltDown() val shift = Gdx.input.isShiftDown() when (character) { TAB -> return false BACKSPACE -> { return if (text.isNotEmpty() && caret > 0) { val oldCaret = caret if (control && !alt && !shift && text.isNotEmpty()) { val lookIn = text.substring(0, caret) caret = lookIn.indexOfLast { it == ' ' || it == '\n' } } else { caret-- } text = text.substring(0, caret) + text.substring(oldCaret) true } else { false } } DELETE -> { return if (text.isNotEmpty() && caret < text.length) { val oldCaret = caret val newNextIndex = if (control && !alt && !shift && text.isNotEmpty() && caret < text.length) { val lookIn = text.substring(caret + 1) val index = lookIn.indexOfFirst { it == ' ' || it == '\n' } if (index != -1) (index + caret + 1) else text.length } else (oldCaret + 1) text = text.substring(0, oldCaret) + text.substring(newNextIndex) true } else { false } } ENTER_ANDROID, ENTER_DESKTOP -> { return if (canInputNewlines && shift && !alt && !control) { text = text.substring(0, caret) + "\n" + text.substring(caret) caret++ caretMoveTimer = 0f true } else { onEnterPressed() } } else -> { if (character < 32.toChar()) return false if (!canTypeText(character) || (characterLimit > 0 && text.length >= characterLimit)) return false text = text.substring(0, caret) + character + text.substring(caret) caret++ caretMoveTimer = 0f return true } } } override fun canBeClickedOn(): Boolean = true fun checkFocus() { if (hasFocus && (!isMouseOver() || !visible)) { hasFocus = false } } override fun touchDown(screenX: Int, screenY: Int, pointer: Int, button: Int): Boolean { if (hasFocus && (!isMouseOver() || !visible)) { hasFocus = false return false } if (super.touchDown(screenX, screenY, pointer, button)) return true return isMouseOver() && hasFocus && visible } override fun keyDown(keycode: Int): Boolean { if (!hasFocus) return false val control = Gdx.input.isControlDown() val alt = Gdx.input.isAltDown() val shift = Gdx.input.isShiftDown() when (keycode) { Input.Keys.LEFT -> { if (control && !alt && !shift && text.isNotEmpty()) { val lookIn = text.substring(0, caret) caret = lookIn.indexOfLast { it == ' ' || it == '\n' } } else { caret-- } caretMoveTimer = INITIAL_CARET_TIMER return true } Input.Keys.RIGHT -> { if (control && !alt && !shift && text.isNotEmpty() && caret < text.length) { val lookIn = text.substring(caret + 1) val index = lookIn.indexOfFirst { it == ' ' || it == '\n' } caret = if (index != -1) (index + caret + 1) else text.length } else { caret++ } caretMoveTimer = INITIAL_CARET_TIMER return true } Input.Keys.HOME -> { caret = 0 caretMoveTimer = INITIAL_CARET_TIMER return true } Input.Keys.END -> { caret = text.length caretMoveTimer = INITIAL_CARET_TIMER return true } } return super.keyDown(keycode) } override fun keyUp(keycode: Int): Boolean { if (!hasFocus) return false when (keycode) { Input.Keys.LEFT, Input.Keys.RIGHT -> { caretMoveTimer = -1f return true } } return super.keyUp(keycode) } override fun onLeftClick(xPercent: Float, yPercent: Float) { super.onLeftClick(xPercent, yPercent) if (isMouseOver() && visible) hasFocus = true // copied from Kotlin stdlib with modifications fun <T> List<T>.binarySearch(fromIndex: Int = 0, toIndex: Int = size, comparison: (T) -> Int): Int { var low = fromIndex var high = toIndex - 1 while (low <= high) { val mid = (low + high).ushr(1) // safe from overflows val midVal = get(mid) val cmp = comparison(midVal) if (cmp < 0) low = mid + 1 else if (cmp > 0) high = mid - 1 else return mid // key found } return low // key not found } val rawpx = xPercent * location.realWidth val thing = when { textAlign and Align.center == Align.center -> { rawpx - (location.realWidth / 2 - layout.width / 2) } textAlign and Align.right == Align.right -> { rawpx - (location.realWidth - layout.width) } else -> { rawpx } } val px = (thing + xOffset) caret = textPositions.sorted().binarySearch { it.compareTo(px) } } }
gpl-3.0
6aef2774123bd7c3fe4635281536d815
33.845805
185
0.499479
4.876547
false
false
false
false
allotria/intellij-community
plugins/ide-features-trainer/src/training/learn/lesson/general/assistance/ParameterInfoLesson.kt
3
1516
// 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.learn.lesson.general.assistance import training.dsl.LessonContext import training.dsl.LessonSample import training.dsl.LessonUtil.restoreIfModifiedOrMoved import training.dsl.TaskRuntimeContext import training.learn.LessonsBundle import training.learn.course.KLesson import kotlin.math.min class ParameterInfoLesson(private val sample: LessonSample) : KLesson("CodeAssistance.ParameterInfo", LessonsBundle.message("parameter.info.lesson.name")) { override val lessonContent: LessonContext.() -> Unit = { prepareSample(sample) var caretOffset = 0 prepareRuntimeTask { caretOffset = editor.caretModel.offset } actionTask("ParameterInfo") { restoreIfModifiedOrMoved() LessonsBundle.message("parameter.info.use.action", action(it)) } task { text(LessonsBundle.message("parameter.info.add.parameters", code("175"), code("100"))) stateCheck { checkParametersAdded(caretOffset) } test { type("175, 100") } } } private val parametersRegex = Regex("""175[ \n]*,[ \n]*100[\s\S]*""") private fun TaskRuntimeContext.checkParametersAdded(caretOffset: Int): Boolean { val sequence = editor.document.charsSequence val partOfSequence = sequence.subSequence(caretOffset, min(caretOffset + 20, sequence.length)) return partOfSequence.matches(parametersRegex) } }
apache-2.0
a70a4a9365d6ca4f3e54842071bac4f7
33.477273
140
0.738786
4.593939
false
false
false
false
allotria/intellij-community
platform/object-serializer/src/BaseCollectionBinding.kt
6
1161
// 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.serialization import com.amazon.ion.IonType import java.lang.reflect.Type import java.util.function.Consumer internal abstract class BaseCollectionBinding(itemType: Type, context: BindingInitializationContext) : Binding { private val itemBinding = createElementBindingByType(itemType, context) protected fun createItemConsumer(context: WriteContext): Consumer<Any?> { val writer = context.writer return Consumer { if (it == null) { writer.writeNull() } else { itemBinding.serialize(it, context) } } } fun readInto(hostObject: Any?, result: MutableCollection<Any?>, context: ReadContext) { val reader = context.reader reader.stepIn() while (true) { @Suppress("MoveVariableDeclarationIntoWhen") val type = reader.next() ?: break val item = when (type) { IonType.NULL -> null else -> itemBinding.deserialize(context, hostObject) } result.add(item) } reader.stepOut() } }
apache-2.0
d392a80941291ae35bbebe498c1ebc5f
30.405405
140
0.689061
4.381132
false
false
false
false
bekwam/todomvcFX
examples/tornadofx/src/main/kotlin/todomvcfx/tornadofx/viewmodel/TodoItem.kt
1
860
package todomvcfx.tornadofx.viewmodel import javafx.beans.property.SimpleBooleanProperty import javafx.beans.property.SimpleIntegerProperty import javafx.beans.property.SimpleStringProperty import tornadofx.getValue import tornadofx.setValue /** * Model component for the TornadoFX version of the TodoItem app * * TodoItem is a property-based domain object for the app. It includes an id generation function. * * Created by ronsmits on 24/09/16. */ class TodoItem(text: String, completed: Boolean) { val idProperty = SimpleIntegerProperty( nextId() ) var id by idProperty val textProperty = SimpleStringProperty(text) val completedProperty = SimpleBooleanProperty(completed) var completed by completedProperty companion object { private var idgen = 1 // faux static class member fun nextId() = idgen++ } }
mit
fc2d5a7316769a872b29d295ccb86ae5
29.75
98
0.759302
4.699454
false
false
false
false
leafclick/intellij-community
platform/diff-impl/src/com/intellij/diff/tools/util/base/TextDiffSettingsHolder.kt
1
7378
// 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.diff.tools.util.base import com.intellij.diff.tools.util.breadcrumbs.BreadcrumbsPlacement import com.intellij.diff.util.DiffPlaces import com.intellij.diff.util.DiffUtil import com.intellij.openapi.Disposable import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.components.service import com.intellij.openapi.util.Key import com.intellij.util.EventDispatcher import com.intellij.util.xmlb.annotations.OptionTag import com.intellij.util.xmlb.annotations.Transient import com.intellij.util.xmlb.annotations.XMap import java.util.* @State(name = "TextDiffSettings", storages = [(Storage(value = DiffUtil.DIFF_CONFIG))]) class TextDiffSettingsHolder : PersistentStateComponent<TextDiffSettingsHolder.State> { companion object { @JvmField val CONTEXT_RANGE_MODES: IntArray = intArrayOf(1, 2, 4, 8, -1) @JvmField val CONTEXT_RANGE_MODE_LABELS: Array<String> = arrayOf("1", "2", "4", "8", "Disable") } data class SharedSettings( // Fragments settings var CONTEXT_RANGE: Int = 4, var MERGE_AUTO_APPLY_NON_CONFLICTED_CHANGES: Boolean = false, var MERGE_LST_GUTTER_MARKERS: Boolean = true ) data class PlaceSettings( // Diff settings var HIGHLIGHT_POLICY: HighlightPolicy = HighlightPolicy.BY_WORD, var IGNORE_POLICY: IgnorePolicy = IgnorePolicy.DEFAULT, // Presentation settings var ENABLE_SYNC_SCROLL: Boolean = true, // Editor settings var SHOW_WHITESPACES: Boolean = false, var SHOW_LINE_NUMBERS: Boolean = true, var SHOW_INDENT_LINES: Boolean = false, var USE_SOFT_WRAPS: Boolean = false, var HIGHLIGHTING_LEVEL: HighlightingLevel = HighlightingLevel.INSPECTIONS, var READ_ONLY_LOCK: Boolean = true, var BREADCRUMBS_PLACEMENT: BreadcrumbsPlacement = BreadcrumbsPlacement.HIDDEN, // Fragments settings var EXPAND_BY_DEFAULT: Boolean = true ) { @Transient val eventDispatcher: EventDispatcher<TextDiffSettings.Listener> = EventDispatcher.create(TextDiffSettings.Listener::class.java) } class TextDiffSettings internal constructor(private val SHARED_SETTINGS: SharedSettings, private val PLACE_SETTINGS: PlaceSettings, val place: String?) { constructor() : this(SharedSettings(), PlaceSettings(), null) fun addListener(listener: Listener, disposable: Disposable) { PLACE_SETTINGS.eventDispatcher.addListener(listener, disposable) } // Presentation settings var isEnableSyncScroll: Boolean get() = PLACE_SETTINGS.ENABLE_SYNC_SCROLL set(value) { PLACE_SETTINGS.ENABLE_SYNC_SCROLL = value } // Diff settings var highlightPolicy: HighlightPolicy get() = PLACE_SETTINGS.HIGHLIGHT_POLICY set(value) { PLACE_SETTINGS.HIGHLIGHT_POLICY = value PLACE_SETTINGS.eventDispatcher.multicaster.highlightPolicyChanged() } var ignorePolicy: IgnorePolicy get() = PLACE_SETTINGS.IGNORE_POLICY set(value) { PLACE_SETTINGS.IGNORE_POLICY = value PLACE_SETTINGS.eventDispatcher.multicaster.ignorePolicyChanged() } // // Merge // var isAutoApplyNonConflictedChanges: Boolean get() = SHARED_SETTINGS.MERGE_AUTO_APPLY_NON_CONFLICTED_CHANGES set(value) { SHARED_SETTINGS.MERGE_AUTO_APPLY_NON_CONFLICTED_CHANGES = value } var isEnableLstGutterMarkersInMerge: Boolean get() = SHARED_SETTINGS.MERGE_LST_GUTTER_MARKERS set(value) { SHARED_SETTINGS.MERGE_LST_GUTTER_MARKERS = value } // Editor settings var isShowLineNumbers: Boolean get() = PLACE_SETTINGS.SHOW_LINE_NUMBERS set(value) { PLACE_SETTINGS.SHOW_LINE_NUMBERS = value } var isShowWhitespaces: Boolean get() = PLACE_SETTINGS.SHOW_WHITESPACES set(value) { PLACE_SETTINGS.SHOW_WHITESPACES = value } var isShowIndentLines: Boolean get() = PLACE_SETTINGS.SHOW_INDENT_LINES set(value) { PLACE_SETTINGS.SHOW_INDENT_LINES = value } var isUseSoftWraps: Boolean get() = PLACE_SETTINGS.USE_SOFT_WRAPS set(value) { PLACE_SETTINGS.USE_SOFT_WRAPS = value } var highlightingLevel: HighlightingLevel get() = PLACE_SETTINGS.HIGHLIGHTING_LEVEL set(value) { PLACE_SETTINGS.HIGHLIGHTING_LEVEL = value } var contextRange: Int get() = SHARED_SETTINGS.CONTEXT_RANGE set(value) { SHARED_SETTINGS.CONTEXT_RANGE = value } var isExpandByDefault: Boolean get() = PLACE_SETTINGS.EXPAND_BY_DEFAULT set(value) { PLACE_SETTINGS.EXPAND_BY_DEFAULT = value } var isReadOnlyLock: Boolean get() = PLACE_SETTINGS.READ_ONLY_LOCK set(value) { PLACE_SETTINGS.READ_ONLY_LOCK = value } var breadcrumbsPlacement: BreadcrumbsPlacement get() = PLACE_SETTINGS.BREADCRUMBS_PLACEMENT set(value) { PLACE_SETTINGS.BREADCRUMBS_PLACEMENT = value PLACE_SETTINGS.eventDispatcher.multicaster.breadcrumbsPlacementChanged() } // // Impl // companion object { @JvmField val KEY: Key<TextDiffSettings> = Key.create("TextDiffSettings") @JvmStatic fun getSettings(): TextDiffSettings = getSettings(null) @JvmStatic fun getSettings(place: String?): TextDiffSettings = service<TextDiffSettingsHolder>().getSettings(place) internal fun getDefaultSettings(place: String): TextDiffSettings = TextDiffSettings(SharedSettings(), service<TextDiffSettingsHolder>().defaultPlaceSettings(place), place) } interface Listener : EventListener { fun highlightPolicyChanged() {} fun ignorePolicyChanged() {} fun breadcrumbsPlacementChanged() {} abstract class Adapter : Listener } } fun getSettings(place: String?): TextDiffSettings { val placeKey = place ?: DiffPlaces.DEFAULT val placeSettings = myState.PLACES_MAP.getOrPut(placeKey) { defaultPlaceSettings(placeKey) } return TextDiffSettings(myState.SHARED_SETTINGS, placeSettings, placeKey) } private fun copyStateWithoutDefaults(): State { val result = State() result.SHARED_SETTINGS = myState.SHARED_SETTINGS result.PLACES_MAP = DiffUtil.trimDefaultValues(myState.PLACES_MAP) { defaultPlaceSettings(it) } return result } private fun defaultPlaceSettings(place: String): PlaceSettings { val settings = PlaceSettings() if (place == DiffPlaces.CHANGES_VIEW) { settings.EXPAND_BY_DEFAULT = false settings.SHOW_LINE_NUMBERS = false } if (place == DiffPlaces.COMMIT_DIALOG) { settings.EXPAND_BY_DEFAULT = false } if (place == DiffPlaces.VCS_LOG_VIEW) { settings.EXPAND_BY_DEFAULT = false } return settings } class State { @OptionTag @XMap @JvmField var PLACES_MAP: TreeMap<String, PlaceSettings> = TreeMap() @JvmField var SHARED_SETTINGS: SharedSettings = SharedSettings() } private var myState: State = State() override fun getState(): State { return copyStateWithoutDefaults() } override fun loadState(state: State) { myState = state } }
apache-2.0
88081add27a4b64eacd4b8fb67224118
35.349754
140
0.703307
4.50978
false
false
false
false
leafclick/intellij-community
platform/script-debugger/protocol/protocol-reader-runtime/src/org/jetbrains/jsonProtocol/OutMessage.kt
1
6452
// 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.jsonProtocol import com.google.gson.stream.JsonWriter import com.intellij.util.containers.isNullOrEmpty import com.intellij.util.io.writeUtf8 import gnu.trove.TIntArrayList import gnu.trove.TIntHashSet import io.netty.buffer.ByteBuf import io.netty.buffer.ByteBufAllocator import io.netty.buffer.ByteBufUtf8Writer import org.jetbrains.io.JsonUtil open class OutMessage { val buffer: ByteBuf = ByteBufAllocator.DEFAULT.buffer() val writer: JsonWriter = JsonWriter(ByteBufUtf8Writer(buffer)) private var finalized: Boolean = false init { writer.beginObject() } open fun beginArguments() { } fun writeMap(name: String, value: Map<String, String>? = null) { if (value == null) return beginArguments() writer.name(name) writer.beginObject() for ((key, value1) in value) { writer.name(key).value(value1) } writer.endObject() } protected fun writeLongArray(name: String, value: LongArray) { beginArguments() writer.name(name) writer.beginArray() for (v in value) { writer.value(v) } writer.endArray() } fun writeDoubleArray(name: String, value: DoubleArray) { beginArguments() writer.name(name) writer.beginArray() for (v in value) { writer.value(v) } writer.endArray() } fun writeIntArray(name: String, value: IntArray? = null) { if (value == null) { return } beginArguments() writer.name(name) writer.beginArray() for (v in value) { writer.value(v.toLong()) } writer.endArray() } fun writeIntSet(name: String, value: TIntHashSet) { beginArguments() writer.name(name) writer.beginArray() value.forEach { value -> writer.value(value.toLong()) true } writer.endArray() } fun writeIntList(name: String, value: TIntArrayList) { beginArguments() writer.name(name) writer.beginArray() for (i in 0..value.size() - 1) { writer.value(value.getQuick(i).toLong()) } writer.endArray() } fun writeSingletonIntArray(name: String, value: Int) { beginArguments() writer.name(name) writer.beginArray() writer.value(value.toLong()) writer.endArray() } fun <E : OutMessage> writeList(name: String, value: List<E>?) { if (value.isNullOrEmpty()) { return } beginArguments() writer.name(name) writer.beginArray() var isNotFirst = false for (item in value!!) { try { if (isNotFirst) { buffer.writeByte(','.toInt()).writeByte(' '.toInt()) } else { isNotFirst = true } if (!item.finalized) { item.finalized = true try { item.writer.endObject() } catch (e: IllegalStateException) { if ("Nesting problem." == e.message) { throw RuntimeException(item.buffer.toString(Charsets.UTF_8) + "\nparent:\n" + buffer.toString(Charsets.UTF_8), e) } else { throw e } } } buffer.writeBytes(item.buffer) } finally { if (item.buffer.refCnt() > 0) { item.buffer.release() } } } writer.endArray() } fun writeStringList(name: String, value: Collection<String>?) { if (value == null) return beginArguments() JsonWriters.writeStringList(writer, name, value) } fun writeEnumList(name: String, values: Collection<Enum<*>>) { beginArguments() writer.name(name).beginArray() for (item in values) { writer.value(item.toString()) } writer.endArray() } fun writeMessage(name: String, value: OutMessage?) { if (value == null) { return } try { beginArguments() prepareWriteRaw(this, name) if (!value.finalized) { value.close() } buffer.writeBytes(value.buffer) } finally { if (value.buffer.refCnt() > 0) { value.buffer.release() } } } fun close() { assert(!finalized) finalized = true writer.endObject() writer.close() } protected fun writeLong(name: String, value: Long) { beginArguments() writer.name(name).value(value) } fun writeString(name: String, value: String?) { if (value != null) { writeNullableString(name, value) } } fun writeNullableString(name: String, value: CharSequence?) { beginArguments() writer.name(name).value(value?.toString()) } } fun prepareWriteRaw(message: OutMessage, name: String) { message.writer.name(name).nullValue() val itemBuffer = message.buffer itemBuffer.writerIndex(itemBuffer.writerIndex() - "null".length) } fun doWriteRaw(message: OutMessage, rawValue: String) { message.buffer.writeUtf8(rawValue) } fun OutMessage.writeEnum(name: String, value: Enum<*>?, defaultValue: Enum<*>?) { if (value != null && value != defaultValue) { writeEnum(name, value) } } fun OutMessage.writeEnum(name: String, value: Enum<*>) { beginArguments() writer.name(name).value(value.toString()) } fun OutMessage.writeString(name: String, value: CharSequence?, defaultValue: CharSequence?) { if (value != null && value != defaultValue) { writeString(name, value) } } fun OutMessage.writeString(name: String, value: CharSequence) { beginArguments() prepareWriteRaw(this, name) JsonUtil.escape(value, buffer) } fun OutMessage.writeInt(name: String, value: Int, defaultValue: Int) { if (value != defaultValue) { writeInt(name, value) } } fun OutMessage.writeInt(name: String, value: Int?) { if (value != null) { beginArguments() writer.name(name).value(value.toLong()) } } fun OutMessage.writeBoolean(name: String, value: Boolean, defaultValue: Boolean) { if (value != defaultValue) { writeBoolean(name, value) } } fun OutMessage.writeBoolean(name: String, value: Boolean?) { if (value != null) { beginArguments() writer.name(name).value(value) } } fun OutMessage.writeDouble(name: String, value: Double?, defaultValue: Double?) { if (value != null && value != defaultValue) { writeDouble(name, value) } } fun OutMessage.writeDouble(name: String, value: Double) { beginArguments() writer.name(name).value(value) }
apache-2.0
a0755202e58dc308aaf58ff60c0ae60e
22.720588
140
0.633602
3.95101
false
false
false
false
leafclick/intellij-community
platform/vcs-impl/src/com/intellij/vcs/commit/SingleChangeListCommitWorkflow.kt
1
5404
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.vcs.commit import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.AbstractVcs import com.intellij.openapi.vcs.VcsBundle.message import com.intellij.openapi.vcs.changes.* import com.intellij.openapi.vcs.changes.ui.CommitChangeListDialog.DIALOG_TITLE import com.intellij.openapi.vcs.checkin.CheckinChangeListSpecificComponent import com.intellij.openapi.vcs.checkin.CheckinHandler import com.intellij.openapi.vcs.impl.PartialChangesUtil import com.intellij.util.ui.UIUtil.removeMnemonic import com.intellij.vcs.commit.SingleChangeListCommitter.Companion.moveToFailedList private val LOG = logger<SingleChangeListCommitWorkflow>() internal val CommitOptions.changeListSpecificOptions: Sequence<CheckinChangeListSpecificComponent> get() = allOptions.filterIsInstance<CheckinChangeListSpecificComponent>() internal fun CommitOptions.changeListChanged(changeList: LocalChangeList) = changeListSpecificOptions.forEach { it.onChangeListSelected(changeList) } internal fun CommitOptions.saveChangeListSpecificOptions() = changeListSpecificOptions.forEach { it.saveState() } internal fun removeEllipsisSuffix(s: String) = s.removeSuffix("...").removeSuffix("\u2026") internal fun CommitExecutor.getPresentableText() = removeEllipsisSuffix(removeMnemonic(actionText)) open class SingleChangeListCommitWorkflow( project: Project, affectedVcses: Set<AbstractVcs>, val initiallyIncluded: Collection<*>, val initialChangeList: LocalChangeList? = null, executors: List<CommitExecutor> = emptyList(), final override val isDefaultCommitEnabled: Boolean = executors.isEmpty(), private val isDefaultChangeListFullyIncluded: Boolean = true, val initialCommitMessage: String? = null, private val resultHandler: CommitResultHandler? = null ) : AbstractCommitWorkflow(project) { init { updateVcses(affectedVcses) initCommitExecutors(executors) } val isPartialCommitEnabled: Boolean = vcses.any { it.arePartialChangelistsSupported() } && (isDefaultCommitEnabled || commitExecutors.any { it.supportsPartialCommit() }) internal val commitMessagePolicy: SingleChangeListCommitMessagePolicy = SingleChangeListCommitMessagePolicy(project, initialCommitMessage) internal lateinit var commitState: ChangeListCommitState override fun processExecuteDefaultChecksResult(result: CheckinHandler.ReturnResult) = when (result) { CheckinHandler.ReturnResult.COMMIT -> DefaultNameChangeListCleaner(project, commitState).use { doCommit(commitState) } CheckinHandler.ReturnResult.CLOSE_WINDOW -> moveToFailedList(project, commitState, message("commit.dialog.rejected.commit.template", commitState.changeList.name)) CheckinHandler.ReturnResult.CANCEL -> Unit } override fun executeCustom(executor: CommitExecutor, session: CommitSession): Boolean = executeCustom(executor, session, commitState.changes, commitState.commitMessage) override fun processExecuteCustomChecksResult(executor: CommitExecutor, session: CommitSession, result: CheckinHandler.ReturnResult) = when (result) { CheckinHandler.ReturnResult.COMMIT -> doCommitCustom(executor, session) CheckinHandler.ReturnResult.CLOSE_WINDOW -> moveToFailedList(project, commitState, message("commit.dialog.rejected.commit.template", commitState.changeList.name)) CheckinHandler.ReturnResult.CANCEL -> Unit } override fun doRunBeforeCommitChecks(checks: Runnable) = PartialChangesUtil.runUnderChangeList(project, commitState.changeList, checks) protected open fun doCommit(commitState: ChangeListCommitState) { LOG.debug("Do actual commit") with(object : SingleChangeListCommitter(project, commitState, commitContext, DIALOG_TITLE, isDefaultChangeListFullyIncluded) { override fun afterRefreshChanges() = endExecution { super.afterRefreshChanges() } }) { addResultHandler(CommitHandlersNotifier(commitHandlers)) addResultHandler(getCommitEventDispatcher()) addResultHandler(resultHandler ?: ShowNotificationCommitResultHandler(this)) runCommit(DIALOG_TITLE, false) } } private fun doCommitCustom(executor: CommitExecutor, session: CommitSession) { val cleaner = DefaultNameChangeListCleaner(project, commitState) with(CustomCommitter(project, session, commitState.changes, commitState.commitMessage)) { addResultHandler(CommitHandlersNotifier(commitHandlers)) addResultHandler(CommitResultHandler { cleaner.clean() }) addResultHandler(getCommitCustomEventDispatcher()) resultHandler?.let { addResultHandler(it) } addResultHandler(getEndExecutionHandler()) runCommit(executor.actionText) } } } private class DefaultNameChangeListCleaner(val project: Project, commitState: ChangeListCommitState) { private val isChangeListFullyIncluded = commitState.changeList.changes.size == commitState.changes.size private val isDefaultNameChangeList = commitState.changeList.hasDefaultName() fun use(block: () -> Unit) { block() clean() } fun clean() { if (isDefaultNameChangeList && isChangeListFullyIncluded) { ChangeListManager.getInstance(project).editComment(LocalChangeList.getDefaultName(), "") } } }
apache-2.0
404284f1f5668b196bedafa4a420de7e
44.805085
140
0.796632
5.267057
false
false
false
false
room-15/ChatSE
app/src/main/java/com/tristanwiley/chatse/chat/adapters/UploadImageAdapter.kt
1
2016
package com.tristanwiley.chatse.chat.adapters import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.ImageView import android.widget.TextView import com.tristanwiley.chatse.R /** * Adapter for DialogPlus to display the different uploading options * @param context: Application context */ class UploadImageAdapter(context: Context) : BaseAdapter() { private val layoutInflater: LayoutInflater = LayoutInflater.from(context) override fun getCount(): Int { return 2 } override fun getItem(position: Int): Any { return position } override fun getItemId(position: Int): Long { return position.toLong() } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? { val viewHolder: UploadImageAdapter.ViewHolder var view = convertView if (view == null) { view = layoutInflater.inflate(R.layout.simple_grid_item, parent, false) viewHolder = UploadImageAdapter.ViewHolder() viewHolder.textView = view.findViewById(R.id.text_view) viewHolder.imageView = view.findViewById(R.id.image_view) view.tag = viewHolder } else { viewHolder = view.tag as UploadImageAdapter.ViewHolder } val context = parent.context when (position) { 0 -> { viewHolder.textView?.text = context.getString(R.string.take_photo) viewHolder.imageView?.setImageResource(R.drawable.ic_camera) } 1 -> { viewHolder.textView?.text = context.getString(R.string.choose_from_gallery) viewHolder.imageView?.setImageResource(R.drawable.ic_gallery_pick) } } return view } internal class ViewHolder { var textView: TextView? = null var imageView: ImageView? = null } }
apache-2.0
043b21814090832b90ad7d67dec2cbca
29.545455
91
0.652778
4.765957
false
false
false
false
Nunnery/MythicDrops
src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/utils/ReflectionUtil.kt
1
4691
/* * This file is part of MythicDrops, licensed under the MIT License. * * Copyright (C) 2020 Richard Harrah * * Permission is hereby granted, free of charge, * to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.tealcube.minecraft.bukkit.mythicdrops.utils import org.bukkit.Bukkit import java.lang.reflect.Constructor import java.lang.reflect.Field import java.lang.reflect.Method /** * Reflection utilities for NMS/CraftBukkit. */ object ReflectionUtil { /** * Version string for NMS and CraftBukkit classes. */ @JvmStatic val version: String by lazy { Bukkit.getServer().javaClass.`package`.name.let { it.substring(it.lastIndexOf('.') + 1) + "." } } // cache of loaded NMS classes private val loadedNmsClasses = mutableMapOf<String, Class<*>?>() // cache of loaded CraftBukkit classes private val loadedCbClasses = mutableMapOf<String, Class<*>?>() // cache of loaded methods private val loadedMethods = mutableMapOf<Class<*>, MutableMap<String, Method?>>() // cache of loaded fields private val loadedFields = mutableMapOf<Class<*>, MutableMap<String, Field?>>() /** * Attempts to get an NMS class from the cache if in the cache, tries to put it in the cache if it's not already * there. */ @JvmStatic @Synchronized fun getNmsClass(nmsClassName: String): Class<*>? = loadedNmsClasses.getOrPut(nmsClassName) { val clazzName = "net.minecraft.server.${version}$nmsClassName" try { Class.forName(clazzName) } catch (ex: ClassNotFoundException) { null } } /** * Attempts to get a CraftBukkit class from the cache if in the cache, tries to put it in the cache if it's not * already there. */ @JvmStatic @Synchronized fun getCbClass(nmsClassName: String): Class<*>? = loadedCbClasses.getOrPut(nmsClassName) { val clazzName = "org.bukkit.craftbukkit.${version}$nmsClassName" try { Class.forName(clazzName) } catch (ex: ClassNotFoundException) { null } } /** * Attempts to find the constructor on the class that has the same types of parameters. */ @Suppress("detekt.SpreadOperator") fun getConstructor(clazz: Class<*>, vararg params: Class<*>): Constructor<*>? = try { clazz.getConstructor(*params) } catch (ex: NoSuchMethodException) { null } /** * Attempts to find the method on the class that has the same types of parameters and same name. */ @Suppress("detekt.SpreadOperator") fun getMethod(clazz: Class<*>, methodName: String, vararg params: Class<*>): Method? { val methods = loadedMethods[clazz] ?: mutableMapOf() if (methods.containsKey(methodName)) { return methods[methodName] } val method = try { clazz.getMethod(methodName, *params) } catch (ex: NoSuchMethodException) { null } methods[methodName] = method loadedMethods[clazz] = methods return method } /** * Attempts to find the field on the class that has the same name. */ @Suppress("detekt.SpreadOperator") fun getField(clazz: Class<*>, fieldName: String): Field? { val fields = loadedFields[clazz] ?: mutableMapOf() if (fields.containsKey(fieldName)) { return fields[fieldName] } val method = try { clazz.getField(fieldName) } catch (ex: NoSuchFieldException) { null } fields[fieldName] = method loadedFields[clazz] = fields return method } }
mit
0ccbf9c451eab2d59fc31bd426ffcb2f
33.492647
116
0.65615
4.752786
false
false
false
false
codeka/wwmmo
common/src/main/kotlin/au/com/codeka/warworlds/common/NormalRandom.kt
1
629
package au.com.codeka.warworlds.common import java.util.* class NormalRandom : Random() { /** * Gets a random double between -1..1, but with a normal distribution around 0.0 (i.e. the * majority of values will be close to 0.0, falling off in both directions). */ operator fun next(): Double { return normalRandom(1000).toDouble() / 500.0 - 1.0 } private fun normalRandom(max: Int): Int { val rounds = 5 var n = 0 val step = max / rounds for (i in 0 until rounds) { n += nextInt(step - 1) } return n } companion object { private const val serialVersionUID = 1L } }
mit
51c333142a15b3e156db888642071891
22.333333
93
0.631161
3.594286
false
false
false
false
AndroidX/androidx
work/work-runtime/src/main/java/androidx/work/impl/WorkDatabase.kt
3
7528
/* * Copyright 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.work.impl import android.content.Context import androidx.annotation.RestrictTo import androidx.room.AutoMigration import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.TypeConverters import androidx.sqlite.db.SupportSQLiteDatabase import androidx.sqlite.db.SupportSQLiteOpenHelper import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory import androidx.work.Data import androidx.work.impl.WorkDatabaseVersions.VERSION_10 import androidx.work.impl.WorkDatabaseVersions.VERSION_11 import androidx.work.impl.WorkDatabaseVersions.VERSION_2 import androidx.work.impl.WorkDatabaseVersions.VERSION_3 import androidx.work.impl.WorkDatabaseVersions.VERSION_5 import androidx.work.impl.WorkDatabaseVersions.VERSION_6 import androidx.work.impl.model.Dependency import androidx.work.impl.model.DependencyDao import androidx.work.impl.model.Preference import androidx.work.impl.model.PreferenceDao import androidx.work.impl.model.RawWorkInfoDao import androidx.work.impl.model.SystemIdInfo import androidx.work.impl.model.SystemIdInfoDao import androidx.work.impl.model.WorkName import androidx.work.impl.model.WorkNameDao import androidx.work.impl.model.WorkProgress import androidx.work.impl.model.WorkProgressDao import androidx.work.impl.model.WorkSpec import androidx.work.impl.model.WorkSpecDao import androidx.work.impl.model.WorkTag import androidx.work.impl.model.WorkTagDao import androidx.work.impl.model.WorkTypeConverters import androidx.work.impl.model.WorkTypeConverters.StateIds.COMPLETED_STATES import java.util.concurrent.Executor import java.util.concurrent.TimeUnit /** * A Room database for keeping track of work states. * * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @Database( entities = [Dependency::class, WorkSpec::class, WorkTag::class, SystemIdInfo::class, WorkName::class, WorkProgress::class, Preference::class], autoMigrations = [ AutoMigration(from = 13, to = 14), AutoMigration(from = 14, to = 15, spec = AutoMigration_14_15::class), ], version = 16 ) @TypeConverters(value = [Data::class, WorkTypeConverters::class]) abstract class WorkDatabase : RoomDatabase() { /** * @return The Data Access Object for [WorkSpec]s. */ abstract fun workSpecDao(): WorkSpecDao /** * @return The Data Access Object for [Dependency]s. */ abstract fun dependencyDao(): DependencyDao /** * @return The Data Access Object for [WorkTag]s. */ abstract fun workTagDao(): WorkTagDao /** * @return The Data Access Object for [SystemIdInfo]s. */ abstract fun systemIdInfoDao(): SystemIdInfoDao /** * @return The Data Access Object for [WorkName]s. */ abstract fun workNameDao(): WorkNameDao /** * @return The Data Access Object for [WorkProgress]. */ abstract fun workProgressDao(): WorkProgressDao /** * @return The Data Access Object for [Preference]. */ abstract fun preferenceDao(): PreferenceDao /** * @return The Data Access Object which can be used to execute raw queries. */ abstract fun rawWorkInfoDao(): RawWorkInfoDao companion object { /** * Creates an instance of the WorkDatabase. * * @param context A context (this method will use the application context from it) * @param queryExecutor An [Executor] that will be used to execute all async Room * queries. * @param useTestDatabase `true` to generate an in-memory database that allows main thread * access * @return The created WorkDatabase */ @JvmStatic fun create( context: Context, queryExecutor: Executor, useTestDatabase: Boolean ): WorkDatabase { val builder = if (useTestDatabase) { Room.inMemoryDatabaseBuilder(context, WorkDatabase::class.java) .allowMainThreadQueries() } else { Room.databaseBuilder(context, WorkDatabase::class.java, WORK_DATABASE_NAME) .openHelperFactory { configuration -> val configBuilder = SupportSQLiteOpenHelper.Configuration.builder(context) configBuilder.name(configuration.name) .callback(configuration.callback) .noBackupDirectory(true) .allowDataLossOnRecovery(true) FrameworkSQLiteOpenHelperFactory().create(configBuilder.build()) } } return builder.setQueryExecutor(queryExecutor) .addCallback(CleanupCallback) .addMigrations(Migration_1_2) .addMigrations(RescheduleMigration(context, VERSION_2, VERSION_3)) .addMigrations(Migration_3_4) .addMigrations(Migration_4_5) .addMigrations(RescheduleMigration(context, VERSION_5, VERSION_6)) .addMigrations(Migration_6_7) .addMigrations(Migration_7_8) .addMigrations(Migration_8_9) .addMigrations(WorkMigration9To10(context)) .addMigrations(RescheduleMigration(context, VERSION_10, VERSION_11)) .addMigrations(Migration_11_12) .addMigrations(Migration_12_13) .addMigrations(Migration_15_16) .fallbackToDestructiveMigration() .build() } } } // Delete rows in the workspec table that... private const val PRUNE_SQL_FORMAT_PREFIX = // are completed... "DELETE FROM workspec WHERE state IN $COMPLETED_STATES AND " + // and the minimum retention time has expired... "(last_enqueue_time + minimum_retention_duration) < " // and all dependents are completed. private const val PRUNE_SQL_FORMAT_SUFFIX = " AND " + "(SELECT COUNT(*)=0 FROM dependency WHERE " + " prerequisite_id=id AND " + " work_spec_id NOT IN " + " (SELECT id FROM workspec WHERE state IN $COMPLETED_STATES))" private val PRUNE_THRESHOLD_MILLIS = TimeUnit.DAYS.toMillis(1) internal object CleanupCallback : RoomDatabase.Callback() { private val pruneSQL: String get() = "$PRUNE_SQL_FORMAT_PREFIX$pruneDate$PRUNE_SQL_FORMAT_SUFFIX" val pruneDate: Long get() = System.currentTimeMillis() - PRUNE_THRESHOLD_MILLIS override fun onOpen(db: SupportSQLiteDatabase) { super.onOpen(db) db.beginTransaction() try { // Prune everything that is completed, has an expired retention time, and has no // active dependents: db.execSQL(pruneSQL) db.setTransactionSuccessful() } finally { db.endTransaction() } } }
apache-2.0
bdb4f1c8e2812e30118a5340aee604ea
37.020202
98
0.675345
4.612745
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/ui/dsl/gridLayout/GridLayout.kt
1
3229
// 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.ui.dsl.gridLayout import com.intellij.ui.dsl.UiDslException import com.intellij.ui.dsl.checkComponent import com.intellij.ui.dsl.checkConstraints import com.intellij.ui.dsl.gridLayout.impl.GridImpl import com.intellij.ui.dsl.gridLayout.impl.PreferredSizeData import org.jetbrains.annotations.ApiStatus import java.awt.* import javax.swing.JComponent /** * Layout manager represented as a table, where some cells can be merged in one cell (resulting cell occupies several columns and rows) * and every cell (or merged cells) can contain a sub-table inside. [Constraints] specifies all possible settings for every cell. * Root grid [rootGrid] and all sub-grids have own columns and rows settings placed in [Grid] */ @ApiStatus.Experimental class GridLayout : LayoutManager2 { /** * Root grid of layout */ val rootGrid: Grid get() = _rootGrid private val _rootGrid = GridImpl() override fun addLayoutComponent(comp: Component?, constraints: Any?) { val jbConstraints = checkConstraints(constraints) (jbConstraints.grid as GridImpl).register(checkComponent(comp), jbConstraints) } /** * Creates sub grid in the specified cell */ fun addLayoutSubGrid(constraints: Constraints): Grid { return (constraints.grid as GridImpl).registerSubGrid(constraints) } override fun addLayoutComponent(name: String?, comp: Component?) { throw UiDslException("Method addLayoutComponent(name: String?, comp: Component?) is not supported") } override fun removeLayoutComponent(comp: Component?) { if (!_rootGrid.unregister(checkComponent(comp))) { throw UiDslException("Component has not been registered: $comp") } } override fun preferredLayoutSize(parent: Container?): Dimension { if (parent == null) { throw UiDslException("Parent is null") } synchronized(parent.treeLock) { return getPreferredSizeData(parent).preferredSize } } override fun minimumLayoutSize(parent: Container?): Dimension { // May be we need to implement more accurate calculation later return preferredLayoutSize(parent) } override fun maximumLayoutSize(target: Container?) = Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE) override fun layoutContainer(parent: Container?) { if (parent == null) { throw UiDslException("Parent is null") } synchronized(parent.treeLock) { _rootGrid.layout(parent.width, parent.height, parent.insets) } } override fun getLayoutAlignmentX(target: Container?) = // Just like other layout managers, no special meaning here 0.5f override fun getLayoutAlignmentY(target: Container?) = // Just like other layout managers, no special meaning here 0.5f override fun invalidateLayout(target: Container?) { // Nothing to do } fun getConstraints(component: JComponent): Constraints? { return _rootGrid.getConstraints(component) } internal fun getPreferredSizeData(parent: Container): PreferredSizeData { return _rootGrid.getPreferredSizeData(parent.insets) } }
apache-2.0
43db7a4e79b388cf748e15537a695901
31.616162
158
0.73769
4.459945
false
false
false
false
smmribeiro/intellij-community
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/CaretBasedCellSelectionModel.kt
1
2084
package org.jetbrains.plugins.notebooks.visualization import com.intellij.openapi.editor.Caret import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.LogicalPosition import kotlin.math.min class CaretBasedCellSelectionModel(private val editor: Editor) : NotebookCellSelectionModel { override val primarySelectedCell: NotebookCellLines.Interval get() = editor.getCell(editor.caretModel.primaryCaret.logicalPosition.line) override val primarySelectedRegion: List<NotebookCellLines.Interval> get() { val primary = primarySelectedCell return selectedRegions.find { primary in it }!! } override val selectedRegions: List<List<NotebookCellLines.Interval>> get() = groupNeighborCells(selectedCells) override val selectedCells: List<NotebookCellLines.Interval> get() { val notebookCellLines = NotebookCellLines.get(editor) return editor.caretModel.allCarets.flatMap { caret -> notebookCellLines.getCells(editor.document.getSelectionLines(caret)) }.distinct() } override fun isSelectedCell(cell: NotebookCellLines.Interval): Boolean = editor.caretModel.allCarets.any { caret -> editor.document.getSelectionLines(caret).hasIntersectionWith(cell.lines) } override fun selectCell(cell: NotebookCellLines.Interval, makePrimary: Boolean) { editor.caretModel.addCaret(cell.startLogicalPosition, makePrimary) } override fun removeSecondarySelections() { editor.caretModel.removeSecondaryCarets() } override fun removeSelection(cell: NotebookCellLines.Interval) { for (caret in editor.caretModel.allCarets) { if (caret.logicalPosition.line in cell.lines) { editor.caretModel.removeCaret(caret) } } } } private fun Document.getSelectionLines(caret: Caret): IntRange = IntRange(getLineNumber(caret.selectionStart), getLineNumber(caret.selectionEnd)) private val NotebookCellLines.Interval.startLogicalPosition: LogicalPosition get() = LogicalPosition(min(firstContentLine, lines.last), 0)
apache-2.0
eb4df5ae43af545a02693cf1756381dd
36.232143
93
0.773992
4.672646
false
false
false
false
JetBrains/xodus
environment/src/main/kotlin/jetbrains/exodus/tree/patricia/MultiPageImmutableNode.kt
1
19175
/** * Copyright 2010 - 2022 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 * * 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 jetbrains.exodus.tree.patricia import jetbrains.exodus.ByteIterable import jetbrains.exodus.ExodusException import jetbrains.exodus.kotlin.notNull import jetbrains.exodus.log.* import jetbrains.exodus.log.Loggable.NULL_ADDRESS import java.util.* internal val Byte.unsigned: Int get() = this.toInt() and 0xff const val CHILDREN_BITSET_SIZE_LONGS = 4 const val CHILDREN_BITSET_SIZE_BYTES = CHILDREN_BITSET_SIZE_LONGS * Long.SIZE_BYTES /** * In V2 database format, a Patricia node with children can be encoded in 3 different ways depending * on number of children. Each of the ways is optimal for the number of children it represents. */ private enum class V2ChildrenFormat { Complete, // the node has all 256 children Sparse, // the number of children is in the range 1..32 Bitset // the number of children is in the range 33..255 } internal class MultiPageImmutableNode : NodeBase, ImmutableNode { private val loggable: RandomAccessLoggable private val log: Log private val data: ByteIterableWithAddress private val childrenCount: Short private val childAddressLength: Byte private val baseAddress: Long // if it is not equal to NULL_ADDRESS then the node is saved in the v2 format constructor(log: Log, loggable: RandomAccessLoggable, data: ByteIterableWithAddress) : this(log, loggable.type, loggable, data, data.iterator()) private constructor( log: Log, type: Byte, loggable: RandomAccessLoggable, data: ByteIterableWithAddress, it: ByteIteratorWithAddress ) : super(type, data, it) { this.log = log this.loggable = loggable var baseAddress = NULL_ADDRESS if (PatriciaTreeBase.nodeHasChildren(type)) { val i = it.compressedUnsignedInt val childrenCount = i ushr 3 if (childrenCount < VERSION2_CHILDREN_COUNT_BOUND) { this.childrenCount = childrenCount.toShort() } else { this.childrenCount = (childrenCount - VERSION2_CHILDREN_COUNT_BOUND).toShort() baseAddress = it.compressedUnsignedLong } checkAddressLength(((i and 7) + 1).also { len -> childAddressLength = len.toByte() }) } else { childrenCount = 0.toShort() childAddressLength = 0.toByte() } this.baseAddress = baseAddress this.data = data.cloneWithAddressAndLength(it.address, it.available()) } override fun getLoggable(): RandomAccessLoggable { return loggable } override fun getAddress() = loggable.address override fun asNodeBase(): NodeBase { return this } public override fun isMutable() = false public override fun getMutableCopy(mutableTree: PatriciaTreeMutable): MutableNode { return mutableTree.mutateNode(this) } public override fun getChild(tree: PatriciaTreeBase, b: Byte): NodeBase? { if (v2Format) { getV2Child(b)?.let { searchResult -> return tree.loadNode(addressByOffsetV2(searchResult.offset)) } } else { val key = b.unsigned var low = 0 var high = childrenCount - 1 while (low <= high) { val mid = low + high ushr 1 val offset = mid * (childAddressLength + 1) val cmp = byteAt(offset).unsigned - key when { cmp < 0 -> low = mid + 1 cmp > 0 -> high = mid - 1 else -> { return tree.loadNode(nextLong(offset + 1)) } } } } return null } public override fun getChildren(): NodeChildren { return object : NodeChildren { override fun iterator(): NodeChildrenIterator { val childrenCount = getChildrenCount() return if (childrenCount == 0) EmptyNodeChildrenIterator() else { if (v2Format) { when (childrenCount) { 256 -> ImmutableNodeCompleteChildrenV2Iterator(-1, null) in 1..32 -> ImmutableNodeSparseChildrenV2Iterator(-1, null) else -> ImmutableNodeBitsetChildrenV2Iterator(-1, null) } } else { ImmutableNodeChildrenIterator(-1, null) } } } } } public override fun getChildren(b: Byte): NodeChildrenIterator { if (v2Format) { getV2Child(b)?.let { searchResult -> val index = searchResult.index val node = ChildReference(b, addressByOffsetV2(searchResult.offset)) return when (searchResult.childrenFormat) { V2ChildrenFormat.Complete -> ImmutableNodeCompleteChildrenV2Iterator(index, node) V2ChildrenFormat.Sparse -> ImmutableNodeSparseChildrenV2Iterator(index, node) V2ChildrenFormat.Bitset -> ImmutableNodeBitsetChildrenV2Iterator(index, node) } } } else { val key = b.unsigned var low = 0 var high = childrenCount - 1 while (low <= high) { val mid = low + high ushr 1 val offset = mid * (childAddressLength + 1) val cmp = byteAt(offset).unsigned - key when { cmp < 0 -> low = mid + 1 cmp > 0 -> high = mid - 1 else -> { val suffixAddress = nextLong(offset + 1) return ImmutableNodeChildrenIterator(mid, ChildReference(b, suffixAddress)) } } } } return EmptyNodeChildrenIterator() } public override fun getChildrenRange(b: Byte): NodeChildrenIterator { val ub = b.unsigned if (v2Format) { when (val childrenCount = getChildrenCount()) { 0 -> return EmptyNodeChildrenIterator() 256 -> return ImmutableNodeCompleteChildrenV2Iterator( ub, ChildReference(b, addressByOffsetV2(ub * childAddressLength)) ) in 1..32 -> { for (i in 0 until childrenCount) { val nextByte = byteAt(i) val next = nextByte.unsigned if (ub <= next) { return ImmutableNodeSparseChildrenV2Iterator( i, ChildReference(nextByte, addressByOffsetV2(childrenCount + i * childAddressLength)) ) } } } else -> { val bitsetIdx = ub / Long.SIZE_BITS val bitset = data.nextLong(bitsetIdx * Long.SIZE_BYTES, Long.SIZE_BYTES) val bit = ub % Long.SIZE_BITS val bitmask = 1L shl bit var index = (bitset and (bitmask - 1L)).countOneBits() if (bitsetIdx > 0) { for (i in 0 until bitsetIdx) { index += data.nextLong(i * Long.SIZE_BYTES, Long.SIZE_BYTES).countOneBits() } } val offset = CHILDREN_BITSET_SIZE_BYTES + index * childAddressLength if ((bitset and bitmask) != 0L) { return ImmutableNodeBitsetChildrenV2Iterator( index, ChildReference(b, addressByOffsetV2(offset)) ) } if (index < childrenCount) { return ImmutableNodeBitsetChildrenV2Iterator( index - 1, ChildReference(b, addressByOffsetV2(offset)) ).apply { next() } } } } } else { var low = -1 var high = getChildrenCount() var offset = -1 var resultByte = 0.toByte() while (high - low > 1) { val mid = low + high + 1 ushr 1 val off = mid * (childAddressLength + 1) val actual = byteAt(off) if (actual.unsigned >= ub) { offset = off resultByte = actual high = mid } else { low = mid } } if (offset >= 0) { val suffixAddress = nextLong(offset + 1) return ImmutableNodeChildrenIterator(high, ChildReference(resultByte, suffixAddress)) } } return EmptyNodeChildrenIterator() } public override fun getChildrenCount() = childrenCount.toInt() public override fun getChildrenLast(): NodeChildrenIterator { val childrenCount = getChildrenCount() return if (childrenCount == 0) EmptyNodeChildrenIterator() else { if (v2Format) { when (childrenCount) { 256 -> ImmutableNodeCompleteChildrenV2Iterator(childrenCount, null) in 1..32 -> ImmutableNodeSparseChildrenV2Iterator(childrenCount, null) else -> ImmutableNodeBitsetChildrenV2Iterator(childrenCount, null) } } else { ImmutableNodeChildrenIterator(childrenCount, null) } } } private val v2Format: Boolean get() = baseAddress != NULL_ADDRESS // if specified byte is found the returns index of child, offset of suffixAddress and type of children format private fun getV2Child(b: Byte): SearchResult? { val ub = b.unsigned when (val childrenCount = getChildrenCount()) { 0 -> return null 256 -> return SearchResult( index = ub, offset = ub * childAddressLength, childrenFormat = V2ChildrenFormat.Complete ) in 1..32 -> { for (i in 0 until childrenCount) { val next = byteAt(i).unsigned if (ub < next) break if (ub == next) { return SearchResult( index = i, offset = childrenCount + i * childAddressLength, childrenFormat = V2ChildrenFormat.Sparse ) } } } else -> { val bitsetIdx = ub / Long.SIZE_BITS val bitset = data.nextLong(bitsetIdx * Long.SIZE_BYTES, Long.SIZE_BYTES) val bit = ub % Long.SIZE_BITS val bitmask = 1L shl bit if ((bitset and bitmask) == 0L) return null var index = (bitset and (bitmask - 1L)).countOneBits() if (bitsetIdx > 0) { for (i in 0 until bitsetIdx) { index += data.nextLong(i * Long.SIZE_BYTES, Long.SIZE_BYTES).countOneBits() } } return SearchResult( index = index, offset = CHILDREN_BITSET_SIZE_BYTES + index * childAddressLength, childrenFormat = V2ChildrenFormat.Bitset ) } } return null } private fun byteAt(offset: Int): Byte { return data.byteAt(offset) } private fun nextLong(offset: Int): Long { return data.nextLong(offset, childAddressLength.toInt()) } private fun addressByOffsetV2(offset: Int) = nextLong(offset) + baseAddress private fun childReferenceV1(index: Int) = (index * (childAddressLength + 1)).let { offset -> ChildReference(byteAt(offset), nextLong(offset + 1)) } // get child reference in case of v2 format with complete children (the node has all 256 children) private fun childReferenceCompleteV2(index: Int) = ChildReference(index.toByte(), addressByOffsetV2(index * childAddressLength)) // get child reference in case of v2 format with sparse children (the number of children is in the range 1..32) private fun childReferenceSparseV2(index: Int) = ChildReference(byteAt(index), addressByOffsetV2(getChildrenCount() + index * childAddressLength)) // get child reference in case of v2 format with bitset children representation // (the number of children is in the range 33..255) private fun childReferenceBitsetV2(index: Int, bit: Int) = ChildReference(bit.toByte(), addressByOffsetV2(CHILDREN_BITSET_SIZE_BYTES + index * childAddressLength)) private fun fillChildReferenceV1(index: Int, node: ChildReference) = (index * (childAddressLength + 1)).let { offset -> node.firstByte = byteAt(offset) node.suffixAddress = nextLong(offset + 1) } private fun fillChildReferenceCompleteV2(index: Int, node: ChildReference) { node.firstByte = index.toByte() node.suffixAddress = addressByOffsetV2(index * childAddressLength) } private fun fillChildReferenceSparseV2(index: Int, node: ChildReference) { node.firstByte = byteAt(index) node.suffixAddress = addressByOffsetV2(getChildrenCount() + index * childAddressLength) } private fun fillChildReferenceBitsetV2(index: Int, bit: Int, node: ChildReference) { node.firstByte = bit.toByte() node.suffixAddress = addressByOffsetV2(CHILDREN_BITSET_SIZE_BYTES + index * childAddressLength) } private abstract inner class NodeChildrenIteratorBase(override var index: Int, override var node: ChildReference?) : NodeChildrenIterator { override val isMutable: Boolean get() = false override fun hasNext() = index < childrenCount - 1 override fun hasPrev() = index > 0 override fun remove() = throw ExodusException("Can't remove manually Patricia node child, use Store.delete() instead") override val parentNode: NodeBase get() = this@MultiPageImmutableNode override val key: ByteIterable get() = keySequence } private inner class ImmutableNodeChildrenIterator(index: Int, node: ChildReference?) : NodeChildrenIteratorBase(index, node) { override fun next(): ChildReference = childReferenceV1(++index).also { node = it } override fun prev(): ChildReference = childReferenceV1(--index).also { node = it } override fun nextInPlace() = fillChildReferenceV1(++index, node.notNull) override fun prevInPlace() = fillChildReferenceV1(--index, node.notNull) } // v2 format complete children (the node has all 256 children) private inner class ImmutableNodeCompleteChildrenV2Iterator(index: Int, node: ChildReference?) : NodeChildrenIteratorBase(index, node) { override fun next() = childReferenceCompleteV2(++index).also { node = it } override fun prev() = childReferenceCompleteV2(--index).also { node = it } override fun nextInPlace() = fillChildReferenceCompleteV2(++index, node.notNull) override fun prevInPlace() = fillChildReferenceCompleteV2(--index, node.notNull) } // v2 format sparse children (the number of children is in the range 1..32) private inner class ImmutableNodeSparseChildrenV2Iterator(index: Int, node: ChildReference?) : NodeChildrenIteratorBase(index, node) { override fun next() = childReferenceSparseV2(++index).also { node = it } override fun prev() = childReferenceSparseV2(--index).also { node = it } override fun nextInPlace() = fillChildReferenceSparseV2(++index, node.notNull) override fun prevInPlace() = fillChildReferenceSparseV2(--index, node.notNull) } // v2 format bitset children (the number of children is in the range 33..255) private inner class ImmutableNodeBitsetChildrenV2Iterator(index: Int, node: ChildReference?) : NodeChildrenIteratorBase(index, node) { private val bitset = LongArray(CHILDREN_BITSET_SIZE_LONGS).let { array -> array.indices.forEach { i -> array[i] = data.nextLong(i * Long.SIZE_BYTES, Long.SIZE_BYTES) } BitSet.valueOf(array) } private var bit = -1 override fun next(): ChildReference { incIndex() return childReferenceBitsetV2(index, bit).also { node = it } } override fun prev(): ChildReference { decIndex() return childReferenceBitsetV2(index, bit).also { node = it } } override fun nextInPlace() { incIndex() fillChildReferenceBitsetV2(index, bit, node.notNull) } override fun prevInPlace() { decIndex() fillChildReferenceBitsetV2(index, bit, node.notNull) } private fun incIndex() { ++index if (bit < 0) { for (i in 0..index) { bit = bitset.nextSetBit(bit + 1) } } else { bit = bitset.nextSetBit(bit + 1) } if (bit < 0) { throw ExodusException("Inconsistent children bitset in Patricia node") } } private fun decIndex() { --index if (bit < 0) { bit = 256 for (i in index until getChildrenCount()) { bit = bitset.previousSetBit(bit - 1) } } else { if (bit == 0) { throw ExodusException("Inconsistent children bitset in Patricia node") } bit = bitset.previousSetBit(bit - 1) } if (bit < 0) { throw ExodusException("Inconsistent children bitset in Patricia node") } } } } private data class SearchResult(val index: Int, val offset: Int, val childrenFormat: V2ChildrenFormat) private fun checkAddressLength(addressLen: Int) { if (addressLen < 0 || addressLen > 8) { throw ExodusException("Invalid length of address: $addressLen") } }
apache-2.0
14b863533b426278a4762d58f9b1f8e4
37.581489
120
0.567927
5.26641
false
false
false
false
itachi1706/DroidEggs
app/src/main/java/com/itachi1706/droideggs/PieEgg/EasterEgg/paint/CutoutAvoidingToolbar.kt
1
3030
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.itachi1706.droideggs.PieEgg.EasterEgg.paint import android.content.Context import android.os.Build import android.util.AttributeSet import android.view.View import android.view.ViewGroup.LayoutParams.MATCH_PARENT import android.view.WindowInsets import android.widget.LinearLayout import androidx.annotation.RequiresApi @RequiresApi(24) class CutoutAvoidingToolbar : LinearLayout { private var _insets: WindowInsets? = null constructor(context: Context) : super(context) { init(null, 0) } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init(attrs, 0) } constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) { init(attrs, defStyle) } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) adjustLayout() } override fun onApplyWindowInsets(insets: WindowInsets?): WindowInsets { _insets = insets if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) adjustLayout() return super.onApplyWindowInsets(insets) } @RequiresApi(28) fun adjustLayout() { _insets?.displayCutout?.boundingRects?.let { var cutoutCenter = 0 var cutoutLeft = 0 var cutoutRight = 0 // collect at most three cutouts for (r in it) { if (r.top > 0) continue if (r.left == left) { cutoutLeft = r.width() } else if (r.right == right) { cutoutRight = r.width() } else { cutoutCenter = r.width() } } // apply to layout (findViewWithTag("cutoutLeft") as View?)?.let { it.layoutParams = LayoutParams(cutoutLeft, MATCH_PARENT) } (findViewWithTag("cutoutCenter") as View?)?.let { it.layoutParams = LayoutParams(cutoutCenter, MATCH_PARENT) } (findViewWithTag("cutoutRight") as View?)?.let { it.layoutParams = LayoutParams(cutoutRight, MATCH_PARENT) } requestLayout() } } @Suppress("UNUSED_PARAMETER") private fun init(attrs: AttributeSet?, defStyle: Int) { } }
apache-2.0
f206153aa16f24f07711736bbf76ebb7
35.963415
105
0.627393
4.397678
false
false
false
false
siosio/intellij-community
plugins/markdown/src/org/intellij/plugins/markdown/editor/lists/ListItemIndentUnindentHandlerBase.kt
1
3534
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.editor.lists import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Caret import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.actionSystem.EditorActionHandler import com.intellij.openapi.editor.actionSystem.EditorWriteActionHandler import com.intellij.psi.PsiDocumentManager import com.intellij.refactoring.suggested.endOffset import org.intellij.plugins.markdown.editor.lists.ListUtils.getListItemAtLine import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile import org.intellij.plugins.markdown.lang.psi.impl.MarkdownListItemImpl /** * This is a base class for classes, handling indenting/unindenting of list items. * It collects selected items (or the ones the carets are inside) and calls [doIndentUnindent] and [updateNumbering] on them one by one. */ internal abstract class ListItemIndentUnindentHandlerBase(private val baseHandler: EditorActionHandler?) : EditorWriteActionHandler.ForEachCaret() { override fun isEnabledForCaret(editor: Editor, caret: Caret, dataContext: DataContext?): Boolean = baseHandler?.isEnabled(editor, caret, dataContext) == true override fun executeWriteAction(editor: Editor, caret: Caret?, dataContext: DataContext?) { if (caret == null || !doExecuteAction(editor, caret)) { baseHandler?.execute(editor, caret, dataContext) } } private fun doExecuteAction(editor: Editor, caret: Caret): Boolean { val project = editor.project ?: return false val psiDocumentManager = PsiDocumentManager.getInstance(project) val document = editor.document val file = psiDocumentManager.getPsiFile(document) as? MarkdownFile ?: return false val firstLinesOfSelectedItems = getFirstLinesOfSelectedItems(caret, document, file) // use lines instead of items, because items may become invalid before used for (line in firstLinesOfSelectedItems) { psiDocumentManager.commitDocument(document) val item = file.getListItemAtLine(line, document)!! if (!doIndentUnindent(item, file, document)) continue psiDocumentManager.commitDocument(document) run { @Suppress("name_shadowing") // item is not valid anymore, but line didn't change val item = file.getListItemAtLine(line, document)!! updateNumbering(item, file, document) } } return firstLinesOfSelectedItems.isNotEmpty() } private fun getFirstLinesOfSelectedItems(caret: Caret, document: Document, file: MarkdownFile): List<Int> { var line = document.getLineNumber(caret.selectionStart) val lastLine = if (caret.hasSelection()) document.getLineNumber(caret.selectionEnd - 1) else line val lines = mutableListOf<Int>() while (line <= lastLine) { val item = file.getListItemAtLine(line, document) if (item == null) { line++ continue } lines.add(line) line = document.getLineNumber(item.endOffset) + 1 } return lines } /** If this method returns `true`, then the document is committed and [updateNumbering] is called */ protected abstract fun doIndentUnindent(item: MarkdownListItemImpl, file: MarkdownFile, document: Document): Boolean protected abstract fun updateNumbering(item: MarkdownListItemImpl, file: MarkdownFile, document: Document) }
apache-2.0
5e86935e7e4b872b042075bb0fde9ef0
43.734177
158
0.758347
4.718291
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertEnumToSealedClassIntention.kt
2
5774
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.codeStyle.CodeStyleManager import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.getOrCreateCompanionObject import org.jetbrains.kotlin.idea.project.platform import org.jetbrains.kotlin.idea.refactoring.withExpectedActuals import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.allChildren import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.siblings import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe class ConvertEnumToSealedClassIntention : SelfTargetingRangeIntention<KtClass>( KtClass::class.java, KotlinBundle.lazyMessage("convert.to.sealed.class") ) { override fun applicabilityRange(element: KtClass): TextRange? { if (element.getClassKeyword() == null) return null val nameIdentifier = element.nameIdentifier ?: return null val enumKeyword = element.modifierList?.getModifier(KtTokens.ENUM_KEYWORD) ?: return null return TextRange(enumKeyword.startOffset, nameIdentifier.endOffset) } override fun applyTo(element: KtClass, editor: Editor?) { val name = element.name ?: return if (name.isEmpty()) return for (klass in element.withExpectedActuals()) { klass as? KtClass ?: continue val classDescriptor = klass.resolveToDescriptorIfAny() ?: continue val isExpect = classDescriptor.isExpect val isActual = classDescriptor.isActual klass.removeModifier(KtTokens.ENUM_KEYWORD) klass.addModifier(KtTokens.SEALED_KEYWORD) val psiFactory = KtPsiFactory(klass) val objects = mutableListOf<KtObjectDeclaration>() for (member in klass.declarations) { if (member !is KtEnumEntry) continue val obj = psiFactory.createDeclaration<KtObjectDeclaration>("object ${member.name}") val initializers = member.initializerList?.initializers ?: emptyList() if (initializers.isNotEmpty()) { initializers.forEach { obj.addSuperTypeListEntry(psiFactory.createSuperTypeCallEntry("${klass.name}${it.text}")) } } else { val defaultEntry = if (isExpect) psiFactory.createSuperTypeEntry(name) else psiFactory.createSuperTypeCallEntry("$name()") obj.addSuperTypeListEntry(defaultEntry) } if (isActual) { obj.addModifier(KtTokens.ACTUAL_KEYWORD) } member.body?.let { body -> obj.add(body) } member.delete() klass.addDeclaration(obj) objects.add(obj) } if (element.platform.isJvm()) { val enumEntryNames = objects.map { it.nameAsSafeName.asString() } val targetClassName = klass.name if (enumEntryNames.isNotEmpty() && targetClassName != null) { val companionObject = klass.getOrCreateCompanionObject() companionObject.addValuesFunction(targetClassName, enumEntryNames, psiFactory) companionObject.addValueOfFunction(targetClassName, classDescriptor, enumEntryNames, psiFactory) } } klass.body?.let { body -> body.allChildren .takeWhile { it !is KtDeclaration } .firstOrNull { it.node.elementType == KtTokens.SEMICOLON } ?.let { semicolon -> val nonWhiteSibling = semicolon.siblings(forward = true, withItself = false).firstOrNull { it !is PsiWhiteSpace } body.deleteChildRange(semicolon, nonWhiteSibling?.prevSibling ?: semicolon) if (nonWhiteSibling != null) { CodeStyleManager.getInstance(klass.project).reformat(nonWhiteSibling.firstChild ?: nonWhiteSibling) } } } } } private fun KtObjectDeclaration.addValuesFunction(targetClassName: String, enumEntryNames: List<String>, psiFactory: KtPsiFactory) { val functionText = "fun values(): Array<${targetClassName}> { return arrayOf(${enumEntryNames.joinToString()}) }" addDeclaration(psiFactory.createFunction(functionText)) } private fun KtObjectDeclaration.addValueOfFunction( targetClassName: String, classDescriptor: ClassDescriptor, enumEntryNames: List<String>, psiFactory: KtPsiFactory ) { val classFqName = classDescriptor.fqNameSafe.asString() val functionText = buildString { append("fun valueOf(value: String): $targetClassName {") append("return when(value) {") enumEntryNames.forEach { append("\"$it\" -> $it\n") } append("else -> throw IllegalArgumentException(\"No object $classFqName.\$value\")") append("}") append("}") } addDeclaration(psiFactory.createFunction(functionText)) } }
apache-2.0
6f1bcb24e2f995bbb69e4f9c0d297e2f
44.464567
158
0.64877
5.557267
false
false
false
false
kivensolo/UiUsingListView
base/src/main/java/com/kingz/base/BaseLazyFragment.kt
1
3810
package com.kingz.base import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import com.zeke.kangaroo.utils.ZLog /** * 实现Fragment懒加载控制的Base类,支持复杂的 Fragment 嵌套组合。 * 比如 Fragment+Fragment、Fragment+ViewPager、ViewPager+ViewPager….等等。 * * Fragment 完整生命周期: * onAttach -> onCreate -> * onCreatedView -> onActivityCreated -> onStart -> onResume * -> onPause -> onStop -> onDestroyView -> onDestroy -> onDetach * */ abstract class BaseLazyFragment : Fragment() { /** * 当使用ViewPager+Fragment形式时,setUserVisibleHint会优先Fragment生命周期函数调用, * 所以这个时候就,会导致在setUserVisibleHint方法执行时就执行了懒加载, * 而不是在onResume方法实际调用的时候执行懒加载。所以需要这个变量进行控制 */ private var isActive = false /** * 是否对用户可见,即是否调用了setUserVisibleHint(boolean)方法 */ private var isVisibleToUser = false /** * 是否调用了setUserVisibleHint方法。 * 处理show+add+hide模式下,默认可见Fragment不调用 * onHiddenChanged方法,进而不执行懒加载方法的问题。 */ private var isCallUserVisibleHint = false /** * 是否已执行懒加载 */ private var isLoaded = false /** * 进行页面懒加载 */ abstract fun lazyInit() override fun onPause() { super.onPause() isActive = false } override fun onResume() { super.onResume() isActive = true if(!isCallUserVisibleHint) isVisibleToUser = !isHidden tryLazyInit() } /** * androidX版本推荐使用 FragmentTransaction#setMaxLifecycle(Fragment, Lifecycle.State)代替 */ override fun setUserVisibleHint(isVisibleToUser: Boolean) { super.setUserVisibleHint(isVisibleToUser) this.isVisibleToUser = isVisibleToUser isCallUserVisibleHint = true tryLazyInit() } /** * 当 Fragment隐藏的状态发生改变时,该函数将会被调用. * 隐藏:hidden为true * 显示:hidden为false */ override fun onHiddenChanged(hidden: Boolean) { super.onHiddenChanged(hidden) isVisibleToUser = !hidden tryLazyInit() } /** * 尝试进行懒加载初始化 */ private fun tryLazyInit(){ // if(!isLoaded && isVisibleToUser && isParentVisible() && isActive){ if(!isLoaded && isVisibleToUser && isActive){ ZLog.d("lazyInit:!!!") lazyInit() isLoaded = true //通知子Fragment进行懒加载 dispatchParentVisibleState() } } /** * ViewPager场景下,判断父fragment是否可见 */ private fun isParentVisible(): Boolean { val fragment = parentFragment return fragment == null || (fragment is BaseLazyFragment && fragment.isVisibleToUser) } /** * ViewPager嵌套场景下,当前fragment可见时, * 如果其子fragment也可见,则让子fragment请求数据 */ private fun dispatchParentVisibleState() { val fragmentManager: FragmentManager = childFragmentManager val fragments: List<Fragment> = fragmentManager.fragments if (fragments.isEmpty()) { return } for (child in fragments) { if (child is BaseLazyFragment && child.isVisibleToUser) { child.tryLazyInit() } } } override fun onDestroyView() { super.onDestroyView() isLoaded = false isActive = false isVisibleToUser = false isCallUserVisibleHint = false } }
gpl-2.0
cd6211ebb1ede05839242c8ed9c74197
24.771654
93
0.628667
4.469945
false
false
false
false
googlecodelabs/firebase-iap-optimization
app/app/src/main/java/org/tensorflow/lite/examples/iapoptimizer/IapOptimizer.kt
1
5320
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.tensorflow.lite.examples.iapoptimizer import android.content.Context import android.util.Log import com.google.android.gms.tasks.Task import com.google.android.gms.tasks.Tasks.call import com.google.firebase.analytics.FirebaseAnalytics import org.json.JSONObject import org.tensorflow.lite.Interpreter import org.tensorflow.lite.support.metadata.MetadataExtractor import java.io.File import java.io.RandomAccessFile import java.nio.ByteBuffer import java.nio.channels.FileChannel import java.util.concurrent.Callable import java.util.concurrent.ExecutorService import java.util.concurrent.Executors class IapOptimizer(private val context: Context) { val testInput = mapOf( "coins_spent" to 2048f, "distance_avg" to 1234f, "device_os" to "ANDROID", "game_day" to 10f, "geo_country" to "Canada", "last_run_end_reason" to "laser" ) private var interpreter: Interpreter? = null private var preprocessingSummary : JSONObject? = null var isInitialized = false private set /** Executor to run inference task in the background */ private val executorService: ExecutorService = Executors.newCachedThreadPool() private var modelInputSize: Int = 0 // will be inferred from TF Lite model fun initialize(model: File): Task<Void> { return call( executorService, Callable<Void> { initializeInterpreter(model) null } ) } private fun initializeInterpreter(model: File) { // Initialize TF Lite Interpreter with NNAPI enabled val options = Interpreter.Options() options.setUseNNAPI(true) val interpreter: Interpreter interpreter = Interpreter(model, options) val aFile = RandomAccessFile(model, "r") val inChannel: FileChannel = aFile.getChannel() val fileSize: Long = inChannel.size() val buffer = ByteBuffer.allocate(fileSize.toInt()) inChannel.read(buffer) buffer.flip() val metaExecutor = MetadataExtractor(buffer) // Get associated preprocessing metadata JSON file from the TFLite file. // This is not yet supported on TFLite's iOS library, // consider bundling this file separately instead. val inputStream = metaExecutor.getAssociatedFile("preprocess.json") val inputAsString = inputStream.bufferedReader().use { it.readText() } preprocessingSummary = JSONObject(inputAsString) // Read input shape from model file val inputShape = interpreter.getInputTensor(0).shape() modelInputSize = inputShape[1] // Finish interpreter initialization this.interpreter = interpreter isInitialized = true Log.d(TAG, "Initialized TFLite interpreter.") } fun predict(): String { if (!isInitialized) { throw IllegalStateException("TF Lite Interpreter is not initialized yet.") } val preprocessedInput = preprocessModelInput(testInput) val byteBuffer = Array(1) { preprocessedInput } val result = Array(1) { FloatArray(OUTPUT_ACTIONS_COUNT) } interpreter?.run(byteBuffer, result) return mapOutputToAction(result[0]) } private fun preprocessModelInput(input : Map<String, Any>) : FloatArray { val result = mutableListOf<Float>() for ((k, v) in input) { if(!preprocessingSummary!!.has(k)) { continue } val channelSummary = preprocessingSummary!!.getJSONObject(k) if (channelSummary.getString("type") == "numerical") { val mean =channelSummary.getDouble("mean") val std =channelSummary.getDouble("std") if (v is Float) { result.add((v - mean.toFloat())/std.toFloat()) } else { throw Exception("Invalid input") } } if (channelSummary.getString("type") == "categorical") { val allValues = channelSummary.getJSONArray("all_values") for (i in 0 until allValues.length()) { val possibleValue = allValues.getString(i) if (v == possibleValue) { result.add(1f) } else { result.add(0f) } } } } return result.toFloatArray() } private fun mapOutputToAction(output: FloatArray) : String { val mapping = preprocessingSummary!!.getJSONArray("output_mapping") val maxIndex = output.indexOf(output.max()!!) return mapping[maxIndex] as String } fun close() { call( executorService, Callable<String> { interpreter?.close() Log.d(TAG, "Closed TFLite interpreter.") null } ) } companion object { private const val TAG = "IapOptimizer" private const val OUTPUT_ACTIONS_COUNT = 8 } }
apache-2.0
2f85c5bda2ebec0cad5f4c570e0003ae
29.751445
80
0.673872
4.451883
false
false
false
false
alisle/Penella
src/main/java/org/penella/index/IndexVertical.kt
1
2896
package org.penella.index import io.vertx.core.AbstractVerticle import io.vertx.core.Future import io.vertx.core.Handler import io.vertx.core.Vertx import io.vertx.core.eventbus.Message import org.penella.MailBoxes import org.penella.codecs.IndexAddCodec import org.penella.codecs.IndexGetFirstLayerCodec import org.penella.codecs.IndexGetSecondLayerCodec import org.penella.codecs.IndexResultSetCodec import org.penella.messages.* /** * 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. * * Created by alisle on 1/25/17. */ class IndexVertical(val name: String, val index: IIndex) : AbstractVerticle() { companion object { fun registerCodecs(vertx: Vertx) { vertx.eventBus().registerDefaultCodec(IndexAdd::class.java, IndexAddCodec()) vertx.eventBus().registerDefaultCodec(IndexGetFirstLayer::class.java, IndexGetFirstLayerCodec()) vertx.eventBus().registerDefaultCodec(IndexGetSecondLayer::class.java, IndexGetSecondLayerCodec()) vertx.eventBus().registerDefaultCodec(IndexResultSet::class.java, IndexResultSetCodec()) } } private val addTripleHandler = Handler<Message<IndexAdd>> { msg -> val triple = msg.body().triple index.add(triple) msg.reply(StatusMessage(Status.SUCESSFUL, "OK")) } private val getFirstLayerHandler = Handler<Message<IndexGetFirstLayer>> { msg -> val first = msg.body().first val type = msg.body().type val results = index.get(type, first) msg.reply(results) } private val getSecondLayerHandler = Handler<Message<IndexGetSecondLayer>> { msg -> val firstType = msg.body().firstType val firstValue = msg.body().firstValue val secondType = msg.body().secondType val secondValue = msg.body().secondValue val results = index.get(firstType, secondType, firstValue, secondValue) msg.reply(results) } override fun start(startFuture: Future<Void>?) { vertx.eventBus().consumer<IndexAdd>(MailBoxes.INDEX_ADD_TRIPLE.mailbox + name).handler(addTripleHandler) vertx.eventBus().consumer<IndexGetFirstLayer>(MailBoxes.INDEX_GET_FIRST.mailbox + name).handler(getFirstLayerHandler) vertx.eventBus().consumer<IndexGetSecondLayer>(MailBoxes.INDEX_GET_SECOND.mailbox + name).handler(getSecondLayerHandler) startFuture?.complete() } }
apache-2.0
6fdc5d9bbffd7d37fd63196fbc78e2d7
37.118421
128
0.722376
4.348348
false
false
false
false
dowenliu-xyz/ketcd
ketcd-core/src/test/kotlin/xyz/dowenliu/ketcd/client/EtcdMaintenanceServiceImplTest.kt
1
6629
package xyz.dowenliu.ketcd.client import org.slf4j.Logger import org.slf4j.LoggerFactory import org.testng.annotations.AfterClass import org.testng.annotations.BeforeClass import org.testng.annotations.Test import org.testng.asserts.Assertion import xyz.dowenliu.ketcd.Endpoint import xyz.dowenliu.ketcd.api.AlarmResponse import xyz.dowenliu.ketcd.api.DefragmentResponse import xyz.dowenliu.ketcd.api.StatusResponse import xyz.dowenliu.ketcd.endpoints import xyz.dowenliu.ketcd.version.EtcdVersion import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicReference /** * create at 2017/4/14 * @author liufl * @since 0.1.0 */ class EtcdMaintenanceServiceImplTest { private val logger: Logger = LoggerFactory.getLogger(javaClass) private val assertion = Assertion() private val etcdClient = EtcdClient.newBuilder() .withEndpoint(*endpoints.map { Endpoint.of(it) }.toTypedArray()) .build() private val service = etcdClient.newMaintenanceService() @BeforeClass fun assertIsImpl() { assertion.assertTrue(service is EtcdMaintenanceServiceImpl) } @AfterClass fun closeImpl() { service as EtcdMaintenanceServiceImpl service.close() } @Test fun testListAlarms() { val response = service.listAlarms() assertion.assertNotNull(response.header) } @Test fun testListAlarmsFuture() { val response = service.listAlarmsInFuture().get(5, TimeUnit.SECONDS) assertion.assertNotNull(response.header) } @Test fun testListAlarmsAsync() { val responseRef = AtomicReference<AlarmResponse?>() val errorRef = AtomicReference<Throwable?>() val finishLatch = CountDownLatch(1) service.listAlarmsAsync(object : ResponseCallback<AlarmResponse> { override fun onResponse(response: AlarmResponse) { responseRef.set(response) logger.debug("Alarm response received.") } override fun onError(throwable: Throwable) { errorRef.set(throwable) } override fun completeCallback() { logger.debug("Asynchronous listing alarms complete.") finishLatch.countDown() } }) finishLatch.await(10, TimeUnit.SECONDS) val response = responseRef.get() val throwable = errorRef.get() assertion.assertTrue(response != null || throwable != null) if (response != null) { assertion.assertNotNull(response.header) } else { throw throwable!! } } @Test(enabled = false) fun testDeactiveAlarm() { // TEST_THIS how to test deactiveAlarm()? } @Test(enabled = false) fun testDeactiveAlarmFuture() { // TEST_THIS how to test deactiveAlarmInFuture()? } @Test(enabled = false) fun testDeactiveAlarmAsync() { // TEST_THIS how to test deactiveAlarmAsync()? } @Test fun testDefragmentMember() { val response = service.defragmentMember() assertion.assertNotNull(response.header) } @Test fun testDefragmentMemberFuture() { val response = service.defragmentMemberInFuture().get(5, TimeUnit.SECONDS) assertion.assertNotNull(response.header) } @Test fun testDefragmentMemberAsync() { val responseRef = AtomicReference<DefragmentResponse?>() val errorRef = AtomicReference<Throwable?>() val finishLatch = CountDownLatch(1) service.defragmentMemberAsync(object : ResponseCallback<DefragmentResponse> { override fun onResponse(response: DefragmentResponse) { responseRef.set(response) logger.debug("Defragment response received.") } override fun onError(throwable: Throwable) { errorRef.set(throwable) } override fun completeCallback() { logger.debug("Asynchronous member defragmentation complete.") finishLatch.countDown() } }) finishLatch.await(10, TimeUnit.SECONDS) val response = responseRef.get() val throwable = errorRef.get() assertion.assertTrue(response != null || throwable != null) if (response != null) { assertion.assertNotNull(response.header) } else { throw throwable!! } } @Test(groups = arrayOf("Maintenance.status")) fun testStatusMember() { val response = service.statusMember() assertion.assertNotNull(response.header) val version = response.version logger.info(version) assertion.assertTrue(version.startsWith("3.")) assertion.assertNotNull(EtcdVersion.ofValue(version)) } @Test(groups = arrayOf("Maintenance.status")) fun testStatusMemberFuture() { val response = service.statusMemberInFuture().get(5, TimeUnit.SECONDS) assertion.assertNotNull(response.header) val version = response.version logger.info(version) assertion.assertTrue(version.startsWith("3.")) assertion.assertNotNull(EtcdVersion.ofValue(version)) } @Test(groups = arrayOf("Maintenance.status")) fun testStatusMemberAsync() { val responseRef = AtomicReference<StatusResponse?>() val errorRef = AtomicReference<Throwable?>() val finishLatch = CountDownLatch(1) service.statusMemberAsync(object : ResponseCallback<StatusResponse> { override fun onResponse(response: StatusResponse) { responseRef.set(response) logger.debug("Status response received.") } override fun onError(throwable: Throwable) { errorRef.set(throwable) } override fun completeCallback() { logger.debug("Asynchronous member status complete.") finishLatch.countDown() } }) finishLatch.await(10, TimeUnit.SECONDS) val response = responseRef.get() val throwable = errorRef.get() assertion.assertTrue(response != null || throwable != null) if (response != null) { assertion.assertNotNull(response.header) val version = response.version logger.info(version) assertion.assertTrue(version.startsWith("3.")) assertion.assertNotNull(EtcdVersion.ofValue(version)) } else { throw throwable!! } } }
apache-2.0
055e4c1ae3869d581360238ba6b6722c
32.484848
85
0.639463
4.965543
false
true
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/collections/FunctionUtils.kt
4
5573
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections.collections import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.builtins.getFunctionalClassKind import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.calls.inference.model.TypeVariableTypeConstructor import org.jetbrains.kotlin.resolve.calls.model.ReceiverKotlinCallArgument import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.calls.model.ResolvedLambdaAtom import org.jetbrains.kotlin.resolve.calls.model.unwrap import org.jetbrains.kotlin.resolve.calls.util.getImplicitReceiverValue import org.jetbrains.kotlin.resolve.calls.tower.NewResolvedCallImpl import org.jetbrains.kotlin.resolve.calls.tower.SubKotlinCallArgumentImpl import org.jetbrains.kotlin.resolve.calls.tower.receiverValue import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.descriptorUtil.isSubclassOf import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.utils.addToStdlib.safeAs fun KotlinType.isFunctionOfAnyKind() = constructor.declarationDescriptor?.getFunctionalClassKind() != null fun KotlinType?.isMap(builtIns: KotlinBuiltIns): Boolean { val classDescriptor = this?.constructor?.declarationDescriptor as? ClassDescriptor ?: return false return classDescriptor.name.asString().endsWith("Map") && classDescriptor.isSubclassOf(builtIns.map) } fun KotlinType?.isIterable(builtIns: KotlinBuiltIns): Boolean { val classDescriptor = this?.constructor?.declarationDescriptor as? ClassDescriptor ?: return false return classDescriptor.isListOrSet(builtIns) || classDescriptor.isSubclassOf(builtIns.iterable) } fun KotlinType?.isCollection(builtIns: KotlinBuiltIns): Boolean { val classDescriptor = this?.constructor?.declarationDescriptor as? ClassDescriptor ?: return false return classDescriptor.isListOrSet(builtIns) || classDescriptor.isSubclassOf(builtIns.collection) } private fun ClassDescriptor.isListOrSet(builtIns: KotlinBuiltIns): Boolean { val className = name.asString() return className.endsWith("List") && isSubclassOf(builtIns.list) || className.endsWith("Set") && isSubclassOf(builtIns.set) } fun KtCallExpression.isCalling(fqName: FqName, context: BindingContext? = null): Boolean { return isCalling(listOf(fqName), context) } fun KtCallExpression.isCalling(fqNames: List<FqName>, context: BindingContext? = null): Boolean { val calleeText = calleeExpression?.text ?: return false val targetFqNames = fqNames.filter { it.shortName().asString() == calleeText } if (targetFqNames.isEmpty()) return false val resolvedCall = getResolvedCall(context ?: safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)) ?: return false return targetFqNames.any { resolvedCall.isCalling(it) } } fun ResolvedCall<out CallableDescriptor>.isCalling(fqName: FqName): Boolean { return resultingDescriptor.fqNameSafe == fqName } fun ResolvedCall<*>.hasLastFunctionalParameterWithResult(context: BindingContext, predicate: (KotlinType) -> Boolean): Boolean { val lastParameter = resultingDescriptor.valueParameters.lastOrNull() ?: return false val lastArgument = valueArguments[lastParameter]?.arguments?.singleOrNull() ?: return false if (this is NewResolvedCallImpl<*>) { // TODO: looks like hack resolvedCallAtom.subResolvedAtoms?.firstOrNull { it is ResolvedLambdaAtom }.safeAs<ResolvedLambdaAtom>()?.let { lambdaAtom -> return lambdaAtom.unwrap().resultArgumentsInfo!!.nonErrorArguments.filterIsInstance<ReceiverKotlinCallArgument>().all { val type = it.receiverValue?.type?.let { type -> if (type.constructor is TypeVariableTypeConstructor) { it.safeAs<SubKotlinCallArgumentImpl>()?.valueArgument?.getArgumentExpression()?.getType(context) ?: type } else { type } } ?: return@all false predicate(type) } } } val functionalType = lastArgument.getArgumentExpression()?.getType(context) ?: return false // Both Function & KFunction must pass here if (!functionalType.isFunctionOfAnyKind()) return false val resultType = functionalType.arguments.lastOrNull()?.type ?: return false return predicate(resultType) } fun KtCallExpression.implicitReceiver(context: BindingContext): ImplicitReceiver? { return getResolvedCall(context)?.getImplicitReceiverValue() } fun KtCallExpression.receiverType(context: BindingContext): KotlinType? { return (getQualifiedExpressionForSelector())?.receiverExpression?.getResolvedCall(context)?.resultingDescriptor?.returnType ?: implicitReceiver(context)?.type }
apache-2.0
862250dcb0ee0253fecfbb1ab2a03cb7
52.586538
158
0.778755
5.057169
false
false
false
false
ngthtung2805/dalatlaptop
app/src/main/java/com/tungnui/dalatlaptop/ux/adapters/ProductReviewRecyclerAdapter.kt
1
1978
package com.tungnui.dalatlaptop.ux.adapters import android.support.v7.widget.RecyclerView import android.view.View import android.view.ViewGroup import com.travijuu.numberpicker.library.Enums.ActionEnum import com.travijuu.numberpicker.library.Interface.ValueChangedListener import com.tungnui.dalatlaptop.R import com.tungnui.dalatlaptop.interfaces.CartRecyclerInterface import com.tungnui.dalatlaptop.listeners.OnSingleClickListener import com.tungnui.dalatlaptop.models.Cart import com.tungnui.dalatlaptop.models.ProductReview import com.tungnui.dalatlaptop.utils.inflate import kotlinx.android.synthetic.main.list_item_customer_review.view.* import java.util.ArrayList class ProductReviewRecyclerAdapter() : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private val productReviews = ArrayList<ProductReview>() override fun getItemCount(): Int { return productReviews.size } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder = ViewHolderProduct(parent.inflate(R.layout.list_item_customer_review)) override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { (holder as ViewHolderProduct).blind(productReviews[position]) } fun refreshItems(proRes: List<ProductReview>) { productReviews.clear() productReviews.addAll(proRes) notifyDataSetChanged() } fun cleatCart() { productReviews.clear() notifyDataSetChanged() } class ViewHolderProduct(itemView: View) : RecyclerView.ViewHolder(itemView) { fun blind(productReview: ProductReview) = with(itemView){ productReview.rating?.let{list_item_customer_review_rating.rating=it.toFloat()} list_item_customer_review_date.text = productReview.dateCreated list_item_customer_review_name.text = productReview.name list_item_customer_review_content.text = productReview.review } } }
mit
bb142d7d9e64cf6ac55c3c220af57b38
34.981818
96
0.755308
4.632319
false
false
false
false
aohanyao/CodeMall
code/ServerCode/CodeMallServer/src/main/java/com/jjc/mailshop/service/imp/FileServiceImp.kt
1
2919
package com.jjc.mailshop.service.imp import com.jjc.mailshop.common.ServerResponse import com.jjc.mailshop.service.IFileService import org.springframework.stereotype.Service import org.springframework.web.multipart.MultipartFile import java.io.File import java.util.* import com.qiniu.common.QiniuException import com.qiniu.storage.model.DefaultPutRet import com.google.gson.Gson import com.qiniu.util.Auth import com.qiniu.storage.UploadManager import com.qiniu.common.Zone import com.qiniu.storage.Configuration /** * Created by Administrator on 2017/6/13 0013. */ @Service class FileServiceImp : IFileService { override fun uploadImage(file: MultipartFile, realFilePath: String): ServerResponse<String> { //1.先存放到本地 //查看文件夹是否存在 var mFile = File(realFilePath) if (!mFile.exists()) { //可写 mFile.setWritable(true) //创建文件夹 mFile.mkdir() } // 获取拓展名 val fileName = file.originalFilename // 获取拓展名 val mExtName = fileName.subSequence(fileName.indexOfLast { it == '.' } + 1, fileName.length) //创建文件 val targetFile = File("$realFilePath/${UUID.randomUUID()}.$mExtName") //写入文件 try { file.transferTo(targetFile) } catch(e: Exception) { e.printStackTrace() return ServerResponse.createByErrorMessage("文件上传失败") } //2.上传到七牛 //构造一个带指定Zone对象的配置类 val cfg = Configuration(Zone.zone2()) //...其他参数参考类注释 val uploadManager = UploadManager(cfg) //...生成上传凭证,然后准备上传 val accessKey = "4pEFhEobGofwwHN2wDlk_z7X-DyHdqli7bBnH2nj" val secretKey = "bXRxAo7Tar2yqvi1tTbAA4pONPZZbRUhiOFUdlMW" //目标名称 val bucket = "mal-shop-image" //如果是Windows情况下,格式是 D:\\qiniu\\test.png val localFilePath = targetFile.path //默认不指定key的情况下,以文件内容的hash值作为文件名 val key: String? = null val auth = Auth.create(accessKey, secretKey) val upToken = auth.uploadToken(bucket) try { val response = uploadManager.put(localFilePath, key, upToken) //解析上传成功的结果 val putRet = Gson().fromJson(response.bodyString(), DefaultPutRet::class.java) //3.删除本地 targetFile.delete() //返回结果 return ServerResponse.createBySuccess("上传成功", "http://orfgrfzku.bkt.clouddn.com/${putRet.key}") } catch (ex: QiniuException) { val r = ex.response //返回错误 return ServerResponse.createBySuccessMessage(r.toString()) } } }
apache-2.0
2e25e532e1ad1dbb550acd834162e01e
31.02439
107
0.633143
3.712871
false
false
false
false
androidx/androidx
viewpager2/viewpager2/src/androidTest/java/androidx/viewpager2/widget/swipe/PageView.kt
3
1578
/* * Copyright 2018 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.viewpager2.widget.swipe import android.app.Activity import android.graphics.Color import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.viewpager2.test.R private val PAGE_COLOR_EVEN = Color.parseColor("#FFAAAA") private val PAGE_COLOR_ODD = Color.parseColor("#AAAAFF") object PageView { fun inflatePage(layoutInflater: LayoutInflater, parent: ViewGroup?): View = layoutInflater.inflate(R.layout.item_test_layout, parent, false) fun findPageInActivity(activity: Activity): View? = activity.findViewById(R.id.text_view) fun getPageText(page: View): String = (page as TextView).text.toString() fun setPageText(page: View, text: String) { (page as TextView).text = text } fun setPageColor(page: View, position: Int) { page.setBackgroundColor(if (position % 2 == 0) PAGE_COLOR_EVEN else PAGE_COLOR_ODD) } }
apache-2.0
498500d4abeafa9b974277a5436ae46a
34.066667
93
0.740177
3.994937
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/components/settings/app/chats/sms/SmsSettingsFragment.kt
1
7038
package org.thoughtcrime.securesms.components.settings.app.chats.sms import android.annotation.SuppressLint import android.app.Activity import android.content.Intent import android.os.Build import android.provider.Settings import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.lifecycle.ViewModelProvider import androidx.navigation.Navigation import androidx.navigation.fragment.findNavController import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.components.settings.DSLConfiguration import org.thoughtcrime.securesms.components.settings.DSLSettingsFragment import org.thoughtcrime.securesms.components.settings.DSLSettingsText import org.thoughtcrime.securesms.components.settings.configure import org.thoughtcrime.securesms.components.settings.models.OutlinedLearnMore import org.thoughtcrime.securesms.exporter.flow.SmsExportActivity import org.thoughtcrime.securesms.exporter.flow.SmsExportDialogs import org.thoughtcrime.securesms.keyvalue.SignalStore import org.thoughtcrime.securesms.keyvalue.SmsExportPhase import org.thoughtcrime.securesms.util.SmsUtil import org.thoughtcrime.securesms.util.Util import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter import org.thoughtcrime.securesms.util.navigation.safeNavigate private const val SMS_REQUEST_CODE: Short = 1234 class SmsSettingsFragment : DSLSettingsFragment(R.string.preferences__sms_mms) { private lateinit var viewModel: SmsSettingsViewModel private lateinit var smsExportLauncher: ActivityResultLauncher<Intent> override fun onResume() { super.onResume() viewModel.checkSmsEnabled() } override fun bindAdapter(adapter: MappingAdapter) { OutlinedLearnMore.register(adapter) smsExportLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { if (it.resultCode == Activity.RESULT_OK) { SmsExportDialogs.showSmsRemovalDialog(requireContext(), requireView()) } } viewModel = ViewModelProvider(this)[SmsSettingsViewModel::class.java] viewModel.state.observe(viewLifecycleOwner) { adapter.submitList(getConfiguration(it).toMappingModelList()) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (Util.isDefaultSmsProvider(requireContext())) { SignalStore.settings().setDefaultSms(true) } else { SignalStore.settings().setDefaultSms(false) if (SignalStore.misc().smsExportPhase.isAtLeastPhase1()) { findNavController().navigateUp() } } } private fun getConfiguration(state: SmsSettingsState): DSLConfiguration { return configure { if (state.useAsDefaultSmsApp && SignalStore.misc().smsExportPhase.isAtLeastPhase1()) { customPref( OutlinedLearnMore.Model( summary = DSLSettingsText.from(R.string.SmsSettingsFragment__sms_support_will_be_removed_soon_to_focus_on_encrypted_messaging), learnMoreUrl = getString(R.string.sms_export_url) ) ) } when (state.smsExportState) { SmsExportState.FETCHING -> Unit SmsExportState.HAS_UNEXPORTED_MESSAGES -> { clickPref( title = DSLSettingsText.from(R.string.SmsSettingsFragment__export_sms_messages), summary = DSLSettingsText.from(R.string.SmsSettingsFragment__you_can_export_your_sms_messages_to_your_phones_sms_database), onClick = { smsExportLauncher.launch(SmsExportActivity.createIntent(requireContext())) } ) dividerPref() } SmsExportState.ALL_MESSAGES_EXPORTED -> { clickPref( title = DSLSettingsText.from(R.string.SmsSettingsFragment__remove_sms_messages), summary = DSLSettingsText.from(R.string.SmsSettingsFragment__remove_sms_messages_from_signal_to_clear_up_storage_space), onClick = { SmsExportDialogs.showSmsRemovalDialog(requireContext(), requireView()) } ) clickPref( title = DSLSettingsText.from(R.string.SmsSettingsFragment__export_sms_messages_again), summary = DSLSettingsText.from(R.string.SmsSettingsFragment__exporting_again_can_result_in_duplicate_messages), onClick = { SmsExportDialogs.showSmsReExportDialog(requireContext()) { smsExportLauncher.launch(SmsExportActivity.createIntent(requireContext(), isReExport = true)) } } ) dividerPref() } SmsExportState.NO_SMS_MESSAGES_IN_DATABASE -> Unit SmsExportState.NOT_AVAILABLE -> Unit } if (state.useAsDefaultSmsApp || SignalStore.misc().smsExportPhase == SmsExportPhase.PHASE_0) { @Suppress("DEPRECATION") clickPref( title = DSLSettingsText.from(R.string.SmsSettingsFragment__use_as_default_sms_app), summary = DSLSettingsText.from(if (state.useAsDefaultSmsApp) R.string.arrays__enabled else R.string.arrays__disabled), onClick = { if (state.useAsDefaultSmsApp) { startDefaultAppSelectionIntent() } else { startActivityForResult(SmsUtil.getSmsRoleIntent(requireContext()), SMS_REQUEST_CODE.toInt()) } } ) } switchPref( title = DSLSettingsText.from(R.string.preferences__sms_delivery_reports), summary = DSLSettingsText.from(R.string.preferences__request_a_delivery_report_for_each_sms_message_you_send), isChecked = state.smsDeliveryReportsEnabled, onClick = { viewModel.setSmsDeliveryReportsEnabled(!state.smsDeliveryReportsEnabled) } ) switchPref( title = DSLSettingsText.from(R.string.preferences__support_wifi_calling), summary = DSLSettingsText.from(R.string.preferences__enable_if_your_device_supports_sms_mms_delivery_over_wifi), isChecked = state.wifiCallingCompatibilityEnabled, onClick = { viewModel.setWifiCallingCompatibilityEnabled(!state.wifiCallingCompatibilityEnabled) } ) if (Build.VERSION.SDK_INT < 21) { clickPref( title = DSLSettingsText.from(R.string.preferences__advanced_mms_access_point_names), onClick = { Navigation.findNavController(requireView()).safeNavigate(R.id.action_smsSettingsFragment_to_mmsPreferencesFragment) } ) } } } // Linter isn't smart enough to figure out the else only happens if API >= 24 @SuppressLint("InlinedApi") @Suppress("DEPRECATION") private fun startDefaultAppSelectionIntent() { val intent: Intent = when { Build.VERSION.SDK_INT < 23 -> Intent(Settings.ACTION_WIRELESS_SETTINGS) Build.VERSION.SDK_INT < 24 -> Intent(Settings.ACTION_SETTINGS) else -> Intent(Settings.ACTION_MANAGE_DEFAULT_APPS_SETTINGS) } startActivityForResult(intent, SMS_REQUEST_CODE.toInt()) } }
gpl-3.0
a07aaf200675cdae335f06d13fbf5e59
39.682081
139
0.711566
4.78125
false
false
false
false
androidx/androidx
room/room-common/src/main/java/androidx/room/ColumnInfo.kt
3
6691
/* * Copyright (C) 2016 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.room import androidx.annotation.IntDef import androidx.annotation.RequiresApi /** * Allows specific customization about the column associated with this field. * * For example, you can specify a column name for the field or change the column's type affinity. */ @Target(AnnotationTarget.FIELD, AnnotationTarget.FUNCTION) @Retention(AnnotationRetention.BINARY) public annotation class ColumnInfo( /** * Name of the column in the database. Defaults to the field name if not set. * * @return Name of the column in the database. */ val name: String = INHERIT_FIELD_NAME, /** * The type affinity for the column, which will be used when constructing the database. * * If it is not specified, the value defaults to [UNDEFINED] and Room resolves it based * on the field's type and available TypeConverters. * * See [SQLite types documentation](https://www.sqlite.org/datatype3.html) for details. * * @return The type affinity of the column. This is either [UNDEFINED], [TEXT], * [INTEGER], [REAL], or [BLOB]. */ @SuppressWarnings("unused") @get:SQLiteTypeAffinity val typeAffinity: Int = UNDEFINED, /** * Convenience method to index the field. * * If you would like to create a composite index instead, see: [Index]. * * @return True if this field should be indexed, false otherwise. Defaults to false. */ val index: Boolean = false, /** * The collation sequence for the column, which will be used when constructing the database. * * The default value is [UNSPECIFIED]. In that case, Room does not add any * collation sequence to the column, and SQLite treats it like [BINARY]. * * @return The collation sequence of the column. This is either [UNSPECIFIED], * [BINARY], [NOCASE], [RTRIM], [LOCALIZED] or [UNICODE]. */ @get:Collate val collate: Int = UNSPECIFIED, /** * The default value for this column. * * ``` * @ColumnInfo(defaultValue = "No name") * public name: String * * @ColumnInfo(defaultValue = "0") * public flag: Int * ``` * * Note that the default value you specify here will _NOT_ be used if you simply * insert the [Entity] with [Insert]. In that case, any value assigned in * Java/Kotlin will be used. Use [Query] with an `INSERT` statement * and skip this column there in order to use this default value. * * NULL, CURRENT_TIMESTAMP and other SQLite constant values are interpreted as such. If you want * to use them as strings for some reason, surround them with single-quotes. * * ``` * @ColumnInfo(defaultValue = "NULL") * public description: String? * * @ColumnInfo(defaultValue = "'NULL'") * public name: String * ``` * * You can also use constant expressions by surrounding them with parentheses. * * ``` * @ColumnInfo(defaultValue = "('Created at' || CURRENT_TIMESTAMP)") * public notice: String * ``` * * @return The default value for this column. * @see [VALUE_UNSPECIFIED] */ val defaultValue: String = VALUE_UNSPECIFIED, ) { /** * The SQLite column type constants that can be used in [typeAffinity()] */ @IntDef(UNDEFINED, TEXT, INTEGER, REAL, BLOB) @Retention(AnnotationRetention.BINARY) public annotation class SQLiteTypeAffinity @RequiresApi(21) @IntDef(UNSPECIFIED, BINARY, NOCASE, RTRIM, LOCALIZED, UNICODE) @Retention(AnnotationRetention.BINARY) public annotation class Collate public companion object { /** * Constant to let Room inherit the field name as the column name. If used, Room will use * the field name as the column name. */ public const val INHERIT_FIELD_NAME: String = "[field-name]" /** * Undefined type affinity. Will be resolved based on the type. * * @see typeAffinity() */ public const val UNDEFINED: Int = 1 /** * Column affinity constant for strings. * * @see typeAffinity() */ public const val TEXT: Int = 2 /** * Column affinity constant for integers or booleans. * * @see typeAffinity() */ public const val INTEGER: Int = 3 /** * Column affinity constant for floats or doubles. * * @see typeAffinity() */ public const val REAL: Int = 4 /** * Column affinity constant for binary data. * * @see typeAffinity() */ public const val BLOB: Int = 5 /** * Collation sequence is not specified. The match will behave like [BINARY]. * * @see collate() */ public const val UNSPECIFIED: Int = 1 /** * Collation sequence for case-sensitive match. * * @see collate() */ public const val BINARY: Int = 2 /** * Collation sequence for case-insensitive match. * * @see collate() */ public const val NOCASE: Int = 3 /** * Collation sequence for case-sensitive match except that trailing space characters are * ignored. * * @see collate() */ public const val RTRIM: Int = 4 /** * Collation sequence that uses system's current locale. * * @see collate() */ @RequiresApi(21) public const val LOCALIZED: Int = 5 /** * Collation sequence that uses Unicode Collation Algorithm. * * @see collate() */ @RequiresApi(21) public const val UNICODE: Int = 6 /** * A constant for [defaultValue()] that makes the column to have no default value. */ public const val VALUE_UNSPECIFIED: String = "[value-unspecified]" } }
apache-2.0
2eab227973bd00db9caaff5622c11aee
29.981481
100
0.606636
4.636868
false
false
false
false
GunoH/intellij-community
platform/core-impl/src/com/intellij/openapi/vfs/impl/LightFilePointer.kt
2
2419
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.vfs.impl import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.vfs.StandardFileSystems import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.pointers.VirtualFilePointer open class LightFilePointer : VirtualFilePointer { private val myUrl: String @Volatile private var myFile: VirtualFile? = null @Volatile private var isRefreshed = false constructor(url: String) { myUrl = url } constructor(file: VirtualFile) { myUrl = file.url myFile = file } override fun getFile(): VirtualFile? { refreshFile() return myFile } override fun getUrl(): String = myUrl override fun getFileName(): String { myFile?.let { return it.name } val index = myUrl.lastIndexOf('/') return if (index >= 0) myUrl.substring(index + 1) else myUrl } override fun getPresentableUrl(): String { return file?.presentableUrl ?: toPresentableUrl(myUrl) } override fun isValid(): Boolean = file != null private fun refreshFile() { val file = myFile if (file != null && file.isValid) { return } val virtualFileManager = VirtualFileManager.getInstance() var virtualFile = virtualFileManager.findFileByUrl(myUrl) if (virtualFile == null && !isRefreshed) { isRefreshed = true val app = ApplicationManager.getApplication() if (app.isDispatchThread || !app.isReadAccessAllowed) { virtualFile = virtualFileManager.refreshAndFindFileByUrl(myUrl) } else { app.executeOnPooledThread { virtualFileManager.refreshAndFindFileByUrl(myUrl) } } } myFile = if (virtualFile != null && virtualFile.isValid) virtualFile else null } override fun equals(other: Any?): Boolean { if (this === other) { return true } return if (other is LightFilePointer) myUrl == other.myUrl else false } override fun hashCode(): Int = myUrl.hashCode() } private fun toPresentableUrl(url: String): String { val fileSystem = VirtualFileManager.getInstance().getFileSystem(VirtualFileManager.extractProtocol(url)) return (fileSystem ?: StandardFileSystems.local()).extractPresentableUrl(VirtualFileManager.extractPath(url)) }
apache-2.0
9cdfc71a466959e8280fa803ba9e52aa
27.809524
120
0.713105
4.687984
false
false
false
false
siosio/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/util/JTableExtensions.kt
1
1480
package com.jetbrains.packagesearch.intellij.plugin.ui.util import com.jetbrains.packagesearch.intellij.plugin.util.AppUI import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import javax.swing.JTable import javax.swing.table.TableColumn internal suspend fun JTable.autosizeColumnsAt(indices: Iterable<Int>) { val (columns, preferredWidths) = withContext(Dispatchers.Default) { val columns = indices.map { columnModel.getColumn(it) } columns to getColumnDataWidths(columns) } columns.forEachIndexed { index, column -> column.width = preferredWidths[index] } } private fun JTable.getColumnDataWidths(columns: Iterable<TableColumn>): IntArray { val preferredWidth = IntArray(columns.count()) val separatorSize = intercellSpacing.width for ((index, column) in columns.withIndex()) { val maxWidth = column.maxWidth val columnIndex = column.modelIndex for (row in 0 until rowCount) { val width = getCellDataWidth(row, columnIndex) + separatorSize preferredWidth[index] = preferredWidth[index].coerceAtLeast(width) if (preferredWidth[index] >= maxWidth) break } } return preferredWidth } private fun JTable.getCellDataWidth(row: Int, column: Int): Int { val renderer = getCellRenderer(row, column) val cellWidth = prepareRenderer(renderer, row, column).preferredSize.width return cellWidth + intercellSpacing.width }
apache-2.0
ff93fb5f962dee60879b8d64927cc50a
36
82
0.727703
4.582043
false
false
false
false
siosio/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/operations/ModuleOperationExecutor.kt
1
7406
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations import com.intellij.buildsystem.model.OperationFailure import com.intellij.buildsystem.model.unified.UnifiedDependency import com.jetbrains.packagesearch.intellij.plugin.extensibility.DependencyOperationMetadata import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModuleOperationProvider import com.jetbrains.packagesearch.intellij.plugin.fus.PackageSearchEventsLogger import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageScope import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion import com.jetbrains.packagesearch.intellij.plugin.util.logDebug import com.jetbrains.packagesearch.intellij.plugin.util.logTrace import com.jetbrains.packagesearch.intellij.plugin.util.logWarn import com.jetbrains.packagesearch.intellij.plugin.util.nullIfBlank internal class ModuleOperationExecutor { /** This **MUST** run on EDT */ fun doOperation(operation: PackageSearchOperation<*>) = try { when (operation) { is PackageSearchOperation.Package.Install -> installPackage(operation) is PackageSearchOperation.Package.Remove -> removePackage(operation) is PackageSearchOperation.Package.ChangeInstalled -> changePackage(operation) is PackageSearchOperation.Repository.Install -> installRepository(operation) is PackageSearchOperation.Repository.Remove -> removeRepository(operation) } null } catch (e: OperationException) { logWarn("ModuleOperationExecutor#doOperation()", e) { "Failure while performing operation $operation" } PackageSearchOperationFailure(operation, e) } private fun installPackage(operation: PackageSearchOperation.Package.Install) { val projectModule = operation.projectModule val operationProvider = ProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType) ?: throw OperationException.unsupportedBuildSystem(projectModule) logDebug("ModuleOperationExecutor#installPackage()") { "Installing package ${operation.model.displayName} in ${projectModule.name}" } operationProvider.addDependencyToModule( operationMetadata = dependencyOperationMetadataFrom(projectModule, operation.model, operation.newVersion, operation.newScope), module = projectModule ).throwIfAnyFailures() PackageSearchEventsLogger.logPackageInstalled(operation.model, operation.projectModule) logTrace("ModuleOperationExecutor#installPackage()") { "Package ${operation.model.displayName} installed in ${projectModule.name}" } } private fun removePackage(operation: PackageSearchOperation.Package.Remove) { val projectModule = operation.projectModule val operationProvider = ProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType) ?: throw OperationException.unsupportedBuildSystem(projectModule) logDebug("ModuleOperationExecutor#removePackage()") { "Removing package ${operation.model.displayName} from ${projectModule.name}" } operationProvider.removeDependencyFromModule( operationMetadata = dependencyOperationMetadataFrom(projectModule, operation.model), module = projectModule ).throwIfAnyFailures() PackageSearchEventsLogger.logPackageRemoved(operation.model, operation.projectModule) logTrace("ModuleOperationExecutor#removePackage()") { "Package ${operation.model.displayName} removed from ${projectModule.name}" } } private fun changePackage(operation: PackageSearchOperation.Package.ChangeInstalled) { val projectModule = operation.projectModule val operationProvider = ProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType) ?: throw OperationException.unsupportedBuildSystem(projectModule) logDebug("ModuleOperationExecutor#changePackage()") { "Changing package ${operation.model.displayName} in ${projectModule.name}" } operationProvider.updateDependencyInModule( operationMetadata = dependencyOperationMetadataFrom(projectModule, operation.model, operation.newVersion, operation.newScope), module = projectModule ).throwIfAnyFailures() PackageSearchEventsLogger.logPackageUpdated(operation.model, operation.projectModule) logTrace("ModuleOperationExecutor#changePackage()") { "Package ${operation.model.displayName} changed in ${projectModule.name}" } } private fun dependencyOperationMetadataFrom( projectModule: ProjectModule, dependency: UnifiedDependency, newVersion: PackageVersion? = null, newScope: PackageScope? = null ) = DependencyOperationMetadata( module = projectModule, groupId = dependency.coordinates.groupId.nullIfBlank() ?: throw OperationException.InvalidPackage(dependency), artifactId = dependency.coordinates.artifactId.nullIfBlank() ?: throw OperationException.InvalidPackage(dependency), currentVersion = dependency.coordinates.version.nullIfBlank(), currentScope = dependency.scope.nullIfBlank(), newVersion = newVersion?.versionName.nullIfBlank() ?: dependency.coordinates.version.nullIfBlank(), newScope = newScope?.scopeName.nullIfBlank() ?: dependency.scope.nullIfBlank() ) private fun installRepository(operation: PackageSearchOperation.Repository.Install) { val projectModule = operation.projectModule val operationProvider = ProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType) ?: throw OperationException.unsupportedBuildSystem(projectModule) logDebug("ModuleOperationExecutor#installRepository()") { "Installing repository ${operation.model.displayName} in ${projectModule.name}" } operationProvider.addRepositoryToModule(operation.model, projectModule) .throwIfAnyFailures() PackageSearchEventsLogger.logRepositoryAdded(operation.model) logTrace("ModuleOperationExecutor#installRepository()") { "Repository ${operation.model.displayName} installed in ${projectModule.name}" } } private fun removeRepository(operation: PackageSearchOperation.Repository.Remove) { val projectModule = operation.projectModule val operationProvider = ProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType) ?: throw OperationException.unsupportedBuildSystem(projectModule) logDebug("ModuleOperationExecutor#removeRepository()") { "Removing repository ${operation.model.displayName} from ${projectModule.name}" } operationProvider.removeRepositoryFromModule(operation.model, projectModule) .throwIfAnyFailures() PackageSearchEventsLogger.logRepositoryRemoved(operation.model) logTrace("ModuleOperationExecutor#removeRepository()") { "Repository ${operation.model.displayName} removed from ${projectModule.name}" } } private fun List<OperationFailure<*>>.throwIfAnyFailures() { when { isEmpty() -> return size > 1 -> throw IllegalStateException("A single operation resulted in multiple failures") } } }
apache-2.0
ce132f11d66fc50625cc3134ecb5530e
55.969231
147
0.762085
6.265651
false
false
false
false
JetBrains/kotlin-native
backend.native/tests/compilerChecks/t38.kt
3
335
import kotlinx.cinterop.* import kotlinx.cinterop.internal.* @CStruct(spelling = "struct { }") class Z constructor(rawPtr: NativePtr) : CStructVar(rawPtr) { var x: Pair<Int, Int>? = null @CStruct.MemberAt(offset = 0L) get @CStruct.MemberAt(offset = 0L) set } fun foo(z: Z) { z.x = 42 to 117 } fun main() { }
apache-2.0
a90d02c5cd2e87e61027e847131856da
22.928571
95
0.635821
3.160377
false
false
false
false
jwren/intellij-community
plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/IntelliJKotlinNewProjectWizard.kt
4
3902
// 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.tools.projectWizard import com.intellij.ide.JavaUiBundle import com.intellij.ide.projectWizard.NewProjectWizardCollector.BuildSystem.logAddSampleCodeChanged import com.intellij.ide.projectWizard.NewProjectWizardCollector.BuildSystem.logSdkChanged import com.intellij.ide.projectWizard.NewProjectWizardConstants.BuildSystem.INTELLIJ import com.intellij.ide.projectWizard.generators.AssetsNewProjectWizardStep import com.intellij.ide.starters.local.StandardAssetsProvider import com.intellij.ide.wizard.AbstractNewProjectWizardStep import com.intellij.ide.wizard.GitNewProjectWizardData.Companion.gitData import com.intellij.ide.wizard.NewProjectWizardBaseData.Companion.name import com.intellij.ide.wizard.NewProjectWizardBaseData.Companion.path import com.intellij.ide.wizard.NewProjectWizardStep import com.intellij.ide.wizard.chain import com.intellij.openapi.module.StdModuleTypes import com.intellij.openapi.observable.util.bindBooleanStorage import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.JavaSdkType import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.SdkTypeId import com.intellij.openapi.projectRoots.impl.DependentSdkType import com.intellij.openapi.roots.ui.configuration.sdkComboBox import com.intellij.ui.UIBundle.* import com.intellij.ui.dsl.builder.* import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemType internal class IntelliJKotlinNewProjectWizard : BuildSystemKotlinNewProjectWizard { override val name = INTELLIJ override val ordinal = 0 override fun createStep(parent: KotlinNewProjectWizard.Step) = Step(parent).chain(::AssetsStep) class Step(parent: KotlinNewProjectWizard.Step) : AbstractNewProjectWizardStep(parent), BuildSystemKotlinNewProjectWizardData by parent { private val sdkProperty = propertyGraph.property<Sdk?>(null) private val addSampleCodeProperty = propertyGraph.property(false) .bindBooleanStorage("NewProjectWizard.addSampleCodeState") private val sdk by sdkProperty private val addSampleCode by addSampleCodeProperty override fun setupUI(builder: Panel) { with(builder) { row(JavaUiBundle.message("label.project.wizard.new.project.jdk")) { val sdkTypeFilter = { it: SdkTypeId -> it is JavaSdkType && it !is DependentSdkType } sdkComboBox(context, sdkProperty, StdModuleTypes.JAVA.id, sdkTypeFilter) .columns(COLUMNS_MEDIUM) .whenItemSelectedFromUi { logSdkChanged(sdk) } } row { checkBox(message("label.project.wizard.new.project.add.sample.code")) .bindSelected(addSampleCodeProperty) .whenStateChangedFromUi { logAddSampleCodeChanged(it) } }.topGap(TopGap.SMALL) kmpWizardLink(context) } } override fun setupProject(project: Project) = KotlinNewProjectWizard.generateProject( project = project, projectPath = "$path/$name", projectName = name, sdk = sdk, buildSystemType = BuildSystemType.Jps, addSampleCode = addSampleCode ) } private class AssetsStep(parent: NewProjectWizardStep) : AssetsNewProjectWizardStep(parent) { override fun setupAssets(project: Project) { outputDirectory = "$path/$name" if (gitData?.git == true) { addAssets(StandardAssetsProvider().getIntelliJIgnoreAssets()) } } } }
apache-2.0
23f47a7634b0e1f0c83d0f8a088171b9
45.464286
158
0.717581
5.237584
false
false
false
false
smmribeiro/intellij-community
java/compiler/impl/src/com/intellij/compiler/impl/CompileDriverNotifications.kt
10
3507
// 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.compiler.impl import com.intellij.build.BuildContentManager import com.intellij.notification.Notification import com.intellij.notification.NotificationAction import com.intellij.notification.NotificationGroupManager import com.intellij.notification.NotificationType import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.invokeLater import com.intellij.openapi.compiler.JavaCompilerBundle import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService import com.intellij.openapi.util.NlsContexts.NotificationContent import com.intellij.openapi.wm.ToolWindowManager import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicReference @Service //project class CompileDriverNotifications( private val project: Project ) : Disposable { private val currentNotification = AtomicReference<Notification>(null) companion object { @JvmStatic fun getInstance(project: Project) = project.service<CompileDriverNotifications>() } override fun dispose() { currentNotification.set(null) } fun createCannotStartNotification() : LightNotification { return LightNotification() } inner class LightNotification { private val isShown = AtomicBoolean() private val notificationGroup = NotificationGroupManager.getInstance().getNotificationGroup("jps configuration error") private val baseNotification = notificationGroup .createNotification(JavaCompilerBundle.message("notification.title.jps.cannot.start.compiler"), NotificationType.ERROR) .setImportant(true) fun withExpiringAction(@NotificationContent title : String, handler: () -> Unit) = apply { baseNotification.addAction(NotificationAction.createSimpleExpiring(title, handler)) } @JvmOverloads fun withOpenSettingsAction(moduleNameToSelect: String? = null, tabNameToSelect: String? = null) = withExpiringAction(JavaCompilerBundle.message("notification.action.jps.open.configuration.dialog")) { val service = ProjectSettingsService.getInstance(project) if (moduleNameToSelect != null) { service.showModuleConfigurationDialog(moduleNameToSelect, tabNameToSelect) } else { service.openProjectSettings() } } fun withContent(@NotificationContent content: String): LightNotification = apply { baseNotification.setContent(content) } /** * This wrapper helps to make sure we have only one active unresolved notification per project */ fun showNotification() { if (ApplicationManager.getApplication().isUnitTestMode) { thisLogger().error("" + baseNotification.content) return } if (!isShown.compareAndSet(false, true)) return val showNotification = Runnable { baseNotification.whenExpired { currentNotification.compareAndExchange(baseNotification, null) } currentNotification.getAndSet(baseNotification)?.expire() baseNotification.notify(project) } showNotification.run() } } }
apache-2.0
c09542e46b0e5bf8c885f61ac12d6655
36.308511
140
0.759338
5.203264
false
false
false
false
smmribeiro/intellij-community
plugins/git4idea/src/git4idea/history/GitHistoryTraverserImpl.kt
4
10064
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.history import com.intellij.openapi.Disposable import com.intellij.openapi.components.service import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.Consumer import com.intellij.util.EventDispatcher import com.intellij.vcs.log.* import com.intellij.vcs.log.data.VcsLogData import com.intellij.vcs.log.data.index.IndexDataGetter import com.intellij.vcs.log.data.index.IndexedDetails.Companion.createMetadata import com.intellij.vcs.log.data.index.VcsLogIndex import com.intellij.vcs.log.graph.api.LiteLinearGraph import com.intellij.vcs.log.graph.impl.facade.PermanentGraphImpl import com.intellij.vcs.log.graph.utils.BfsWalk import com.intellij.vcs.log.graph.utils.DfsWalk import com.intellij.vcs.log.graph.utils.LinearGraphUtils import com.intellij.vcs.log.graph.utils.impl.BitSetFlags import com.intellij.vcs.log.impl.TimedVcsCommitImpl import com.intellij.vcs.log.util.VcsLogUtil import com.intellij.vcs.log.visible.filters.VcsLogFilterObject import git4idea.GitCommit import git4idea.GitUtil import git4idea.GitVcs import git4idea.history.GitHistoryTraverser.Traverse import git4idea.history.GitHistoryTraverser.TraverseCommitInfo import java.util.* internal class GitHistoryTraverserImpl(private val project: Project, private val logData: VcsLogData) : GitHistoryTraverser { private val requestedRootsIndexingListeners = EventDispatcher.create(RequestedRootsIndexingListener::class.java) private val indexListener = VcsLogIndex.IndexingFinishedListener { requestedRootsIndexingListeners.multicaster.indexingFinished(it) } init { logData.index.addListener(indexListener) Disposer.register(logData, this) } override fun toHash(id: TraverseCommitId) = logData.getCommitId(id)!!.hash private fun startSearch( start: Hash, root: VirtualFile, walker: (startId: TraverseCommitId, graph: LiteLinearGraph, visited: BitSetFlags, handler: (id: TraverseCommitId) -> Boolean) -> Unit, commitHandler: Traverse.(id: TraverseCommitInfo) -> Boolean ) { val dataPack = logData.dataPack val hashIndex = logData.getCommitIndex(start, root) val permanentGraph = dataPack.permanentGraph as PermanentGraphImpl<Int> val hashNodeId = permanentGraph.permanentCommitsInfo.getNodeId(hashIndex).takeIf { it != -1 } ?: throw IllegalArgumentException("Hash '${start.asString()}' doesn't exist in repository: $root") val graph = LinearGraphUtils.asLiteLinearGraph(permanentGraph.linearGraph) val visited = BitSetFlags(graph.nodesCount()) val traverse = TraverseImpl(this) walker(hashNodeId, graph, visited) { ProgressManager.checkCanceled() if (Disposer.isDisposed(this)) { throw ProcessCanceledException() } val commitId = permanentGraph.permanentCommitsInfo.getCommitId(it) val parents = graph.getNodes(it, LiteLinearGraph.NodeFilter.DOWN) traverse.commitHandler(TraverseCommitInfo(commitId, parents)) } traverse.loadDetails() } override fun traverse( root: VirtualFile, start: GitHistoryTraverser.StartNode, type: GitHistoryTraverser.TraverseType, commitHandler: Traverse.(id: TraverseCommitInfo) -> Boolean ) { fun findBranchHash(branchName: String) = VcsLogUtil.findBranch(logData.dataPack.refsModel, root, branchName)?.commitHash ?: throw IllegalArgumentException("Branch '$branchName' doesn't exist in the repository: $root") val hash = when (start) { is GitHistoryTraverser.StartNode.CommitHash -> start.hash GitHistoryTraverser.StartNode.Head -> findBranchHash(GitUtil.HEAD) is GitHistoryTraverser.StartNode.Branch -> findBranchHash(start.branchName) } startSearch( hash, root, walker = { hashNodeId, graph, visited, handler -> when (type) { GitHistoryTraverser.TraverseType.DFS -> DfsWalk(listOf(hashNodeId), graph, visited).walk(true, handler) GitHistoryTraverser.TraverseType.BFS -> BfsWalk(hashNodeId, graph, visited).walk(handler) } }, commitHandler = commitHandler ) } override fun addIndexingListener( roots: Collection<VirtualFile>, disposable: Disposable, listener: GitHistoryTraverser.IndexingListener ) { val indexingListener = RequestedRootsIndexingListenerImpl(roots, this, listener) requestedRootsIndexingListeners.addListener(indexingListener, disposable) val indexedRoot = roots.firstOrNull { logData.index.isIndexed(it) } ?: return indexingListener.indexingFinished(indexedRoot) } override fun loadMetadata(ids: List<TraverseCommitId>): List<VcsCommitMetadata> = ids.groupBy { getRoot(it) }.map { (root, commits) -> GitLogUtil.collectMetadata(project, GitVcs.getInstance(project), root, commits.map { toHash(it).asString() }) }.flatten() override fun loadFullDetails( ids: List<TraverseCommitId>, requirements: GitCommitRequirements, fullDetailsHandler: (GitCommit) -> Unit ) { ids.groupBy { getRoot(it) }.forEach { (root, commits) -> GitLogUtil.readFullDetailsForHashes(project, root, commits.map { toHash(it).asString() }, requirements, Consumer { fullDetailsHandler(it) }) } } override fun getCurrentUser(root: VirtualFile): VcsUser? = logData.currentUser[root] override fun dispose() { logData.index.removeListener(indexListener) } private fun getRoot(id: TraverseCommitId): VirtualFile = logData.getCommitId(id)!!.root private class IndexedRootImpl( private val traverser: GitHistoryTraverser, private val project: Project, override val root: VirtualFile, private val dataGetter: IndexDataGetter ) : GitHistoryTraverser.IndexedRoot { override fun filterCommits(filter: GitHistoryTraverser.IndexedRoot.TraverseCommitsFilter): Collection<TraverseCommitId> { val logFilter = when (filter) { is GitHistoryTraverser.IndexedRoot.TraverseCommitsFilter.Author -> VcsLogFilterObject.fromUser(filter.author) is GitHistoryTraverser.IndexedRoot.TraverseCommitsFilter.File -> VcsLogFilterObject.fromPaths(setOf(filter.file)) } return dataGetter.filter(listOf(logFilter)) } override fun loadTimedCommit(id: TraverseCommitId): TimedVcsCommit { val parents = dataGetter.getParents(id)!! val timestamp = dataGetter.getCommitTime(id)!! val hash = traverser.toHash(id) return TimedVcsCommitImpl(hash, parents, timestamp) } override fun loadMetadata(id: TraverseCommitId): VcsCommitMetadata { val storage = dataGetter.logStorage val factory = project.service<VcsLogObjectsFactory>() return createMetadata(id, dataGetter, storage, factory)!! } } private class RequestedRootsIndexingListenerImpl( private val requestedRoots: Collection<VirtualFile>, private val traverser: GitHistoryTraverserImpl, private val listener: GitHistoryTraverser.IndexingListener ) : RequestedRootsIndexingListener { override fun indexingFinished(root: VirtualFile) { val index = traverser.logData.index val dataGetter = index.dataGetter ?: return val indexedRoots = requestedRoots.filter { index.isIndexed(it) }.map { IndexedRootImpl(traverser, traverser.project, it, dataGetter) } if (indexedRoots.isNotEmpty()) { listener.indexedRootsUpdated(indexedRoots) } } } private interface RequestedRootsIndexingListener : VcsLogIndex.IndexingFinishedListener, EventListener private class TraverseImpl(private val traverser: GitHistoryTraverser) : Traverse { val requests = mutableListOf<Request>() override fun loadMetadataLater(id: TraverseCommitId, onLoad: (VcsCommitMetadata) -> Unit) { requests.add(Request.LoadMetadata(id, onLoad)) } override fun loadFullDetailsLater(id: TraverseCommitId, requirements: GitCommitRequirements, onLoad: (GitCommit) -> Unit) { requests.add(Request.LoadFullDetails(id, requirements, onLoad)) } fun loadDetails() { loadMetadata(requests.filterIsInstance<Request.LoadMetadata>()) loadFullDetails(requests.filterIsInstance<Request.LoadFullDetails>()) } private fun loadMetadata(loadMetadataRequests: List<Request.LoadMetadata>) { val commitsMetadata = traverser.loadMetadata(loadMetadataRequests.map { it.id }).associateBy { it.id } for (request in loadMetadataRequests) { val hash = traverser.toHash(request.id) val details = commitsMetadata[hash] ?: continue request.onLoad(details) } } private fun loadFullDetails(loadFullDetailsRequests: List<Request.LoadFullDetails>) { val handlers = mutableMapOf<Hash, MutableMap<GitCommitRequirements, MutableList<(GitCommit) -> Unit>>>() loadFullDetailsRequests.forEach { request -> traverser.toHash(request.id).let { hash -> val requirementsToHandlers = handlers.getOrPut(hash) { mutableMapOf() } requirementsToHandlers.getOrPut(request.requirements) { mutableListOf() }.add(request.onLoad) } } val requirementTypes = loadFullDetailsRequests.map { it.requirements }.distinct() requirementTypes.forEach { requirements -> traverser.loadFullDetails(loadFullDetailsRequests.map { it.id }, requirements) { details -> handlers[details.id]?.get(requirements)?.forEach { onLoad -> onLoad(details) } } } } sealed class Request(val id: TraverseCommitId) { class LoadMetadata(id: TraverseCommitId, val onLoad: (VcsCommitMetadata) -> Unit) : Request(id) class LoadFullDetails(id: TraverseCommitId, val requirements: GitCommitRequirements, val onLoad: (GitCommit) -> Unit) : Request(id) } } }
apache-2.0
b9343dfe7d1dba5f28fb3ffb7b6fdf0e
41.289916
140
0.744237
4.731547
false
false
false
false
smmribeiro/intellij-community
plugins/gradle/java/testSources/execution/GradleTasksExecutionTest.kt
12
4255
// 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.jetbrains.plugins.gradle.execution import com.intellij.execution.executors.DefaultRunExecutor import com.intellij.openapi.externalSystem.model.execution.ExternalSystemTaskExecutionSettings import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter import com.intellij.openapi.externalSystem.service.execution.ProgressExecutionMode import com.intellij.openapi.externalSystem.service.notification.ExternalSystemProgressNotificationManager import com.intellij.openapi.externalSystem.task.TaskCallback import com.intellij.openapi.externalSystem.util.ExternalSystemUtil import org.assertj.core.api.Assertions.assertThat import org.jetbrains.plugins.gradle.importing.GradleImportingTestCase import org.jetbrains.plugins.gradle.util.GradleConstants import org.junit.Test import org.junit.runners.Parameterized import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit class GradleTasksExecutionTest : GradleImportingTestCase() { @Test fun `run task with specified build file test`() { createProjectSubFile("build.gradle", """ task myTask() { doLast { print 'Hi!' } } """.trimIndent()) createProjectSubFile("build007.gradle", """ task anotherTask() { doLast { print 'Hi, James!' } } """.trimIndent()) assertThat(runTaskAndGetErrorOutput(projectPath, "myTask")).isEmpty() assertThat(runTaskAndGetErrorOutput("$projectPath/build.gradle", "myTask")).isEmpty() assertThat(runTaskAndGetErrorOutput(projectPath, "anotherTask")).contains("Task 'anotherTask' not found in root project 'project'.") assertThat(runTaskAndGetErrorOutput("$projectPath/build007.gradle", "anotherTask")).isEmpty() assertThat(runTaskAndGetErrorOutput("$projectPath/build007.gradle", "myTask")).contains( "Task 'myTask' not found in root project 'project'.") assertThat(runTaskAndGetErrorOutput("$projectPath/build.gradle", "myTask", "-b foo")).contains("The specified build file", "foo' does not exist.") } private fun runTaskAndGetErrorOutput(projectPath: String, taskName: String, scriptParameters: String = ""): String { val taskErrOutput = StringBuilder() val stdErrListener = object : ExternalSystemTaskNotificationListenerAdapter() { override fun onTaskOutput(id: ExternalSystemTaskId, text: String, stdOut: Boolean) { if (!stdOut) { taskErrOutput.append(text) } } } val notificationManager = ExternalSystemProgressNotificationManager.getInstance() notificationManager.addNotificationListener(stdErrListener) try { val settings = ExternalSystemTaskExecutionSettings() settings.externalProjectPath = projectPath settings.taskNames = listOf(taskName) settings.scriptParameters = scriptParameters settings.externalSystemIdString = GradleConstants.SYSTEM_ID.id val future = CompletableFuture<String>() ExternalSystemUtil.runTask(settings, DefaultRunExecutor.EXECUTOR_ID, myProject, GradleConstants.SYSTEM_ID, object : TaskCallback { override fun onSuccess() { future.complete(taskErrOutput.toString()) } override fun onFailure() { future.complete(taskErrOutput.toString()) } }, ProgressExecutionMode.IN_BACKGROUND_ASYNC) return future.get(10, TimeUnit.SECONDS) } finally { notificationManager.removeNotificationListener(stdErrListener) } } companion object { /** * It's sufficient to run the test against one gradle version */ @Parameterized.Parameters(name = "with Gradle-{0}") @JvmStatic fun tests(): Collection<Array<out String>> = arrayListOf(arrayOf(BASE_GRADLE_VERSION)) } }
apache-2.0
af520b50357dd3cc4d1c09eb394d126a
48.488372
140
0.700118
5.547588
false
true
false
false
BenWoodworth/FastCraft
fastcraft-bukkit/src/main/kotlin/net/benwoodworth/fastcraft/bukkit/tools/MaterialOrderGenerator.kt
1
1789
package net.benwoodworth.fastcraft.bukkit.tools import org.bukkit.Bukkit import org.bukkit.Material import java.io.File internal object MaterialOrderGenerator { private val nmsVersion = Bukkit.getServer()::class.java.`package`.name.substring("org.bukkit.craftbukkit.".length) private val nms = "net.minecraft.server.$nmsVersion" private val obc = "org.bukkit.craftbukkit.$nmsVersion" /** * For use with CraftBukkit 1.13+. * * Lists materials in the order they appear in the Minecraft item registry. (Same as in the creative menu) * * For new Minecraft releases, use this to generate a new file into bukkit/item-order/<version>.txt. */ fun generate(out: File) { val IRegistry = Class.forName("$nms.IRegistry") val IRegistry_ITEM = IRegistry.getDeclaredField("ITEM") val IRegistry_getKey = IRegistry.getDeclaredMethod("getKey", Any::class.java) val itemRegistry = IRegistry_ITEM.get(null) as Iterable<*> val Material_getKey = Material::class.java.getDeclaredMethod("getKey") val itemIdsToMaterials = enumValues<Material>() .map { Material_getKey.invoke(it).toString() to it } .toMap() val orderedItemIds = itemRegistry.asSequence() .map { item -> IRegistry_getKey.invoke(itemRegistry, item) } .map { it.toString() } val orderedMaterials = orderedItemIds .mapNotNull { itemId -> itemIdsToMaterials[itemId] .also { if (it == null) println("ID doesn't match a material: $it") } } out.writer().buffered().use { writer -> orderedMaterials.forEach { material -> writer.append("${material.name}\n") } } } }
gpl-3.0
d605460657e71c7a328dff715f6d8ecf
36.270833
118
0.633874
4.4725
false
false
false
false
erdo/asaf-project
fore-kt-android-adapters/src/main/java/co/early/fore/kt/adapters/mutable/ChangeAwareArrayList.kt
1
8682
package co.early.fore.kt.adapters.mutable import co.early.fore.adapters.mutable.ChangeAwareList import co.early.fore.adapters.mutable.UpdateSpec import co.early.fore.adapters.mutable.Updateable import co.early.fore.core.time.SystemTimeWrapper import co.early.fore.kt.core.delegate.Fore import java.util.* import java.util.function.UnaryOperator /** * <p>Basic Android adapters use notifyDataSetChanged() to trigger a redraw of the list UI. * * <code> * adapter.notifyDataSetChanged(); * </code> * * <p>In order to take advantage of insert and remove animations, we can provide the adapter with * more information about how the list has changed (eg: there was an item inserted at position 5 * or the item at position 3 has changed etc), for that we call a selection of notifyXXX methods() * indicating what sort of change happened and which rows were effected. * * <p>This list class will automatically generate an update specification for each change you make * to it, suitable for deciding how to call the various notifyXXX methods: * * <code> * * UpdateSpec updateSpec = list.getMostRecentUpdateSpec(); * * switch (updateSpec.type) { * case FULL_UPDATE: * adapter.notifyDataSetChanged(); * break; * case ITEM_CHANGED: * adapter.notifyItemChanged(updateSpec.rowPosition); * break; * case ITEM_REMOVED: * adapter.notifyItemRemoved(updateSpec.rowPosition); * break; * case ITEM_INSERTED: * adapter.notifyItemInserted(updateSpec.rowPosition); * break; * } * * </code> * * <p>This class only supports one type of change at a time (you can't handle a cell update; * two removals; and three inserts, all in the same notify round trip - each has to be handled one at a time) * */ class ChangeAwareArrayList<T>( private val systemTimeWrapper: SystemTimeWrapper? = null ) : ArrayList<T>(), ChangeAwareList<T>, Updateable { private var updateSpec: UpdateSpec = createFullUpdateSpec(Fore.getSystemTimeWrapper(systemTimeWrapper)) override fun add(element: T): Boolean { val temp = super.add(element) updateSpec = UpdateSpec( UpdateSpec.UpdateType.ITEM_INSERTED, size - 1, 1, Fore.getSystemTimeWrapper(systemTimeWrapper) ) return temp } override fun add(index: Int, element: T) { super.add(index, element) updateSpec = UpdateSpec( UpdateSpec.UpdateType.ITEM_INSERTED, index, 1, Fore.getSystemTimeWrapper(systemTimeWrapper) ) } override fun set(index: Int, element: T): T { val temp = super.set(index, element) updateSpec = UpdateSpec( UpdateSpec.UpdateType.ITEM_CHANGED, index, 1, Fore.getSystemTimeWrapper(systemTimeWrapper) ) return temp } override fun removeAt(index: Int): T { val temp = super.removeAt(index) updateSpec = UpdateSpec( UpdateSpec.UpdateType.ITEM_REMOVED, index, 1, Fore.getSystemTimeWrapper(systemTimeWrapper) ) return temp } override fun clear() { updateSpec = UpdateSpec( UpdateSpec.UpdateType.ITEM_REMOVED, 0, size, Fore.getSystemTimeWrapper(systemTimeWrapper) ) super.clear() } override fun addAll(elements: Collection<T>): Boolean { val temp = super.addAll(elements) updateSpec = UpdateSpec( UpdateSpec.UpdateType.ITEM_INSERTED, size - 1, elements.size, Fore.getSystemTimeWrapper(systemTimeWrapper) ) return temp } override fun addAll(index: Int, elements: Collection<T>): Boolean { val temp = super.addAll(index, elements) updateSpec = UpdateSpec( UpdateSpec.UpdateType.ITEM_INSERTED, index, elements.size, Fore.getSystemTimeWrapper(systemTimeWrapper) ) return temp } /** * Standard AbstractList and ArrayList have this method protected as you * are supposed to remove a range by doing this: * list.subList(start, end).clear(); * (clear() ends up calling removeRange() behind the scenes). * This won't work for these change aware lists (plus it's a ball ache), * so this gets made public */ override fun removeRange(fromIndex: Int, toIndex: Int) { super.removeRange(fromIndex, toIndex) updateSpec = UpdateSpec( UpdateSpec.UpdateType.ITEM_REMOVED, fromIndex, toIndex - fromIndex, Fore.getSystemTimeWrapper(systemTimeWrapper) ) } override fun remove(element: T): Boolean { val index = super.indexOf(element) return if (index != -1) { val temp = super.remove(element) updateSpec = UpdateSpec( UpdateSpec.UpdateType.ITEM_REMOVED, index, 1, Fore.getSystemTimeWrapper(systemTimeWrapper) ) temp } else { false } } override fun removeAll(elements: Collection<T>): Boolean { val temp = super.removeAll(elements) if (temp) { updateSpec = createFullUpdateSpec( Fore.getSystemTimeWrapper(systemTimeWrapper) ) } return temp } override fun replaceAll(operator: UnaryOperator<T>) { throw UnsupportedOperationException("Not supported by this class") } /** * Inform the list that the content of one of its rows has * changed. * * Without calling this, the list may not be aware of * any changes made to this row and the updateSpec will * be incorrect as a result (you won't get default * animations on your recyclerview) * * @param rowIndex index of the row that had its data changed */ override fun makeAwareOfDataChange(rowIndex: Int) { updateSpec = UpdateSpec( UpdateSpec.UpdateType.ITEM_CHANGED, rowIndex, 1, Fore.getSystemTimeWrapper(systemTimeWrapper) ) } /** * Inform the list that the content of a range of its rows has * changed. * * Without calling this, the list will not be aware of * any changes made to these rows and the updateSpec will * be incorrect as a result (you won't get default * animations on your recyclerview) * * @param rowStartIndex index of the row that had its data changed * @param rowsAffected how many rows have been affected */ override fun makeAwareOfDataChange(rowStartIndex: Int, rowsAffected: Int) { updateSpec = UpdateSpec( UpdateSpec.UpdateType.ITEM_CHANGED, rowStartIndex, rowsAffected, Fore.getSystemTimeWrapper(systemTimeWrapper) ) } /** * Make sure you understand the limitations of this method! * * It essentially only supports one recycleView at a time, * in the unlikely event that you want two different list * views animating the same changes to this list, you will * need to store the updateSpec returned here so that both * recycleView adapters get a copy, otherwise the second * adapter will always get a FULL_UPDATE (meaning no * fancy animations for the second one) * * If the updateSpec is old, then we assume that whatever changes * were made to the Updateable last time were never picked up by a * recyclerView (maybe because the list was not visible at the time). * In this case we clear the updateSpec and create a fresh one with a * full update spec. * * @return the latest update spec for the list */ override fun getAndClearLatestUpdateSpec(maxAgeMs: Long): UpdateSpec { val latestUpdateSpecAvailable = updateSpec updateSpec = createFullUpdateSpec(Fore.getSystemTimeWrapper(systemTimeWrapper)) return if (Fore.getSystemTimeWrapper(systemTimeWrapper).currentTimeMillis() - latestUpdateSpecAvailable.timeStamp < maxAgeMs) { latestUpdateSpecAvailable } else { updateSpec } } private fun createFullUpdateSpec(stw: SystemTimeWrapper): UpdateSpec { return UpdateSpec(UpdateSpec.UpdateType.FULL_UPDATE, 0, 0, stw) } }
apache-2.0
fd3eaee0aa54b89c14ca428cb46cbd09
33.316206
135
0.626123
4.927355
false
false
false
false
OlegAndreych/work_calendar
src/main/kotlin/org/andreych/workcalendar/storage/CalendarStorage.kt
1
1838
package org.andreych.workcalendar.storage import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import net.fortuna.ical4j.data.CalendarOutputter import net.fortuna.ical4j.model.Calendar import org.springframework.jdbc.core.JdbcTemplate import org.springframework.jdbc.core.RowMapper import java.io.ByteArrayOutputStream import java.sql.ResultSet import java.util.zip.GZIPOutputStream /** * Хранит актуальные данные iCalendar. */ class CalendarStorage(private val jdbcTemplate: JdbcTemplate) { companion object { //@formatter:off private const val INSERT_NEWS = "INSERT INTO calendar (original_json, compressed_ical) " + "VALUES (?,?) " + "ON CONFLICT DO NOTHING" //@formatter:on private const val SELECT_NEWS = "SELECT compressed_ical FROM calendar ORDER BY id DESC LIMIT 1" } suspend fun update(data: Pair<String?, Calendar>) { val bytes = withContext(Dispatchers.Default) { val calendarBytes = ByteArrayOutputStream().use { baos -> GZIPOutputStream(baos).use { gzos -> CalendarOutputter().output(data.second, gzos) } baos.toByteArray() } calendarBytes } withContext(Dispatchers.IO) { jdbcTemplate.update { con -> val ps = con.prepareStatement(INSERT_NEWS) ps.setString(1, data.first) ps.setBytes(2, bytes) ps } } } suspend fun getBytes(): ByteArray? = withContext(Dispatchers.IO) { return@withContext jdbcTemplate.query(SELECT_NEWS, RowMapper { rs: ResultSet, _: Int -> return@RowMapper rs.getBytes(1) })[0] } }
apache-2.0
00a881d3d03cc8142a8a26e97201cdd9
31.446429
95
0.618392
4.644501
false
false
false
false
odnoklassniki/ok-android-sdk
odnoklassniki-android-sdk/src/main/java/ru/ok/android/sdk/AbstractWidgetActivity.kt
2
5247
package ru.ok.android.sdk import android.app.Activity import android.app.AlertDialog import android.content.Context import android.net.http.SslError import android.os.Bundle import android.view.KeyEvent import android.webkit.SslErrorHandler import android.webkit.WebView import ru.ok.android.sdk.util.Utils import ru.ok.android.sdk.util.OkRequestUtil import java.util.* private val DEFAULT_OPTIONS = mapOf( "st.popup" to "on", "st.silent" to "on" ) internal abstract class AbstractWidgetActivity : Activity() { protected var mAppId: String? = null protected var mAccessToken: String? = null protected var mSessionSecretKey: String? = null protected val args = HashMap<String, String>() protected var retryAllowed = true protected open val layoutId: Int get() = R.layout.oksdk_webview_activity protected abstract val widgetId: String protected val baseUrl: String get() = REMOTE_WIDGETS + "dk?st.cmd=" + widgetId + "&st.access_token=" + mAccessToken + "&st.app=" + mAppId + "&st.return=" + returnUrl protected val returnUrl: String get() = "okwidget://" + widgetId.toLowerCase() protected abstract val cancelledMessageId: Int override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(layoutId) args.clear() val bundle = intent.extras if (bundle != null) { mAppId = bundle.getString(PARAM_APP_ID) mAccessToken = bundle.getString(PARAM_ACCESS_TOKEN) mSessionSecretKey = bundle.getString(PARAM_SESSION_SECRET_KEY) if (bundle.containsKey(PARAM_WIDGET_ARGS)) { @Suppress("UNCHECKED_CAST") val map = bundle.getSerializable(PARAM_WIDGET_ARGS) as? HashMap<String, String> if (map != null) { args.putAll(map) } } if (bundle.containsKey(PARAM_WIDGET_RETRY_ALLOWED)) { retryAllowed = bundle.getBoolean(PARAM_WIDGET_RETRY_ALLOWED, true) } } } protected abstract fun processResult(result: String?) protected fun processError(error: String) { if (!retryAllowed) { processResult(error) return } try { AlertDialog.Builder(this) .setMessage(error) .setPositiveButton(getString(R.string.retry)) { _, _ -> findViewById<WebView>(R.id.web_view).loadUrl(prepareUrl()) } .setNegativeButton(getString(R.string.cancel)) { _, _ -> processResult(error) } .show() } catch (ignore: RuntimeException) { // this usually happens during fast back. avoid crash in such a case processResult(error) } } /** * Prepares widget URL based on widget parameters * * @param options widget options (if null, default options are being sent) * @return widget url * @see .args * * @see .DEFAULT_OPTIONS */ protected fun prepareUrl(options: Map<String, String>? = null): String { val params = TreeMap<String, String>() for ((key, value) in args) params[key] = value params["st.return"] = returnUrl val sigSource = StringBuilder(200) val url = StringBuilder(baseUrl) for ((key, value) in params) { if (WIDGET_SIGNED_ARGS.contains(key)) sigSource.append(key).append('=').append(value) if (key != "st.return") url.append('&').append(key).append('=').append(OkRequestUtil.encode(value)) } val signature = Utils.toMD5(sigSource.toString() + mSessionSecretKey) for ((key, value) in options ?: DEFAULT_OPTIONS) url.append('&').append(key).append('=').append(value) url.append("&st.signature=").append(signature) return url.toString() } override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { if (KeyEvent.KEYCODE_BACK == keyCode) { processError(getString(cancelledMessageId)) return true } return false } @Suppress("OverridingDeprecatedMember", "DEPRECATION") inner class OkWidgetViewClient(context: Context) : OkWebViewClient(context) { override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean { if (url.startsWith(returnUrl)) { val parameters = OkRequestUtil.getUrlParameters(url) val result = parameters.getString("result") processResult(result) return true } return super.shouldOverrideUrlLoading(view, url) } override fun onReceivedError(view: WebView, errorCode: Int, description: String, failingUrl: String) { super.onReceivedError(view, errorCode, description, failingUrl) processError(getErrorMessage(errorCode)) } override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) { super.onReceivedSslError(view, handler, error) processError(getErrorMessage(error)) } } }
apache-2.0
67e75c1ab583922fc97fb8fabf2beb40
35.186207
136
0.616543
4.631068
false
false
false
false
Austin72/Charlatano
src/main/kotlin/com/charlatano/settings/Advanced.kt
1
1712
/* * Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO * Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.charlatano.settings import com.charlatano.game.CSGO.clientDLL import com.charlatano.game.offsets.ClientOffsets.dwSensitivity import com.charlatano.game.offsets.ClientOffsets.dwSensitivityPtr import com.charlatano.utils.extensions.uint /** * These should be set the same as your in-game "m_pitch" and "m_yaw" values. */ var GAME_PITCH = 0.022 // m_pitch var GAME_YAW = 0.022 // m_yaw val GAME_SENSITIVITY by lazy(LazyThreadSafetyMode.NONE) { val pointer = clientDLL.address + dwSensitivityPtr val value = clientDLL.uint(dwSensitivity) xor pointer java.lang.Float.intBitsToFloat(value.toInt()).toDouble() } /** * The tick ratio of the server. */ var SERVER_TICK_RATE = 64 /** * The maximum amount of entities that can be managed by the cached list. */ var MAX_ENTITIES = 1024 /** * The intervar in milliseconds to recycle entities in the cached list. */ var CLEANUP_TIME = 10_000
agpl-3.0
7a476f06ba7c8f9ba40c8ee87b615da7
31.942308
78
0.745911
3.762637
false
false
false
false
seventhroot/elysium
bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/database/table/RPKChatGroupTable.kt
1
5492
/* * Copyright 2016 Ross Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.chat.bukkit.database.table import com.rpkit.chat.bukkit.RPKChatBukkit import com.rpkit.chat.bukkit.chatgroup.RPKChatGroup import com.rpkit.chat.bukkit.chatgroup.RPKChatGroupImpl import com.rpkit.chat.bukkit.database.jooq.rpkit.Tables.RPKIT_CHAT_GROUP import com.rpkit.core.database.Database import com.rpkit.core.database.Table import org.ehcache.config.builders.CacheConfigurationBuilder import org.ehcache.config.builders.ResourcePoolsBuilder import org.jooq.impl.DSL.constraint import org.jooq.impl.SQLDataType /** * Represents the chat group table. */ class RPKChatGroupTable(database: Database, private val plugin: RPKChatBukkit): Table<RPKChatGroup>(database, RPKChatGroup::class) { private val cache = if (plugin.config.getBoolean("caching.rpkit_chat_group.id.enabled")) { database.cacheManager.createCache("rpk-chat-bukkit.rpkit_chat_group.id", CacheConfigurationBuilder.newCacheConfigurationBuilder(Int::class.javaObjectType, RPKChatGroup::class.java, ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_chat_group.id.size")))) } else { null } private val nameCache = if (plugin.config.getBoolean("caching.rpkit_chat_group.name.enabled")) { database.cacheManager.createCache("rpk-chat-bukkit.rpkit_chat_group.name", CacheConfigurationBuilder.newCacheConfigurationBuilder(String::class.java, Int::class.javaObjectType, ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_chat_group.name.size")))) } else { null } override fun create() { database.create .createTableIfNotExists(RPKIT_CHAT_GROUP) .column(RPKIT_CHAT_GROUP.ID, SQLDataType.INTEGER.identity(true)) .column(RPKIT_CHAT_GROUP.NAME, SQLDataType.VARCHAR(256)) .constraints( constraint("pk_rpkit_chat_group").primaryKey(RPKIT_CHAT_GROUP.ID) ) .execute() } override fun applyMigrations() { if (database.getTableVersion(this) == null) { database.setTableVersion(this, "0.4.0") } } override fun insert(entity: RPKChatGroup): Int { database.create .insertInto( RPKIT_CHAT_GROUP, RPKIT_CHAT_GROUP.NAME ) .values(entity.name) .execute() val id = database.create.lastID().toInt() entity.id = id cache?.put(id, entity) nameCache?.put(entity.name, id) return id } override fun update(entity: RPKChatGroup) { database.create .update(RPKIT_CHAT_GROUP) .set(RPKIT_CHAT_GROUP.NAME, entity.name) .where(RPKIT_CHAT_GROUP.ID.eq(entity.id)) .execute() cache?.put(entity.id, entity) nameCache?.put(entity.name, entity.id) } override fun get(id: Int): RPKChatGroup? { if (cache?.containsKey(id) == true) { return cache.get(id) } else { val result = database.create .select(RPKIT_CHAT_GROUP.NAME) .from(RPKIT_CHAT_GROUP) .where(RPKIT_CHAT_GROUP.ID.eq(id)) .fetchOne() ?: return null val chatGroup = RPKChatGroupImpl( plugin, id, result.get(RPKIT_CHAT_GROUP.NAME) ) cache?.put(id, chatGroup) nameCache?.put(chatGroup.name, id) return chatGroup } } /** * Gets a chat group by name. * If no chat group exists with the given name, null is returned. * * @param name The name * @return The chat group, or null if there is no chat group with the given name */ fun get(name: String): RPKChatGroup? { if (nameCache?.containsKey(name) == true) { return get(nameCache.get(name)) } else { val result = database.create .select(RPKIT_CHAT_GROUP.ID) .from(RPKIT_CHAT_GROUP) .where(RPKIT_CHAT_GROUP.NAME.eq(name)) .fetchOne() ?: return null val chatGroup = RPKChatGroupImpl( plugin, result.get(RPKIT_CHAT_GROUP.ID), name ) cache?.put(chatGroup.id, chatGroup) nameCache?.put(name, chatGroup.id) return chatGroup } } override fun delete(entity: RPKChatGroup) { database.create .deleteFrom(RPKIT_CHAT_GROUP) .where(RPKIT_CHAT_GROUP.ID.eq(entity.id)) .execute() cache?.remove(entity.id) nameCache?.remove(entity.name) } }
apache-2.0
823f62a9aa121bb9dbe1eb00407ba5ca
36.114865
132
0.60051
4.450567
false
true
false
false
kpspemu/kpspemu
src/commonMain/kotlin/com/soywiz/kpspemu/hle/modules/InterruptManager.kt
1
3089
package com.soywiz.kpspemu.hle.modules import com.soywiz.kpspemu.* import com.soywiz.kpspemu.cpu.* import com.soywiz.kpspemu.hle.* import com.soywiz.kpspemu.hle.manager.* @Suppress("UNUSED_PARAMETER", "MemberVisibilityCanPrivate") class InterruptManager(emulator: Emulator) : SceModule(emulator, "InterruptManager", 0x40000011, "interruptman.prx", "sceInterruptManager") { val interruptManager = emulator.interruptManager fun sceKernelRegisterSubIntrHandler( thread: PspThread, interrupt: Int, handlerIndex: Int, callbackAddress: Int, callbackArgument: Int ): Int { val intr = interruptManager.get(interrupt, handlerIndex) intr.address = callbackAddress intr.argument = callbackArgument intr.enabled = true intr.cpuState = thread.state return 0 } fun sceKernelEnableSubIntr(interrupt: Int, handlerIndex: Int): Int { val intr = interruptManager.get(interrupt, handlerIndex) intr.enabled = true return 0 } fun sceKernelDisableSubIntr(interrupt: Int, handlerIndex: Int): Int { val intr = interruptManager.get(interrupt, handlerIndex) intr.enabled = false return 0 } fun sceKernelSuspendSubIntr(cpu: CpuState): Unit = UNIMPLEMENTED(0x5CB5A78B) fun sceKernelResumeSubIntr(cpu: CpuState): Unit = UNIMPLEMENTED(0x7860E0DC) fun QueryIntrHandlerInfo(cpu: CpuState): Unit = UNIMPLEMENTED(0xD2E8363F) fun sceKernelReleaseSubIntrHandler(cpu: CpuState): Unit = UNIMPLEMENTED(0xD61E6961) fun sceKernelRegisterUserSpaceIntrStack(cpu: CpuState): Unit = UNIMPLEMENTED(0xEEE43F47) fun sceKernelIsSubInterruptOccurred(cpu: CpuState): Unit = UNIMPLEMENTED(0xFC4374B8) override fun registerModule() { registerFunctionInt( "sceKernelRegisterSubIntrHandler", 0xCA04A2B9, since = 150 ) { sceKernelRegisterSubIntrHandler(thread, int, int, int, int) } registerFunctionInt("sceKernelEnableSubIntr", 0xFB8E22EC, since = 150) { sceKernelEnableSubIntr(int, int) } registerFunctionInt("sceKernelDisableSubIntr", 0x8A389411, since = 150) { sceKernelDisableSubIntr(int, int) } registerFunctionRaw("sceKernelSuspendSubIntr", 0x5CB5A78B, since = 150) { sceKernelSuspendSubIntr(it) } registerFunctionRaw("sceKernelResumeSubIntr", 0x7860E0DC, since = 150) { sceKernelResumeSubIntr(it) } registerFunctionRaw("QueryIntrHandlerInfo", 0xD2E8363F, since = 150) { QueryIntrHandlerInfo(it) } registerFunctionRaw("sceKernelReleaseSubIntrHandler", 0xD61E6961, since = 150) { sceKernelReleaseSubIntrHandler( it ) } registerFunctionRaw( "sceKernelRegisterUserSpaceIntrStack", 0xEEE43F47, since = 150 ) { sceKernelRegisterUserSpaceIntrStack(it) } registerFunctionRaw( "sceKernelIsSubInterruptOccurred", 0xFC4374B8, since = 150 ) { sceKernelIsSubInterruptOccurred(it) } } }
mit
5caca087d749987186c0dcd8d4a137c9
39.644737
117
0.691486
4.431851
false
false
false
false
RocketChat/Rocket.Chat.Android
app/src/main/java/chat/rocket/android/authentication/presentation/AuthenticationNavigator.kt
2
6534
package chat.rocket.android.authentication.presentation import android.content.Intent import chat.rocket.android.R import chat.rocket.android.analytics.event.ScreenViewEvent import chat.rocket.android.authentication.domain.model.DeepLinkInfo import chat.rocket.android.authentication.ui.AuthenticationActivity import chat.rocket.android.main.ui.MainActivity import chat.rocket.android.server.ui.changeServerIntent import chat.rocket.android.util.extensions.addFragment import chat.rocket.android.util.extensions.addFragmentBackStack import chat.rocket.android.util.extensions.toPreviousView import chat.rocket.android.webview.ui.webViewIntent class AuthenticationNavigator(internal val activity: AuthenticationActivity) { private var savedDeepLinkInfo: DeepLinkInfo? = null fun saveDeepLinkInfo(deepLinkInfo: DeepLinkInfo) { savedDeepLinkInfo = deepLinkInfo } fun toOnBoarding() { activity.addFragment( ScreenViewEvent.OnBoarding.screenName, R.id.fragment_container, allowStateLoss = true ) { chat.rocket.android.authentication.onboarding.ui.newInstance() } } fun toSignInToYourServer(deepLinkInfo: DeepLinkInfo? = null, addToBackStack: Boolean = true) { if (addToBackStack) { activity.addFragmentBackStack( ScreenViewEvent.Server.screenName, R.id.fragment_container ) { chat.rocket.android.authentication.server.ui.newInstance(deepLinkInfo) } } else { activity.addFragment( ScreenViewEvent.Server.screenName, R.id.fragment_container, allowStateLoss = true ) { chat.rocket.android.authentication.server.ui.newInstance(deepLinkInfo) } } } fun toLoginOptions( serverUrl: String, state: String? = null, facebookOauthUrl: String? = null, githubOauthUrl: String? = null, googleOauthUrl: String? = null, linkedinOauthUrl: String? = null, gitlabOauthUrl: String? = null, wordpressOauthUrl: String? = null, casLoginUrl: String? = null, casToken: String? = null, casServiceName: String? = null, casServiceNameTextColor: Int = 0, casServiceButtonColor: Int = 0, customOauthUrl: String? = null, customOauthServiceName: String? = null, customOauthServiceNameTextColor: Int = 0, customOauthServiceButtonColor: Int = 0, samlUrl: String? = null, samlToken: String? = null, samlServiceName: String? = null, samlServiceNameTextColor: Int = 0, samlServiceButtonColor: Int = 0, totalSocialAccountsEnabled: Int = 0, isLoginFormEnabled: Boolean = true, isNewAccountCreationEnabled: Boolean = true, deepLinkInfo: DeepLinkInfo? = null ) { activity.addFragmentBackStack( ScreenViewEvent.LoginOptions.screenName, R.id.fragment_container ) { chat.rocket.android.authentication.loginoptions.ui.newInstance( serverUrl, state, facebookOauthUrl, githubOauthUrl, googleOauthUrl, linkedinOauthUrl, gitlabOauthUrl, wordpressOauthUrl, casLoginUrl, casToken, casServiceName, casServiceNameTextColor, casServiceButtonColor, customOauthUrl, customOauthServiceName, customOauthServiceNameTextColor, customOauthServiceButtonColor, samlUrl, samlToken, samlServiceName, samlServiceNameTextColor, samlServiceButtonColor, totalSocialAccountsEnabled, isLoginFormEnabled, isNewAccountCreationEnabled, deepLinkInfo ) } } fun toTwoFA(username: String, password: String) { activity.addFragmentBackStack(ScreenViewEvent.TwoFa.screenName, R.id.fragment_container) { chat.rocket.android.authentication.twofactor.ui.newInstance(username, password) } } fun toCreateAccount() { activity.addFragmentBackStack(ScreenViewEvent.SignUp.screenName, R.id.fragment_container) { chat.rocket.android.authentication.signup.ui.newInstance() } } fun toLogin(serverUrl: String) { activity.addFragmentBackStack(ScreenViewEvent.Login.screenName, R.id.fragment_container) { chat.rocket.android.authentication.login.ui.newInstance(serverUrl) } } fun toForgotPassword() { activity.addFragmentBackStack( ScreenViewEvent.ResetPassword.screenName, R.id.fragment_container ) { chat.rocket.android.authentication.resetpassword.ui.newInstance() } } fun toPreviousView() { activity.toPreviousView() } fun toRegisterUsername(userId: String, authToken: String) { activity.addFragmentBackStack( ScreenViewEvent.RegisterUsername.screenName, R.id.fragment_container ) { chat.rocket.android.authentication.registerusername.ui.newInstance(userId, authToken) } } fun toWebPage(url: String, toolbarTitle: String? = null) { activity.startActivity(activity.webViewIntent(url, toolbarTitle)) activity.overridePendingTransition(R.anim.slide_up, R.anim.hold) } fun toChatList(serverUrl: String) { activity.startActivity(activity.changeServerIntent(serverUrl)) activity.finish() } fun toChatList(passedDeepLinkInfo: DeepLinkInfo? = null) { val deepLinkInfo = passedDeepLinkInfo ?: savedDeepLinkInfo savedDeepLinkInfo = null if (deepLinkInfo != null) { activity.startActivity(Intent(activity, MainActivity::class.java).also { it.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP it.putExtra( chat.rocket.android.authentication.domain.model.DEEP_LINK_INFO_KEY, deepLinkInfo ) }) } else { activity.startActivity(Intent(activity, MainActivity::class.java)) } activity.finish() } }
mit
fd3a93ba8d1c496fcce611675e3b1dfa
35.099448
99
0.630701
5.181602
false
false
false
false
UnderMybrella/Visi
src/main/kotlin/org/abimon/visi/collections/LateArray.kt
1
2090
package org.abimon.visi.collections class LateArray<T : Any> constructor(private val backing: Array<T?>, override val size: Int): List<T> { companion object { inline operator fun <reified T : Any> invoke(size: Int): LateArray<T> = LateArray(Array(size, { null as T? }), size) } override fun contains(element: T): Boolean = element in backing override fun containsAll(elements: Collection<T>): Boolean = elements.all { t -> t in backing } override fun get(index: Int): T = backing[index] ?: throw UninitializedPropertyAccessException() override fun indexOf(element: T): Int = backing.indexOf(element) override fun isEmpty(): Boolean = size == 0 override fun iterator(): Iterator<T> = object : Iterator<T> { var index: Int = 0 override fun hasNext(): Boolean = index < size override fun next(): T = this@LateArray[index++] } override fun lastIndexOf(element: T): Int = backing.lastIndexOf(element) override fun listIterator(): ListIterator<T> = listIterator(0) override fun listIterator(index: Int): ListIterator<T> = object : ListIterator<T> { var currIndex: Int = index override fun previousIndex(): Int = currIndex - 1 override fun hasNext(): Boolean = currIndex < size override fun hasPrevious(): Boolean = currIndex > 0 override fun next(): T = this@LateArray[currIndex++] override fun previous(): T = this@LateArray[currIndex--] override fun nextIndex(): Int = currIndex + 1 } override fun subList(fromIndex: Int, toIndex: Int): List<T> = backing.copyOfRange(fromIndex, toIndex).map { t -> t ?: throw UninitializedPropertyAccessException() } operator fun set(index: Int, element: T): Unit = backing.set(index, element) fun finalise(): Array<T> { if(backing.any { t -> t == null }) throw UninitializedPropertyAccessException() return backing.requireNoNulls() } }
mit
e191087cd44c7bc050cf9e63a90a639f
35.684211
168
0.622488
4.696629
false
false
false
false
nickthecoder/tickle
tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/action/movement/Accelerate.kt
1
1353
/* Tickle Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.tickle.action.movement import org.joml.Vector2d import uk.co.nickthecoder.tickle.Game import uk.co.nickthecoder.tickle.action.Action open class Accelerate( val velocity: Vector2d, val acceleration: Vector2d) : Action { private var previousTime = Game.instance.seconds override fun begin(): Boolean { previousTime = Game.instance.seconds return super.begin() } override fun act(): Boolean { val diff = Game.instance.seconds - previousTime velocity.x += acceleration.x * diff velocity.y += acceleration.y * diff previousTime = Game.instance.seconds return false } }
gpl-3.0
f1c8af35b8ee934f934b32bdee1f10dc
29.066667
69
0.728012
4.322684
false
false
false
false
itachi1706/CheesecakeUtilities
app/src/main/java/com/itachi1706/cheesecakeutilities/modules/ordCountdown/json/GCalHoliday.kt
1
588
package com.itachi1706.cheesecakeutilities.modules.ordCountdown.json /** * Created by Kenneth on 15/10/2017. * for com.itachi1706.cheesecakeutilities.modules.ORDCountdown.json in CheesecakeUtilities */ class GCalHoliday { val startYear: String? = null val endYear: String? = null val yearRange: String? = null val timestamp: String? = null val msg: String? = null val size: Int = 0 val error: Int = 0 val isCache: Boolean = false val output: Array<GCalHolidayItem>? = null val timestampLong: Long get() = timestamp?.toLong() ?: 0 }
mit
14f8e9f42846022379521d56b8305514
24.565217
90
0.683673
3.868421
false
false
false
false
burntcookie90/Sleep-Cycle-Alarm
mobile/src/main/kotlin/io/dwak/sleepcyclealarm/MainActivity.kt
1
2913
package io.dwak.sleepcyclealarm import android.app.TimePickerDialog import android.content.Intent import android.os.Bundle import android.provider.AlarmClock import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import butterknife.bindView import io.dwak.sleepcyclealarm.extension.fromDate import io.dwak.sleepcyclealarm.extension.hourOfDay import io.dwak.sleepcyclealarm.extension.minute import io.dwak.sleepcyclealarm.extension.navigateTo import io.dwak.sleepcyclealarm.ui.options.OptionsFragment import io.dwak.sleepcyclealarm.ui.times.WakeUpTimesFragment import java.util.ArrayList import java.util.Calendar import java.util.Date public class MainActivity : AppCompatActivity(), OptionsFragment.OptionsFragmentInteractionListener, WakeUpTimesFragment.WakeUpTimesFragmentListener { val toolbar : Toolbar by bindView(R.id.toolbar) override fun onCreate(savedInstanceState : Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) navigateTo(OptionsFragment.newInstance(), addToBackStack = false) } override fun navigateToWakeUpTimes(sleepNow : Boolean) { when { sleepNow -> { navigateTo(WakeUpTimesFragment.newInstance(sleepNow), tag = "SleepNow") { setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right) } } else -> { with(Calendar.getInstance()) { TimePickerDialog(this@MainActivity, { v, h, m-> hourOfDay = h minute = m navigateTo(WakeUpTimesFragment.newInstance(time), tag = "SleepLater") { setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right) } }, hourOfDay, minute, false) .show() } } } } override fun setAlarm(wakeUpTime : Date) { val calendar = Calendar.getInstance().fromDate(wakeUpTime) with(Intent(AlarmClock.ACTION_SET_ALARM)) { putExtra(AlarmClock.EXTRA_MESSAGE, ""); putExtra(AlarmClock.EXTRA_HOUR, calendar.hourOfDay); putExtra(AlarmClock.EXTRA_MINUTES, calendar.minute); startActivity(this); } } }
apache-2.0
cde27f57887643288958a7f7f3babbbc
40.628571
112
0.565053
5.475564
false
false
false
false
Blankj/AndroidUtilCode
feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/bar/status/fragment/BarStatusFragmentActivity.kt
1
3545
package com.blankj.utilcode.pkg.feature.bar.status.fragment import android.content.Context import android.content.Intent import android.os.Bundle import android.view.View import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentPagerAdapter import androidx.viewpager.widget.ViewPager import com.blankj.common.activity.CommonActivity import com.blankj.utilcode.pkg.R import com.google.android.material.bottomnavigation.BottomNavigationView import kotlinx.android.synthetic.main.bar_status_fragment_activity.* import java.util.* /** * ``` * author: Blankj * blog : http://blankj.com * time : 2017/05/27 * desc : demo about BarUtils * ``` */ class BarStatusFragmentActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, BarStatusFragmentActivity::class.java) context.startActivity(starter) } } private val itemIds = intArrayOf( R.id.barStatusFragmentNavigationColor, R.id.barStatusFragmentNavigationAlpha, R.id.barStatusFragmentNavigationImageView, R.id.barStatusFragmentNavigationCustom ) private val mFragmentList = ArrayList<androidx.fragment.app.Fragment>() private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener l@{ item -> when (item.itemId) { R.id.barStatusFragmentNavigationColor -> { barStatusFragmentVp.currentItem = 0 return@l true } R.id.barStatusFragmentNavigationAlpha -> { barStatusFragmentVp.currentItem = 1 return@l true } R.id.barStatusFragmentNavigationImageView -> { barStatusFragmentVp.currentItem = 2 return@l true } R.id.barStatusFragmentNavigationCustom -> { barStatusFragmentVp.currentItem = 3 return@l true } else -> false } } override fun isSwipeBack(): Boolean { return false } override fun bindLayout(): Int { return R.layout.bar_status_fragment_activity } override fun initView(savedInstanceState: Bundle?, contentView: View?) { super.initView(savedInstanceState, contentView) mFragmentList.add(BarStatusFragmentColor.newInstance()) mFragmentList.add(BarStatusFragmentAlpha.newInstance()) mFragmentList.add(BarStatusFragmentImageView.newInstance()) mFragmentList.add(BarStatusFragmentCustom.newInstance()) barStatusFragmentVp.offscreenPageLimit = mFragmentList.size - 1 barStatusFragmentVp.adapter = object : FragmentPagerAdapter(supportFragmentManager) { override fun getItem(position: Int): Fragment { return mFragmentList[position] } override fun getCount(): Int { return mFragmentList.size } } barStatusFragmentVp.addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {} override fun onPageSelected(position: Int) { barStatusFragmentNav.selectedItemId = itemIds[position] } override fun onPageScrollStateChanged(state: Int) {} }) barStatusFragmentNav.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener) } }
apache-2.0
fddbac9ee19e98cf3a9c6ef6fd1bfb52
34.09901
117
0.67024
5.609177
false
false
false
false
chrsep/Kingfish
app/src/main/java/com/directdev/portal/features/finance/FinancesRecyclerAdapter.kt
1
4907
package com.directdev.portal.features.finance import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.directdev.portal.R import com.directdev.portal.models.FinanceModel import com.directdev.portal.utils.formatToRupiah import io.realm.OrderedRealmCollection import io.realm.Realm import io.realm.RealmRecyclerViewAdapter import kotlinx.android.synthetic.main.item_finances.view.* import kotlinx.android.synthetic.main.item_finances_header.view.* import org.joda.time.DateTime import org.joda.time.DateTimeComparator import org.joda.time.Days import org.joda.time.format.DateTimeFormat /**------------------------------------------------------------------------------------------------- * * Adapter for list of bills in finance fragment. It includes a header that shows the total number * of incoming bills. * *------------------------------------------------------------------------------------------------*/ // TODO: REFACTOR | This list is reversed, and i forgot why, further investigation needed // This recyclerView is in reversed order, so we put the header (The one that shows unpaid bill) at // the end of the list to make it show on top class FinancesRecyclerAdapter( val realm: Realm, data: OrderedRealmCollection<FinanceModel>?, autoUpdate: Boolean) : RealmRecyclerViewAdapter<FinanceModel, FinancesRecyclerAdapter.ViewHolder>(data, autoUpdate) { private val HEADER = 1 override fun getItemCount() = super.getItemCount() + 1 // Normally for header, position==0 will be used (So that it shows on top), since this is // reversed, we will want to put the header on the bottom. override fun getItemViewType(position: Int) = if (position == data?.size) HEADER else super.getItemViewType(position) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = if (viewType == HEADER) HeaderViewHolder(realm, LayoutInflater.from(parent.context).inflate(R.layout.item_finances_header, parent, false)) else NormalViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_finances, parent, false)) override fun onBindViewHolder(holder: ViewHolder, position: Int) { if (position == data?.size) holder.bindData(getItem(position - 1) as FinanceModel) else holder.bindData(getItem(position) as FinanceModel) } abstract class ViewHolder(view: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(view) { abstract fun bindData(item: FinanceModel) } private class NormalViewHolder(view: View) : ViewHolder(view) { override fun bindData(item: FinanceModel) { val date = DateTime .parse(item.dueDate.substring(0, 10)) .toString(DateTimeFormat.forPattern("dd MMM ''yy")) val amount = item.chargeAmount.formatToRupiah() itemView.finance_description.text = item.description itemView.finance_date.text = date itemView.finance_amount.text = amount if (DateTime.parse(item.dueDate.substring(0, 10)).isAfterNow) { itemView.finance_passed.visibility = View.GONE itemView.finance_upcoming.visibility = View.VISIBLE } else { itemView.finance_passed.visibility = View.VISIBLE itemView.finance_upcoming.visibility = View.GONE } } } private class HeaderViewHolder(val realm: Realm, view: View) : ViewHolder(view) { override fun bindData(item: FinanceModel) { val totalBillText: String val nextChargeText: String val data = realm.where(FinanceModel::class.java).findAll() val closestDate = data .map { DateTime.parse(it.dueDate.substring(0, 10)) } .filter { it.isAfterNow } .sortedWith(DateTimeComparator.getInstance()) if (closestDate.isNotEmpty()) { val nextChargeDate = closestDate[0].toString("dd MMMM") val daysCount = Days .daysBetween(closestDate[0], DateTime.now()) .days .toString() .substring(1) val totalBill = data .filter { DateTime.parse(it.dueDate.substring(0, 10)).isAfterNow } .sumBy { it.chargeAmount.toDouble().toInt() } totalBillText = "Rp. $totalBill" nextChargeText = "$nextChargeDate ($daysCount days)" } else { totalBillText = "Rp. 0,-" nextChargeText = "-" } itemView.total_amount.text = totalBillText itemView.next_charge.text = nextChargeText } } }
gpl-3.0
aff6057b659b8c7566528e1bbc184d4e
44.444444
130
0.614836
4.902098
false
false
false
false
angcyo/RLibrary
uiview/src/main/java/com/angcyo/uiview/widget/BlockSeekBar.kt
1
8822
package com.angcyo.uiview.widget import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.RectF import android.graphics.drawable.Drawable import android.support.v4.view.MotionEventCompat import android.util.AttributeSet import android.view.MotionEvent import android.view.View import com.angcyo.uiview.R import com.angcyo.uiview.kotlin.density import com.angcyo.uiview.kotlin.getDrawable /** * Created by angcyo on 2017-09-13. */ class BlockSeekBar(context: Context, attributeSet: AttributeSet? = null) : View(context, attributeSet) { /**不规则高度列表*/ private val heightList = listOf(0.5f, 0.7f, 0.9f, 1.0f, 0.8f, 0.6f, 0.3f, 0.7f, 0.8f) private val tempRectF = RectF() private val clipRectF = RectF() private val paint by lazy { Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL } } /**每一个的宽度*/ private var blockWidth = 4 * density /**圆角大小*/ private var roundSize = 4 * density /**空隙大小*/ private var spaceSize = 2 * density /**滑块*/ private var sliderDrawable: Drawable? = null var blockProgressColor: Int = Color.YELLOW var blockProgressBgColor: Int = Color.WHITE /**当前的进度, 非百分比*/ var blockProgress: Int = 0 set(value) { field = when { value < 0 -> 0 value > blockMaxProgress -> blockMaxProgress else -> value } postInvalidate() } /**最大刻度, 百分比计算的分母*/ var blockMaxProgress: Int = 100 set(value) { field = value postInvalidate() } /**滑块的最小宽度, 非百分比*/ var blockMinWidth: Int = 20 set(value) { field = when { value < 10 -> 10 value > blockMaxProgress -> blockMaxProgress - 10 else -> value } postInvalidate() } init { sliderDrawable = getDrawable(R.drawable.base_slider)?.apply { setBounds(0, 0, intrinsicWidth, intrinsicHeight) } val typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.BlockSeekBar) blockProgress = typedArray.getInt(R.styleable.BlockSeekBar_r_block_progress, blockProgress) blockMaxProgress = typedArray.getInt(R.styleable.BlockSeekBar_r_block_max_progress, blockMaxProgress) blockMinWidth = typedArray.getInt(R.styleable.BlockSeekBar_r_block_min_width, blockMinWidth) blockProgressColor = typedArray.getColor(R.styleable.BlockSeekBar_r_block_progress_color, blockProgressColor) blockProgressBgColor = typedArray.getColor(R.styleable.BlockSeekBar_r_block_progress_bg_color, blockProgressBgColor) val drawable = typedArray.getDrawable(R.styleable.BlockSeekBar_r_slider_drawable) if (drawable != null) { sliderDrawable = drawable.apply { setBounds(0, 0, intrinsicWidth, intrinsicHeight) } } typedArray.recycle() } //滑块的高度 private val sliderHeight: Int get() { if (sliderDrawable == null) { return 0 } return sliderDrawable!!.intrinsicHeight } private val sliderWidth: Int get() { if (sliderDrawable == null) { return 0 } return sliderDrawable!!.intrinsicWidth } //滑块允许绘制的高度 private val blockDrawHeight: Int get() { return measuredHeight - sliderHeight - paddingTop - paddingBottom } //滑块允许绘制的宽度 private val blockDrawWidth: Int get() { return sliderDrawWidth - sliderWidth } private val sliderDrawWidth: Int get() { return measuredWidth - paddingLeft - paddingRight } private val sliderDrawLeft: Float get() { return drawProgress * blockDrawWidth } private val blockDrawLeft: Float get() { return paddingLeft.toFloat() + sliderWidth / 2 } /**按照百分比, 转换的进度*/ private val drawProgress: Float get() { return Math.min(blockProgress * 1f / blockMaxProgress, 1f) } //最小绘制宽度的进度比 private val drawMinBlockProgress: Float get() { return Math.min(blockMinWidth * 1f / blockMaxProgress, 1f) } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) if (isInEditMode) { canvas.drawColor(Color.DKGRAY) } //绘制标准柱子 drawBlock(canvas, blockProgressBgColor) //绘制进度柱子 canvas.save() val left = blockDrawLeft + blockDrawWidth * drawProgress clipRectF.set(left, 0f, left + drawMinBlockProgress * blockDrawWidth, blockDrawHeight.toFloat() + paddingTop) canvas.clipRect(clipRectF) drawBlock(canvas, blockProgressColor) canvas.restore() //绘制滑块 canvas.save() canvas.translate(paddingLeft.toFloat() + sliderDrawLeft, blockDrawHeight.toFloat() + paddingTop) sliderDrawable?.draw(canvas) canvas.restore() } private fun drawBlock(canvas: Canvas, color: Int) { var left = blockDrawLeft var index = 0 while (left + blockWidth < measuredWidth - sliderWidth / 2 - paddingRight) { paint.color = color val blockHeight = blockDrawHeight * heightList[index.rem(heightList.size)] val top = (blockDrawHeight - blockHeight) / 2 + paddingTop tempRectF.set(left, top, left + blockWidth, top + blockHeight) canvas.drawRoundRect(tempRectF, roundSize, roundSize, paint) left += blockWidth + spaceSize index++ } } //touch处理 override fun onTouchEvent(event: MotionEvent): Boolean { val action = MotionEventCompat.getActionMasked(event) val eventX = event.x //L.e("call: onTouchEvent([event])-> " + action + " x:" + eventX); when (action) { MotionEvent.ACTION_DOWN -> { //L.e("call: onTouchEvent([event])-> DOWN:" + " x:" + eventX); // isTouchDown = true // notifyListenerStartTouch() blockSeekListener?.onTouchStart(this) calcProgress(eventX) parent.requestDisallowInterceptTouchEvent(true) } MotionEvent.ACTION_MOVE -> calcProgress(eventX) MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { // isTouchDown = false // notifyListenerStopTouch() blockSeekListener?.onTouchEnd(this) parent.requestDisallowInterceptTouchEvent(false) } } return true } /** * 根据touch坐标, 计算进度 */ private fun calcProgress(touchX: Float) { //事件发生在柱子中的比率 val scale = (touchX - blockDrawLeft) / blockDrawWidth val progress = (scale * blockMaxProgress).toInt() if (progress <= blockMaxProgress - blockMinWidth) { //将比率转换成进度 blockProgress = progress //L.e("call: onSeekChange -> $blockProgress ${blockProgress + blockMinWidth}") blockSeekListener?.onSeekChange(this, blockProgress, blockProgress + blockMinWidth) postInvalidate() } // val x = touchX - paddingLeft.toFloat() - (mThumbWidth / 2).toFloat() // val old = this.curProgress // this.curProgress = ensureProgress((x / getMaxLength() * maxProgress).toInt()) // if (old != curProgress) { // notifyListenerProgress(true) // } } fun setBlockProgressAndNotify(progress: Int) { blockProgress = progress blockSeekListener?.onSeekChange(this, blockProgress, blockProgress + blockMinWidth) } /**事件监听*/ var blockSeekListener: OnBlockSeekListener? = null public abstract class OnBlockSeekListener { public open fun onTouchStart(view: BlockSeekBar) { } public open fun onSeekChange(view: BlockSeekBar, startX: Int /*非百分比*/, endX: Int) { } public open fun onTouchEnd(view: BlockSeekBar) { } } }
apache-2.0
0c286f776f08543d121a3ddf7141f295
29.910112
124
0.584742
4.730705
false
false
false
false