repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
GKZX-HN/MyGithub | app/src/main/java/com/gkzxhn/mygithub/base/BaseFragment.kt | 1 | 2752 | package com.gkzxhn.balabala.base
import android.app.Activity
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.trello.rxlifecycle2.components.support.RxFragment
/**
* Created by 方 on 2017/10/19.
*/
abstract class BaseFragment :RxFragment(){
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = initView(inflater, container, savedInstanceState)
setupComponent()
isInit = true
return view
}
protected open fun setupComponent(){}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initStatusBar()
initToolBar()
initContentView()
Log.i(javaClass.simpleName, "onViewCreated : $userVisibleHint")
}
override fun onResume() {
Log.i(javaClass.simpleName, "onResume : $userVisibleHint")
if (userVisibleHint && isFirst) {
onVisible()
isFirst = false
}
super.onResume()
}
override fun onDestroy() {
isInit = false
super.onDestroy()
}
private var isFirst = true
private var isInit = false
override fun setUserVisibleHint(isVisibleToUser: Boolean) {
Log.i(javaClass.simpleName, "setUserVisibleHint : ${isVisibleToUser}")
if (isVisibleToUser && isInit && isFirst) {
isFirst = false
onVisible()
}
super.setUserVisibleHint(isVisibleToUser)
}
open protected fun onVisible(){
Log.i(javaClass.simpleName, "onVisible")
}
/**
* 初始化内容视图
*/
abstract fun initContentView()
open fun getToolbar(): Toolbar? = null
open fun getStatusBar(): View? = null
abstract fun initView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?) : View
open fun initToolBar() {
getToolbar()?.let{
try {
(activity as AppCompatActivity).setSupportActionBar(it)
} catch(e: Exception) {
}
}
}
private fun initStatusBar() {
getStatusBar()?.let {
it.layoutParams.height = getStatusHeight(activity)
}
}
fun getStatusHeight(activity: Activity): Int {
// 获得状态栏高度
val resourceId = activity.resources.getIdentifier("status_bar_height", "dimen", "android")
val statusBarHeight = activity.resources.getDimensionPixelSize(resourceId)
return statusBarHeight
}
} | gpl-3.0 | 772e3dda93aa6635ec34341a93f0baa0 | 27.072165 | 117 | 0.64842 | 4.958106 | false | false | false | false |
sjnyag/stamp | app/src/main/java/com/sjn/stamp/utils/AlbumArtHelper.kt | 1 | 9607 | package com.sjn.stamp.utils
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Typeface
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.support.v4.media.MediaBrowserCompat
import android.view.View
import android.widget.ImageView
import com.sjn.stamp.R
import com.sjn.stamp.ui.MediaBrowsable
import com.sjn.stamp.ui.custom.TextDrawable
import java.util.*
object AlbumArtHelper {
private const val IMAGE_VIEW_ALBUM_ART_TYPE_BITMAP = "bitmap"
private const val IMAGE_VIEW_ALBUM_ART_TYPE_TEXT = "text"
fun readBitmapSync(context: Context, url: String?, title: String?): Bitmap {
return readBitmapSync(context, Uri.parse(url), title)
}
fun readBitmapSync(context: Context, url: Uri?, title: String?): Bitmap {
return try {
readBitmap(context, url) ?: AlbumArtHelper.createTextBitmap(title)
} catch (e: Exception) {
AlbumArtHelper.createTextBitmap(title)
}
}
fun readBitmapAsync(context: Context, url: String?, title: String?, onLoad: (Bitmap) -> Unit) {
Handler(Looper.getMainLooper()).post {
onLoad(readBitmapSync(context, url, title))
}
}
fun readBitmapAsync(context: Context, url: Uri?, title: String?, onLoad: (Bitmap) -> Unit) {
Handler(Looper.getMainLooper()).post {
onLoad(readBitmapSync(context, url, title))
}
}
fun reload(context: Context, view: ImageView, imageType: String?, artUrl: String?, text: String?) {
view.setTag(R.id.image_view_album_art_url, artUrl)
if (imageType == "bitmap") {
view.loadBitmap(context, artUrl, text)
} else if (imageType == "text") {
setPlaceHolder(context, view, text)
}
}
fun update(context: Context?, view: ImageView?, artUrl: String?, text: CharSequence?) {
context?.let { _context ->
view?.let { _view ->
artUrl?.let { _artUrl ->
updateAlbumArtImpl(_context, _view, _artUrl, text?.toString() ?: "")
}
}
}
}
fun searchAndUpdate(context: Context, view: ImageView, title: String, query: String, mediaBrowsable: MediaBrowsable?) {
if (view.getTag(R.id.image_view_album_art_query) == query && view.getTag(R.id.image_view_album_art_query_result) != null) {
AlbumArtHelper.update(context, view, view.getTag(R.id.image_view_album_art_query_result).toString(), title)
return
}
view.setTag(R.id.image_view_album_art_query, query)
view.setTag(R.id.image_view_album_art_query_result, null)
AlbumArtHelper.setPlaceHolder(context, view, title)
mediaBrowsable?.searchMediaItems(query, null, object : MediaBrowserCompat.SearchCallback() {
override fun onSearchResult(query: String, extras: Bundle?, items: List<MediaBrowserCompat.MediaItem>) {
updateByExistingAlbumArt(context, view, title, query, items)
}
})
}
private fun setPlaceHolder(context: Context?, view: ImageView?, text: String?) {
context?.runOnUiThread {
view?.setTextDrawable(text)
}
}
private fun updateByExistingAlbumArt(context: Context, view: ImageView, text: String, query: String, items: List<MediaBrowserCompat.MediaItem>) {
if (view.getTag(R.id.image_view_album_art_query) != query) {
return
}
if (items.isEmpty()) {
setPlaceHolder(context, view, text)
return
}
Thread(Runnable {
view.loadBitmap(context, items.first().description.iconUri.toString()) {
if (items.size > 1) {
updateByExistingAlbumArt(context, view, text, query, items.drop(1))
}
}
}).start()
}
private fun updateAlbumArtImpl(context: Context, view: ImageView, artUrl: String, text: String) {
view.setTag(R.id.image_view_album_art_url, artUrl)
if (artUrl.isEmpty()) {
setPlaceHolder(context, view, text)
return
}
Thread(Runnable {
view.loadBitmap(context, artUrl, text)
}).start()
}
private fun ImageView.setTextDrawable(text: String?) {
setTag(R.id.image_view_album_art_type, IMAGE_VIEW_ALBUM_ART_TYPE_TEXT)
setTag(R.id.image_view_album_art_text, text)
setLayerType(View.LAYER_TYPE_SOFTWARE, null)
setImageDrawable(createTextDrawable(text ?: ""))
}
private fun ImageView.setAlbumArtBitmap(bitmap: Bitmap) {
setTag(R.id.image_view_album_art_type, IMAGE_VIEW_ALBUM_ART_TYPE_BITMAP)
setImageBitmap(bitmap)
}
private fun ImageView.loadBitmap(context: Context, artUrl: String?, onNothing: () -> Unit) {
var bitmap: Bitmap? = null
try {
readBitmap(context, Uri.parse(artUrl))?.let {
bitmap = it
}
} catch (e: Exception) {
}
bitmap?.let {
context.runOnUiThread {
setTag(R.id.image_view_album_art_url, artUrl)
setTag(R.id.image_view_album_art_query_result, artUrl)
setAlbumArtBitmap(it)
}
} ?: run {
onNothing()
}
}
private fun ImageView.loadBitmap(context: Context, artUrl: String?, text: String?) {
loadBitmap(context, artUrl) { setPlaceHolder(context, this, text) }
}
private fun createTextBitmap(text: CharSequence?) =
toBitmap(createTextDrawable(text?.toString() ?: ""))
private fun createTextDrawable(text: String): TextDrawable = TextDrawable.builder()
.beginConfig()
.useFont(Typeface.DEFAULT)
.bold()
.toUpperCase()
.endConfig()
.rect()
.build(if (text.isEmpty()) "" else text[0].toString(), ColorGenerator.MATERIAL.getColor(text))
fun toBitmap(drawable: Drawable): Bitmap {
if (drawable is BitmapDrawable && drawable.bitmap != null) {
return drawable.bitmap
}
val width = if (drawable.intrinsicWidth > 0) drawable.intrinsicWidth else 96
val height = if (drawable.intrinsicHeight > 0) drawable.intrinsicHeight else 96
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas()
canvas.setBitmap(bitmap)
drawable.setBounds(0, 0, width, height)
drawable.draw(canvas)
return bitmap
}
private fun readBitmap(context: Context, uri: Uri?) = getThumbnail(context, uri)
private fun getThumbnail(context: Context, uri: Uri?, size: Int = 256): Bitmap? {
if (uri == null) {
return null
}
val onlyBoundsOptions = BitmapFactory.Options().apply {
inJustDecodeBounds = true
inPreferredConfig = Bitmap.Config.ARGB_8888
}
context.contentResolver.openInputStream(uri).use {
BitmapFactory.decodeStream(it, null, onlyBoundsOptions)
}
if (onlyBoundsOptions.outWidth == -1 || onlyBoundsOptions.outHeight == -1) {
return null
}
val originalSize = if (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) onlyBoundsOptions.outHeight else onlyBoundsOptions.outWidth
return context.contentResolver.openInputStream(uri).use {
BitmapFactory.decodeStream(it, null, BitmapFactory.Options().apply {
inSampleSize = if (originalSize > size) originalSize / size else 1
inPreferredConfig = Bitmap.Config.ARGB_8888
})
}
}
private class ColorGenerator private constructor(private val colors: List<Int>) {
private val random: Random = Random(System.currentTimeMillis())
val randomColor: Int
get() = colors[random.nextInt(colors.size)]
internal fun getColor(key: Any?): Int = if (key == null) colors[0] else colors[Math.abs(key.hashCode()) % colors.size]
companion object {
internal var DEFAULT: ColorGenerator
internal var MATERIAL: ColorGenerator
init {
DEFAULT = create(Arrays.asList(
-0xe9c9c,
-0xa7aa7,
-0x65bc2,
-0x1b39d2,
-0x98408c,
-0xa65d42,
-0xdf6c33,
-0x529d59,
-0x7fa87f
))
MATERIAL = create(Arrays.asList(
-0x1a8c8d,
-0xf9d6e,
-0x459738,
-0x6a8a33,
-0x867935,
-0x9b4a0a,
-0xb03c09,
-0xb22f1f,
-0xb24954,
-0x7e387c,
-0x512a7f,
-0x759b,
-0x2b1ea9,
-0x2ab1,
-0x48b3,
-0x5e7781,
-0x6f5b52
))
}
fun create(colorList: List<Int>): ColorGenerator {
return ColorGenerator(colorList)
}
}
}
} | apache-2.0 | 01a7f4b6aef08e53300673dd22619233 | 35.953846 | 149 | 0.58041 | 4.296512 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveAllArgumentNamesIntention.kt | 2 | 3380 | // 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 org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.completion.ArgumentThatCanBeUsedWithoutName
import org.jetbrains.kotlin.idea.completion.collectAllArgumentsThatCanBeUsedWithoutName
import org.jetbrains.kotlin.idea.base.psi.copied
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.calls.components.isVararg
class RemoveAllArgumentNamesIntention : SelfTargetingIntention<KtCallElement>(
KtCallElement::class.java,
KotlinBundle.lazyMessage("remove.all.argument.names")
) {
override fun isApplicableTo(element: KtCallElement, caretOffset: Int): Boolean {
val arguments = element.valueArgumentList?.arguments ?: return false
if (arguments.count { it.isNamed() } < 2) return false
val resolvedCall = element.resolveToCall() ?: return false
return collectAllArgumentsThatCanBeUsedWithoutName(resolvedCall).any()
}
override fun applyTo(element: KtCallElement, editor: Editor?) {
val argumentList = element.valueArgumentList ?: return
val resolvedCall = element.resolveToCall() ?: return
argumentList.removeArgumentNames(collectAllArgumentsThatCanBeUsedWithoutName(resolvedCall))
}
companion object {
fun KtValueArgumentList.removeArgumentNames(
argumentsThatCanBeUsedWithoutName: List<ArgumentThatCanBeUsedWithoutName>,
removeOnlyLastArgumentName: Boolean = false
) {
val lastArgument = argumentsThatCanBeUsedWithoutName.lastOrNull()?.argument
argumentsThatCanBeUsedWithoutName.reversed().forEach { (argument, parameter) ->
val newArguments = if (!argument.isNamed() || (removeOnlyLastArgumentName && argument != lastArgument)) {
listOf(argument.copied())
} else {
createArgumentWithoutName(argument, parameter)
}
removeArgument(argument)
newArguments.reversed().forEach { addArgumentBefore(it, arguments.firstOrNull()) }
}
}
private fun createArgumentWithoutName(argument: KtValueArgument, parameter: ValueParameterDescriptor?): List<KtValueArgument> {
if (!argument.isNamed()) return listOf(argument.copied())
val argumentExpr = argument.getArgumentExpression() ?: return emptyList()
val psiFactory = KtPsiFactory(argument)
val isVararg = parameter?.isVararg ?: false
return when {
isVararg && argumentExpr is KtCollectionLiteralExpression ->
argumentExpr.getInnerExpressions().map { psiFactory.createArgument(it) }
isVararg && argumentExpr is KtCallExpression && argumentExpr.isArrayOfFunction() ->
argumentExpr.valueArguments.map { psiFactory.createArgument(it.getArgumentExpression()) }
else ->
listOf(psiFactory.createArgument(argumentExpr, null, isVararg))
}
}
}
}
| apache-2.0 | 6c9c0a9d8ddc9b236679bacd3bc464c5 | 52.650794 | 158 | 0.703846 | 5.614618 | false | false | false | false |
just-4-fun/holomorph | src/test/kotlin/just4fun/holomorph/mains/TypeIntercept.kt | 1 | 1449 | package just4fun.holomorph.mains
import just4fun.holomorph.EnclosedEntries
import just4fun.holomorph.Intercept
import just4fun.holomorph.Reflexion
import just4fun.holomorph.ValueInterceptor
import just4fun.holomorph.forms.DefaultFactory
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.shouldEqual
class TypeIntercept: Spek() { init {
given("") {
on("") {
class Interceptor: ValueInterceptor<Int> {
override fun intercept(value: String): Int? = 5
}
class Obj {
@Intercept(Interceptor::class) val a: Int = -1
val b: Int = -1
}
val rx = Reflexion(Obj::class)
val obj = rx.instanceFrom("{a:ok, b:ok}", DefaultFactory).valueOrThrow
val text = rx.instanceTo(obj, DefaultFactory)
it("Check results") {
shouldEqual(obj.a, 5)
shouldEqual(obj.b, 0)
shouldEqual(text, """{"a":5,"b":0}""")
}
}
on("") {
class Wrapper(val n: Int)
class Interceptor: ValueInterceptor<Int> {
val wrx = Reflexion(Wrapper::class)
override fun intercept(subEntries: EnclosedEntries, expectNames: Boolean): Int? = wrx.schema.fromEntries(subEntries, expectNames)!!.n
}
class Obj {
@Intercept(Interceptor::class) val a: Int = -1
val b: Int = -1
}
val rx = Reflexion(Obj::class)
val obj = rx.instanceFrom("{a:{n:5}, b:ok}", DefaultFactory).valueOrThrow
it("Check results") {
shouldEqual(obj.a, 5)
shouldEqual(obj.b, 0)
}
}
}
}
}
| apache-2.0 | 2a6d80b234664a80885f6ddf03c8584b | 23.982759 | 137 | 0.665286 | 3.21286 | false | false | false | false |
JStege1206/AdventOfCode | aoc-2018/src/main/kotlin/nl/jstege/adventofcode/aoc2018/days/Day06.kt | 1 | 3098 | package nl.jstege.adventofcode.aoc2018.days
import nl.jstege.adventofcode.aoccommon.days.Day
import nl.jstege.adventofcode.aoccommon.utils.Point
class Day06 : Day(title = "Chronal Coordinates") {
companion object Configuration {
private const val MAX_DISTANCE_SUM = 10000
}
override fun first(input: Sequence<String>): Any = input
.parse()
.let { (points, min, max) ->
min.createGridTo(max)
.mapNotNull { gridPoint -> points.findNearest(gridPoint) }
.groupBy { it.second }
.values
.asSequence()
.filter { gridPoints -> gridPoints.none { (point, _) -> point.onEdge(min, max) } }
.map { it.size }
.max() ?: 0
}
override fun second(input: Sequence<String>): Any = input
.parse()
.let { (points, min, max) ->
val xLimit = (MAX_DISTANCE_SUM - (max.x - min.x)) / points.size
val yLimit = (MAX_DISTANCE_SUM - (max.y - min.y)) / points.size
Point.of(min.x - xLimit, min.y - yLimit)
.createGridTo(Point.of(max.x + xLimit, max.y + yLimit))
.count { gp -> points.sumBy { p -> p.manhattan(gp) } < MAX_DISTANCE_SUM }
}
private fun Sequence<String>.parse(): Triple<List<Point>, Point, Point> {
var maxX = Int.MIN_VALUE
var maxY = Int.MIN_VALUE
var minX = Int.MAX_VALUE
var minY = Int.MAX_VALUE
return this@parse
.map { it.split(", ").map(String::toInt) }
.map { (x, y) ->
if (x > maxX) maxX = x
if (y > maxY) maxY = y
if (x < minX) minX = x
if (y < minY) minY = y
Point.of(x, y)
}
.toList()
.let { Triple(it, Point.of(minX, minY), Point.of(maxX, maxY)) }
}
private fun List<Point>.findNearest(origin: Point): Pair<Point, Point>? = this
.fold(
Closest(Pair(Point.ZERO_ZERO, Int.MAX_VALUE), false)
) { closest, destination ->
destination.manhattan(origin).let { distance ->
when {
distance < closest.coord.second -> Closest(destination to distance)
distance == closest.coord.second -> closest.apply { valid = false }
else -> closest
}
}
}
.takeIf { it.valid }
?.let { origin to it.coord.first }
private fun Point.onEdge(min: Point, max: Point): Boolean =
x == min.x || x == max.x || y == min.y || y == max.y
private fun Point.createGridTo(p: Point, including: Boolean = true): Sequence<Point> =
if (this == p) sequenceOf(this)
else (p.x - x + if (including) 1 else 0).let { width ->
var n = 0
generateSequence { Point.of(x + n % width, y + n / width).also { n++ } }
.take((p.y - y + if (including) 1 else 0) * width)
}
data class Closest(var coord: Pair<Point, Int>, var valid: Boolean = true)
}
| mit | b1a247338712125c6b09f6e166e04a8f | 37.725 | 98 | 0.516785 | 3.801227 | false | false | false | false |
ingokegel/intellij-community | plugins/yaml/src/org/jetbrains/yaml/annotator/YAMLInvalidBlockChildrenErrorAnnotator.kt | 4 | 6266 | // 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.yaml.annotator
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.Annotator
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.impl.source.tree.TreeUtil
import com.intellij.psi.templateLanguages.OuterLanguageElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtilCore
import com.intellij.psi.util.parentOfType
import com.intellij.refactoring.suggested.endOffset
import com.intellij.refactoring.suggested.startOffset
import org.jetbrains.annotations.Nls
import org.jetbrains.yaml.YAMLBundle
import org.jetbrains.yaml.YAMLTokenTypes
import org.jetbrains.yaml.YAMLUtil
import org.jetbrains.yaml.psi.YAMLAnchor
import org.jetbrains.yaml.psi.YAMLKeyValue
import org.jetbrains.yaml.psi.YAMLSequenceItem
import org.jetbrains.yaml.psi.YAMLValue
import org.jetbrains.yaml.psi.impl.YAMLBlockMappingImpl
import org.jetbrains.yaml.psi.impl.YAMLBlockSequenceImpl
import org.jetbrains.yaml.psi.impl.YAMLKeyValueImpl
import kotlin.math.min
private class YAMLInvalidBlockChildrenErrorAnnotator : Annotator {
override fun annotate(element: PsiElement, holder: AnnotationHolder) {
if (PsiTreeUtil.findChildrenOfType(element, OuterLanguageElement::class.java).isNotEmpty()) return
if (anotherErrorWillBeReported(element)) return
if (reportSameLineWarning(element, holder)) return
if (element is YAMLBlockMappingImpl) {
if (!isValidBlockMapChild(element.firstChild)) {
reportWholeElementProblem(holder, element, element.firstKeyValue.key ?: element.firstKeyValue)
return
}
element.children.firstOrNull { !isValidBlockMapChild(it) }?.let {
reportSubElementProblem(holder, YAMLBundle.message("inspections.invalid.child.in.block.mapping"), it)
}
checkIndent(element.keyValues.toList(), holder, YAMLBundle.message("inspections.invalid.key.indent"))
}
if (element is YAMLBlockSequenceImpl) {
if (!isValidBlockSequenceChild(element.firstChild)) {
reportWholeElementProblem(holder, element, element.items.firstOrNull() ?: element)
return
}
element.children.firstOrNull { !isValidBlockSequenceChild(it) }?.let {
reportSubElementProblem(holder, YAMLBundle.message("inspections.invalid.child.in.block.sequence"), it)
}
checkIndent(element.items, holder, YAMLBundle.message("inspections.invalid.list.item.indent"))
}
}
private fun reportWholeElementProblem(holder: AnnotationHolder, element: PsiElement, reportElement: PsiElement) {
holder.newAnnotation(HighlightSeverity.ERROR, getMessageForParent(element))
.range(TextRange.create(element.startOffset, endOfLine(reportElement, element))).create()
}
private fun endOfLine(subElement: PsiElement, whole: PsiElement): Int {
var current = subElement
while (true) {
val next = PsiTreeUtil.nextLeaf(current) ?: break
if (PsiUtilCore.getElementType(next) === YAMLTokenTypes.EOL) {
break
}
current = next
if (current.endOffset >= whole.endOffset) {
break
}
}
return min(current.endOffset, whole.endOffset)
}
private fun checkIndent(elements: List<PsiElement>, holder: AnnotationHolder, message: @Nls String) {
if (elements.size > 1) {
val firstIndent = YAMLUtil.getIndentToThisElement(elements.first())
for (item in elements.subList(1, elements.size)) {
if (YAMLUtil.getIndentToThisElement(item) != firstIndent) {
reportSubElementProblem(holder, message, item)
}
}
}
}
private fun getMessageForParent(element: PsiElement) =
if (findNeededParent(element) is YAMLKeyValueImpl)
YAMLBundle.message("inspections.invalid.child.in.block.mapping")
else YAMLBundle.message("inspections.invalid.child.in.block.sequence")
private fun isValidBlockMapChild(element: PsiElement?): Boolean =
element.let { it is YAMLKeyValue || it is YAMLAnchor || it is LeafPsiElement }
private fun isValidBlockSequenceChild(element: PsiElement?): Boolean =
element.let { it is YAMLSequenceItem || it is YAMLAnchor || it is LeafPsiElement }
private fun anotherErrorWillBeReported(element: PsiElement): Boolean {
val kvParent = findNeededParent(element) ?: return false
val kvGrandParent = kvParent.parentOfType<YAMLKeyValueImpl>(withSelf = false) ?: return false
return YAMLUtil.psiAreAtTheSameLine(kvGrandParent, element)
}
private fun findNeededParent(element: PsiElement) = PsiTreeUtil.findFirstParent(element, true) {
it is YAMLKeyValueImpl || it is YAMLSequenceItem
}
private fun reportSameLineWarning(value: PsiElement, holder: AnnotationHolder): Boolean {
val keyValue = value.parent
if (keyValue !is YAMLKeyValue) return false
val key = keyValue.key ?: return false
if (value is YAMLBlockMappingImpl) {
val firstSubValue = value.firstKeyValue
if (YAMLUtil.psiAreAtTheSameLine(key, firstSubValue)) {
reportAboutSameLine(holder, value)
return true
}
}
if (value is YAMLBlockSequenceImpl) {
val items = value.items
if (items.isEmpty()) {
// a very strange situation: a sequence without any item
return true
}
val firstItem = items[0]
if (YAMLUtil.psiAreAtTheSameLine(key, firstItem)) {
reportAboutSameLine(holder, value)
return true
}
}
return false
}
private fun reportAboutSameLine(holder: AnnotationHolder, value: YAMLValue) {
reportSubElementProblem(holder, YAMLBundle.message("annotator.same.line.composed.value.message"), value)
}
private fun reportSubElementProblem(holder: AnnotationHolder, message: @Nls String, subElement: PsiElement) {
val firstLeaf = TreeUtil.findFirstLeaf(subElement.node)?.psi ?: return
holder.newAnnotation(HighlightSeverity.ERROR, message)
.range(TextRange.create(subElement.startOffset, endOfLine(firstLeaf, subElement))).create()
}
} | apache-2.0 | 4ad41643050d111aa7a0228acdf91ac7 | 40.230263 | 140 | 0.747207 | 4.28298 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertFunctionTypeParameterToReceiverIntention.kt | 1 | 19275 | // 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.progress.ProgressManager
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.util.RefactoringUIUtil
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.core.CollectingNameValidator
import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester
import org.jetbrains.kotlin.idea.base.psi.copied
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.core.*
import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress
import org.jetbrains.kotlin.idea.refactoring.CallableRefactoring
import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.explicateReceiverOf
import org.jetbrains.kotlin.idea.refactoring.checkConflictsInteractively
import org.jetbrains.kotlin.idea.refactoring.getAffectedCallables
import org.jetbrains.kotlin.idea.refactoring.introduce.introduceVariable.KotlinIntroduceVariableHandler
import org.jetbrains.kotlin.idea.references.KtReference
import org.jetbrains.kotlin.idea.references.KtSimpleReference
import org.jetbrains.kotlin.idea.search.usagesSearch.searchReferencesOrMethodReferences
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch
import org.jetbrains.kotlin.psi.typeRefHelpers.setReceiverTypeReference
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getAbbreviatedTypeOrType
import org.jetbrains.kotlin.resolve.calls.util.getArgumentByParameterIndex
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
class ConvertFunctionTypeParameterToReceiverIntention : SelfTargetingRangeIntention<KtTypeReference>(
KtTypeReference::class.java,
KotlinBundle.lazyMessage("convert.function.type.parameter.to.receiver")
) {
class FunctionDefinitionInfo(element: KtFunction) : AbstractProcessableUsageInfo<KtFunction, ConversionData>(element) {
override fun process(data: ConversionData, elementsToShorten: MutableList<KtElement>) {
val function = element ?: return
val functionParameter = function.valueParameters.getOrNull(data.functionParameterIndex) ?: return
val functionType = functionParameter.typeReference?.typeElement as? KtFunctionType ?: return
val functionTypeParameterList = functionType.parameterList ?: return
val parameterToMove = functionTypeParameterList.parameters.getOrNull(data.typeParameterIndex) ?: return
val typeReferenceToMove = parameterToMove.typeReference ?: return
functionType.setReceiverTypeReference(typeReferenceToMove)
functionTypeParameterList.removeParameter(parameterToMove)
}
}
class ParameterCallInfo(element: KtCallExpression) : AbstractProcessableUsageInfo<KtCallExpression, ConversionData>(element) {
override fun process(data: ConversionData, elementsToShorten: MutableList<KtElement>) {
val callExpression = element ?: return
val argumentList = callExpression.valueArgumentList ?: return
val expressionToMove = argumentList.arguments.getOrNull(data.typeParameterIndex)?.getArgumentExpression() ?: return
val callWithReceiver =
KtPsiFactory(callExpression).createExpressionByPattern("$0.$1", expressionToMove, callExpression) as KtQualifiedExpression
(callWithReceiver.selectorExpression as KtCallExpression).valueArgumentList!!.removeArgument(data.typeParameterIndex)
callExpression.replace(callWithReceiver)
}
}
class InternalReferencePassInfo(element: KtSimpleNameExpression) :
AbstractProcessableUsageInfo<KtSimpleNameExpression, ConversionData>(element) {
override fun process(data: ConversionData, elementsToShorten: MutableList<KtElement>) {
val expression = element ?: return
val lambdaType = data.lambdaType
val validator = CollectingNameValidator()
val parameterNames = lambdaType.arguments
.dropLast(1)
.map { Fe10KotlinNameSuggester.suggestNamesByType(it.type, validator, "p").first() }
val receiver = parameterNames.getOrNull(data.typeParameterIndex) ?: return
val arguments = parameterNames.filter { it != receiver }
val adapterLambda = KtPsiFactory(expression).createLambdaExpression(
parameterNames.joinToString(),
"$receiver.${expression.text}(${arguments.joinToString()})"
)
expression.replaced(adapterLambda).moveFunctionLiteralOutsideParenthesesIfPossible()
}
}
class LambdaInfo(element: KtExpression) : AbstractProcessableUsageInfo<KtExpression, ConversionData>(element) {
override fun process(data: ConversionData, elementsToShorten: MutableList<KtElement>) {
val expression = element ?: return
val context = expression.analyze(BodyResolveMode.PARTIAL)
val psiFactory = KtPsiFactory(expression)
if (expression is KtLambdaExpression || (expression !is KtSimpleNameExpression && expression !is KtCallableReferenceExpression)) {
expression.forEachDescendantOfType<KtThisExpression> {
if (it.getLabelName() != null) return@forEachDescendantOfType
val descriptor = context[BindingContext.REFERENCE_TARGET, it.instanceReference] ?: return@forEachDescendantOfType
it.replace(psiFactory.createExpression(explicateReceiverOf(descriptor)))
}
}
if (expression is KtLambdaExpression) {
expression.valueParameters.getOrNull(data.typeParameterIndex)?.let { parameterToConvert ->
val thisRefExpr = psiFactory.createThisExpression()
for (ref in ReferencesSearch.search(parameterToConvert, LocalSearchScope(expression))) {
(ref.element as? KtSimpleNameExpression)?.replace(thisRefExpr)
}
val lambda = expression.functionLiteral
lambda.valueParameterList!!.removeParameter(parameterToConvert)
if (lambda.valueParameters.isEmpty()) {
lambda.arrow?.delete()
}
}
return
}
val originalLambdaTypes = data.lambdaType
val originalParameterTypes = originalLambdaTypes.arguments.dropLast(1).map { it.type }
val calleeText = when (expression) {
is KtSimpleNameExpression -> expression.text
is KtCallableReferenceExpression -> "(${expression.text})"
else -> generateVariable(expression)
}
val parameterNameValidator = CollectingNameValidator(
if (expression !is KtCallableReferenceExpression) listOf(calleeText) else emptyList()
)
val parameterNamesWithReceiver = originalParameterTypes.mapIndexed { i, type ->
if (i != data.typeParameterIndex) Fe10KotlinNameSuggester.suggestNamesByType(type, parameterNameValidator, "p")
.first() else "this"
}
val parameterNames = parameterNamesWithReceiver.filter { it != "this" }
val body = psiFactory.createExpression(parameterNamesWithReceiver.joinToString(prefix = "$calleeText(", postfix = ")"))
val replacingLambda = psiFactory.buildExpression {
appendFixedText("{ ")
appendFixedText(parameterNames.joinToString())
appendFixedText(" -> ")
appendExpression(body)
appendFixedText(" }")
} as KtLambdaExpression
expression.replaced(replacingLambda).moveFunctionLiteralOutsideParenthesesIfPossible()
}
private fun generateVariable(expression: KtExpression): String {
var baseCallee = ""
KotlinIntroduceVariableHandler.doRefactoring(project, null, expression, false, emptyList()) {
baseCallee = it.name!!
}
return baseCallee
}
}
private inner class Converter(
private val data: ConversionData,
editor: Editor?
) : CallableRefactoring<CallableDescriptor>(data.function.project, editor, data.functionDescriptor, text) {
override fun performRefactoring(descriptorsForChange: Collection<CallableDescriptor>) {
val callables = getAffectedCallables(project, descriptorsForChange)
val conflicts = MultiMap<PsiElement, String>()
val usages = ArrayList<AbstractProcessableUsageInfo<*, ConversionData>>()
project.runSynchronouslyWithProgress(KotlinBundle.message("looking.for.usages.and.conflicts"), true) {
runReadAction {
val progressIndicator = ProgressManager.getInstance().progressIndicator
progressIndicator.isIndeterminate = false
val progressStep = 1.0 / callables.size
for ((i, callable) in callables.withIndex()) {
progressIndicator.fraction = (i + 1) * progressStep
if (callable !is PsiNamedElement) continue
if (!checkModifiable(callable)) {
val renderedCallable = RefactoringUIUtil.getDescription(callable, true).capitalize()
conflicts.putValue(callable, KotlinBundle.message("can.t.modify.0", renderedCallable))
}
usageLoop@ for (ref in callable.searchReferencesOrMethodReferences()) {
val refElement = ref.element
when (ref) {
is KtSimpleReference<*> -> processExternalUsage(conflicts, refElement, usages)
is KtReference -> continue@usageLoop
else -> {
if (data.isFirstParameter) continue@usageLoop
conflicts.putValue(
refElement,
KotlinBundle.message(
"can.t.replace.non.kotlin.reference.with.call.expression.0",
StringUtil.htmlEmphasize(refElement.text)
)
)
}
}
}
if (callable is KtFunction) {
usages += FunctionDefinitionInfo(callable)
processInternalUsages(callable, usages)
}
}
}
}
project.checkConflictsInteractively(conflicts) {
project.executeWriteCommand(text) {
val elementsToShorten = ArrayList<KtElement>()
usages.sortedByDescending { it.element?.textOffset }.forEach { it.process(data, elementsToShorten) }
ShortenReferences.DEFAULT.process(elementsToShorten)
}
}
}
private fun processExternalUsage(
conflicts: MultiMap<PsiElement, String>,
refElement: PsiElement,
usages: ArrayList<AbstractProcessableUsageInfo<*, ConversionData>>
) {
val callElement = refElement.getParentOfTypeAndBranch<KtCallElement> { calleeExpression }
if (callElement != null) {
val context = callElement.analyze(BodyResolveMode.PARTIAL)
val expressionToProcess = getArgumentExpressionToProcess(callElement, context) ?: return
if (!data.isFirstParameter
&& callElement is KtConstructorDelegationCall
&& expressionToProcess !is KtLambdaExpression
&& expressionToProcess !is KtSimpleNameExpression
&& expressionToProcess !is KtCallableReferenceExpression
) {
conflicts.putValue(
expressionToProcess,
KotlinBundle.message(
"following.expression.won.t.be.processed.since.refactoring.can.t.preserve.its.semantics.0",
expressionToProcess.text
)
)
return
}
if (!checkThisExpressionsAreExplicatable(conflicts, context, expressionToProcess)) return
if (data.isFirstParameter && expressionToProcess !is KtLambdaExpression) return
usages += LambdaInfo(expressionToProcess)
return
}
if (data.isFirstParameter) return
val callableReference = refElement.getParentOfTypeAndBranch<KtCallableReferenceExpression> { callableReference }
if (callableReference != null) {
conflicts.putValue(
refElement,
KotlinBundle.message(
"callable.reference.transformation.is.not.supported.0",
StringUtil.htmlEmphasize(callableReference.text)
)
)
return
}
}
private fun getArgumentExpressionToProcess(callElement: KtCallElement, context: BindingContext): KtExpression? {
return callElement
.getArgumentByParameterIndex(data.functionParameterIndex, context)
.singleOrNull()
?.getArgumentExpression()
?.let { KtPsiUtil.safeDeparenthesize(it) }
}
private fun checkThisExpressionsAreExplicatable(
conflicts: MultiMap<PsiElement, String>,
context: BindingContext,
expressionToProcess: KtExpression
): Boolean {
for (thisExpr in expressionToProcess.collectDescendantsOfType<KtThisExpression>()) {
if (thisExpr.getLabelName() != null) continue
val descriptor = context[BindingContext.REFERENCE_TARGET, thisExpr.instanceReference] ?: continue
if (explicateReceiverOf(descriptor) == "this") {
conflicts.putValue(
thisExpr,
KotlinBundle.message(
"following.expression.won.t.be.processed.since.refactoring.can.t.preserve.its.semantics.0",
thisExpr.text
)
)
return false
}
}
return true
}
private fun processInternalUsages(callable: KtFunction, usages: ArrayList<AbstractProcessableUsageInfo<*, ConversionData>>) {
val body = when (callable) {
is KtConstructor<*> -> callable.containingClassOrObject?.body
else -> callable.bodyExpression
}
if (body != null) {
val functionParameter = callable.valueParameters.getOrNull(data.functionParameterIndex) ?: return
for (ref in ReferencesSearch.search(functionParameter, LocalSearchScope(body))) {
val element = ref.element as? KtSimpleNameExpression ?: continue
val callExpression = element.getParentOfTypeAndBranch<KtCallExpression> { calleeExpression }
if (callExpression != null) {
usages += ParameterCallInfo(callExpression)
} else if (!data.isFirstParameter) {
usages += InternalReferencePassInfo(element)
}
}
}
}
}
class ConversionData(
val typeParameterIndex: Int,
val functionParameterIndex: Int,
val lambdaType: KotlinType,
val function: KtFunction
) {
val isFirstParameter: Boolean get() = typeParameterIndex == 0
val functionDescriptor by lazy { function.unsafeResolveToDescriptor() as FunctionDescriptor }
}
private fun KtTypeReference.getConversionData(): ConversionData? {
val parameter = parent as? KtParameter ?: return null
val functionType = parameter.getParentOfTypeAndBranch<KtFunctionType> { parameterList } ?: return null
if (functionType.receiverTypeReference != null) return null
val lambdaType = functionType.getAbbreviatedTypeOrType(functionType.analyze(BodyResolveMode.PARTIAL)) ?: return null
val containingParameter = (functionType.parent as? KtTypeReference)?.parent as? KtParameter ?: return null
val ownerFunction = containingParameter.ownerFunction as? KtFunction ?: return null
val typeParameterIndex = functionType.parameters.indexOf(parameter)
val functionParameterIndex = ownerFunction.valueParameters.indexOf(containingParameter)
return ConversionData(typeParameterIndex, functionParameterIndex, lambdaType, ownerFunction)
}
override fun startInWriteAction(): Boolean = false
override fun applicabilityRange(element: KtTypeReference): TextRange? {
val data = element.getConversionData() ?: return null
val elementBefore = data.function.valueParameters[data.functionParameterIndex].typeReference!!.typeElement as KtFunctionType
val elementAfter = elementBefore.copied().apply {
setReceiverTypeReference(element)
parameterList!!.removeParameter(data.typeParameterIndex)
}
setTextGetter(KotlinBundle.lazyMessage("convert.0.to.1", elementBefore.text, elementAfter.text))
return element.textRange
}
override fun applyTo(element: KtTypeReference, editor: Editor?) {
element.getConversionData()?.let { Converter(it, editor).run() }
}
}
| apache-2.0 | 5576139af03628b11fbc2178f5788e09 | 51.094595 | 158 | 0.650584 | 6.270332 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/fixers/KotlinFunctionParametersFixer.kt | 6 | 1588 | // 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.editor.fixers
import com.intellij.lang.SmartEnterProcessorWithFixers
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.editor.KotlinSmartEnterHandler
import org.jetbrains.kotlin.psi.KtNamedFunction
import kotlin.math.max
class KotlinFunctionParametersFixer : SmartEnterProcessorWithFixers.Fixer<KotlinSmartEnterHandler>() {
override fun apply(editor: Editor, processor: KotlinSmartEnterHandler, psiElement: PsiElement) {
if (psiElement !is KtNamedFunction) return
val parameterList = psiElement.valueParameterList
if (parameterList == null) {
val identifier = psiElement.nameIdentifier ?: return
// Insert () after name or after type parameters list when it placed after name
val offset = max(identifier.range.end, psiElement.typeParameterList?.range?.end ?: psiElement.range.start)
editor.document.insertString(offset, "()")
processor.registerUnresolvedError(offset + 1)
} else {
val rParen = parameterList.lastChild ?: return
if (")" != rParen.text) {
val params = parameterList.parameters
val offset = if (params.isEmpty()) parameterList.range.start + 1 else params.last().range.end
editor.document.insertString(offset, ")")
}
}
}
}
| apache-2.0 | 1031c513c44e5c69620dfcd65dff838a | 44.371429 | 158 | 0.701511 | 4.993711 | false | false | false | false |
hermantai/samples | kotlin/kotlin-and-android-development-featuring-jetpack/chapter-13/app-code/app/src/main/java/dev/mfazio/abl/settings/ImageCreditsAdapter.kt | 3 | 1392 | package dev.mfazio.abl.settings
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import dev.mfazio.abl.R
import dev.mfazio.abl.databinding.ImageCreditItemBinding
class ImageCreditsAdapter :
ListAdapter<ImageCredit, ImageCreditsAdapter.ViewHolder>(ImageCreditDiffCallback()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder(
DataBindingUtil.inflate(
LayoutInflater.from(parent.context),
R.layout.image_credit_item,
parent,
false
)
)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(getItem(position))
}
class ViewHolder(private val binding: ImageCreditItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(imageCredit: ImageCredit) {
binding.imageCredit = imageCredit
}
}
}
private class ImageCreditDiffCallback : DiffUtil.ItemCallback<ImageCredit>() {
override fun areItemsTheSame(oldItem: ImageCredit, newItem: ImageCredit) =
oldItem.id == newItem.id
override fun areContentsTheSame(oldItem: ImageCredit, newItem: ImageCredit) =
oldItem == newItem
} | apache-2.0 | cb2fa1f122114026a00fef9b7f8c85f6 | 31.395349 | 89 | 0.73204 | 4.816609 | false | false | false | false |
JavaEden/Orchid-Core | OrchidCore/src/main/kotlin/com/eden/orchid/impl/generators/AssetsGenerator.kt | 2 | 3854 | package com.eden.orchid.impl.generators
import com.eden.common.util.EdenUtils
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.generators.OrchidCollection
import com.eden.orchid.api.generators.OrchidGenerator
import com.eden.orchid.api.generators.emptyModel
import com.eden.orchid.api.generators.modelOf
import com.eden.orchid.api.options.OptionsHolder
import com.eden.orchid.api.options.annotations.BooleanDefault
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.ImpliedKey
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.options.annotations.StringDefault
import com.eden.orchid.api.options.annotations.Validate
import com.eden.orchid.api.resources.resourcesource.LocalResourceSource
import com.eden.orchid.api.theme.assets.AssetManagerDelegate
import com.eden.orchid.api.theme.assets.AssetPage
import java.util.Arrays
import javax.inject.Inject
import javax.inject.Singleton
import javax.validation.constraints.NotBlank
@Singleton
@Description(
value = "Add additional arbitrary assets to your site. Assets added from themes, pages, and components " + "are automatically rendered to your site, this is just for additional static assets.",
name = "Assets"
)
class AssetsGenerator : OrchidGenerator<OrchidGenerator.Model>(GENERATOR_KEY, Stage.WARM_UP) {
@Option
@Description("Set which local resource directories you want to copy static assets from.")
@ImpliedKey(typeKey = "sourceDir")
@StringDefault("assets/media")
lateinit var sourceDirs: List<AssetDirectory>
private fun createAssetManagerDelegate(context: OrchidContext): AssetManagerDelegate {
return AssetManagerDelegate(context, this, "generator", null)
}
override fun startIndexing(context: OrchidContext): Model {
val delegate = createAssetManagerDelegate(context)
val resourceSource = context.getDefaultResourceSource(LocalResourceSource, null)
val assetPages = sourceDirs
.flatMap { dir ->
context.getDefaultResourceSource(LocalResourceSource, null).getResourceEntries(
context,
dir.sourceDir,
if (!EdenUtils.isEmpty(dir.assetFileExtensions)) dir.assetFileExtensions else null,
dir.recursive
)
}
.map { resource ->
context
.assetManager
.createAsset(delegate, resourceSource, resource.reference.originalFullFileName)
.let { context.assetManager.getActualAsset(delegate, it, false) }
}
return modelOf { assetPages }
}
override fun startGeneration(context: OrchidContext, model: Model) {
model.allPages.filterIsInstance<AssetPage>().forEach { context.renderAsset(it) }
}
// Helpers
//----------------------------------------------------------------------------------------------------------------------
@Validate
class AssetDirectory : OptionsHolder {
@Option
@NotBlank
@Description("Set which local resource directories you want to copy static assets from.")
lateinit var sourceDir: String
@Option
@Description("Restrict the file extensions used for the assets in this directory.")
lateinit var assetFileExtensions: Array<String>
@Option
@BooleanDefault(true)
@Description("Whether to include subdirectories of this directory")
var recursive: Boolean = true
override fun toString(): String {
return "AssetDirectory(sourceDir='$sourceDir', assetFileExtensions=${Arrays.toString(assetFileExtensions)}, isRecursive=$recursive)"
}
}
companion object {
val GENERATOR_KEY = "assets"
}
}
| mit | 37ce96fbaf9c42659ede96df506e385c | 37.929293 | 197 | 0.688376 | 4.934699 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/slicer/SlicerTestUtil.kt | 4 | 4952 | // 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.slicer
import com.intellij.analysis.AnalysisScope
import com.intellij.ide.projectView.TreeStructureProvider
import com.intellij.ide.util.treeView.AbstractTreeStructureBase
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.PsiSearchScopeUtil
import com.intellij.slicer.DuplicateMap
import com.intellij.slicer.SliceAnalysisParams
import com.intellij.slicer.SliceNode
import com.intellij.slicer.SliceRootNode
import com.intellij.usages.TextChunk
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils
import java.awt.Font
internal class TestSliceTreeStructure(private val rootNode: SliceNode) : AbstractTreeStructureBase(rootNode.project) {
override fun getProviders() = emptyList<TreeStructureProvider>()
override fun getRootElement() = rootNode
override fun commit() {
}
override fun hasSomethingToCommit() = false
}
internal fun buildTreeRepresentation(rootNode: SliceNode): String {
val project = rootNode.element!!.project!!
val projectScope = GlobalSearchScope.projectScope(project)
fun TextChunk.render(): String {
var text = text
if (attributes.fontType == Font.BOLD) {
text = "<bold>$text</bold>"
}
return text
}
fun SliceNode.isSliceLeafValueClassNode() = this is HackedSliceLeafValueClassNode
fun process(node: SliceNode, indent: Int): String {
val usage = node.element!!.value
node.calculateDupNode()
val isDuplicated = !node.isSliceLeafValueClassNode() && node.duplicate != null
return buildString {
when {
node is SliceRootNode && usage.element is KtFile -> {
node.sortedChildren.forEach { append(process(it, indent)) }
return@buildString
}
// SliceLeafValueClassNode is package-private
node.isSliceLeafValueClassNode() -> append("[${node.nodeText}]\n")
else -> {
val chunks = usage.text
if (!PsiSearchScopeUtil.isInScope(projectScope, usage.element!!)) {
append("LIB ")
} else {
append(chunks.first().render() + " ")
}
repeat(indent) { append('\t') }
if (usage is KotlinSliceDereferenceUsage) {
append("DEREFERENCE: ")
}
if (usage is KotlinSliceUsage) {
usage.mode.inlineCallStack.forEach {
append("(INLINE CALL ${it.function?.name}) ")
}
usage.mode.behaviourStack.reversed().joinTo(this, separator = "") { it.testPresentationPrefix }
}
if (isDuplicated) {
append("DUPLICATE: ")
}
chunks.slice(1 until chunks.size).joinTo(this, separator = "") { it.render() }
KotlinSliceUsageCellRenderer.containerSuffix(usage)?.let {
append(" ($it)")
}
append("\n")
}
}
if (!isDuplicated) {
node.sortedChildren.forEach { append(process(it, indent + 1)) }
}
}.replace(Regex("</bold><bold>"), "")
}
return process(rootNode, 0)
}
private val SliceNode.sortedChildren: List<SliceNode>
get() = children.sortedBy { it.value.element?.startOffset ?: -1 }
internal fun testSliceFromOffset(
file: KtFile,
offset: Int,
doTest: (sliceProvider: KotlinSliceProvider, rootNode: SliceRootNode) -> Unit
) {
val fileText = file.text
val flowKind = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// FLOW: ")
val withDereferences = InTextDirectivesUtils.isDirectiveDefined(fileText, "// WITH_DEREFERENCES")
val analysisParams = SliceAnalysisParams().apply {
dataFlowToThis = when (flowKind) {
"IN" -> true
"OUT" -> false
else -> throw AssertionError("Invalid flow kind: $flowKind")
}
showInstanceDereferences = withDereferences
scope = AnalysisScope(file.project)
}
val elementAtCaret = file.findElementAt(offset)!!
val sliceProvider = KotlinSliceProvider()
val expression = sliceProvider.getExpressionAtCaret(elementAtCaret, analysisParams.dataFlowToThis)!!
val rootUsage = sliceProvider.createRootUsage(expression, analysisParams)
val rootNode = SliceRootNode(file.project, DuplicateMap(), rootUsage)
doTest(sliceProvider, rootNode)
}
| apache-2.0 | 164042507ff0b93c8b78a7aaaf87d4ba | 36.515152 | 158 | 0.622577 | 4.883629 | false | false | false | false |
GunoH/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/util/recordUtil.kt | 9 | 1809 | // 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.
@file:JvmName("GrRecordUtils")
package org.jetbrains.plugins.groovy.lang.psi.util
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.psi.util.elementType
import com.intellij.psi.util.siblings
import org.jetbrains.plugins.groovy.GroovyBundle
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrRecordDefinition
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
import org.jetbrains.plugins.groovy.transformations.TransformationContext
/**
* According to Groovy compiler, no record transformation is done when there is no property handler.
*/
fun isRecordTransformationApplied(context: TransformationContext): Boolean {
return context.getAnnotation(GroovyCommonClassNames.GROOVY_TRANSFORM_RECORD_BASE) != null &&
context.getAnnotation(GroovyCommonClassNames.GROOVY_TRANSFORM_PROPERTY_OPTIONS) != null
}
fun getCompactConstructor(typedef : GrTypeDefinition) : GrMethod? =
typedef.codeConstructors.find(GrMethod::isCompactConstructor)
fun GrMethod.isCompactConstructor(): Boolean =
isConstructor && parameterList.text == ""
internal fun forbidRecord(holder: AnnotationHolder, recordDefinition: GrRecordDefinition) {
holder
.newAnnotation(HighlightSeverity.ERROR, GroovyBundle.message("inspection.message.records.are.available.in.groovy.4.or.later"))
.range(recordDefinition.firstChild.siblings().first { it.elementType === org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes.kRECORD })
.create()
}
| apache-2.0 | c3d2547ad55d362e4b263592459735e4 | 50.685714 | 158 | 0.815368 | 4.359036 | false | false | false | false |
GunoH/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/highlighting/MarkdownHighlightingAnnotator.kt | 2 | 2679 | // 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.highlighting
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.Annotator
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.psi.PsiElement
import com.intellij.psi.tree.IElementType
import com.intellij.psi.util.PsiUtilCore
import org.intellij.plugins.markdown.lang.MarkdownElementTypes
import org.intellij.plugins.markdown.lang.MarkdownTokenTypes
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownCodeFence
import org.intellij.plugins.markdown.lang.psi.util.hasType
class MarkdownHighlightingAnnotator : Annotator {
override fun annotate(element: PsiElement, holder: AnnotationHolder) {
when (PsiUtilCore.getElementType(element)) {
MarkdownTokenTypes.EMPH -> annotateBasedOnParent(element, holder) {
when (it) {
MarkdownElementTypes.EMPH -> MarkdownHighlighterColors.ITALIC_MARKER
MarkdownElementTypes.STRONG -> MarkdownHighlighterColors.BOLD_MARKER
else -> null
}
}
MarkdownTokenTypes.BACKTICK -> annotateBasedOnParent(element, holder) {
when (it) {
MarkdownElementTypes.CODE_FENCE -> MarkdownHighlighterColors.CODE_FENCE_MARKER
MarkdownElementTypes.CODE_SPAN -> MarkdownHighlighterColors.CODE_SPAN_MARKER
else -> null
}
}
else -> annotateWithHighlighter(element, holder)
}
}
private fun annotateBasedOnParent(element: PsiElement, holder: AnnotationHolder, predicate: (IElementType) -> TextAttributesKey?) {
val parentType = element.parent?.let(PsiUtilCore::getElementType) ?: return
val attributes = predicate.invoke(parentType)
if (attributes != null) {
holder.newSilentAnnotation(HighlightSeverity.INFORMATION).textAttributes(attributes).create()
}
}
private fun annotateWithHighlighter(element: PsiElement, holder: AnnotationHolder) {
if (element.hasType(MarkdownTokenTypes.CODE_FENCE_CONTENT) && (element.parent as? MarkdownCodeFence)?.fenceLanguage != null) {
return
}
val highlights = syntaxHighlighter.getTokenHighlights(PsiUtilCore.getElementType(element))
if (highlights.isNotEmpty() && highlights.first() != MarkdownHighlighterColors.TEXT) {
holder.newSilentAnnotation(HighlightSeverity.INFORMATION).textAttributes(highlights.first()).create()
}
}
companion object {
private val syntaxHighlighter = MarkdownSyntaxHighlighter()
}
}
| apache-2.0 | 88fbd93c074c0b5cbb8a8b47b0a3b0ba | 45.189655 | 158 | 0.761105 | 4.888686 | false | false | false | false |
brianwernick/PlaylistCore | library/src/main/kotlin/com/devbrackets/android/playlistcore/data/RemoteActions.kt | 1 | 788 | package com.devbrackets.android.playlistcore.data
/**
* A simple container for the remote actions used by the
* [com.devbrackets.android.playlistcore.manager.BasePlaylistManager]
* to inform the [BasePlaylistService] of processes to handle.
*/
object RemoteActions {
private val PREFIX = "com.devbrackets.android.playlistcore."
val ACTION_START_SERVICE = PREFIX + "start_service"
val ACTION_PLAY_PAUSE = PREFIX + "play_pause"
val ACTION_PREVIOUS = PREFIX + "previous"
val ACTION_NEXT = PREFIX + "next"
val ACTION_STOP = PREFIX + "stop"
val ACTION_SEEK_STARTED = PREFIX + "seek_started"
val ACTION_SEEK_ENDED = PREFIX + "seek_ended"
//Extras
val ACTION_EXTRA_SEEK_POSITION = PREFIX + "seek_position"
val ACTION_EXTRA_START_PAUSED = PREFIX + "start_paused"
}
| apache-2.0 | f1e17f2d1bbabe87ef987fd07878eccf | 31.833333 | 69 | 0.729695 | 3.752381 | false | false | false | false |
marcbaldwin/RxAdapter | rxadapter/src/main/kotlin/xyz/marcb/rxadapter/Section.kt | 1 | 1842 | package xyz.marcb.rxadapter
import androidx.recyclerview.widget.RecyclerView
import io.reactivex.Observable
class Section : AdapterPart {
override val snapshots: Observable<AdapterPartSnapshot> get() = parts.combine()
override var visible: Observable<Boolean>? = null
private val parts = ArrayList<AdapterPart>()
inline fun <VH> item(
vhClass: Class<VH>,
id: Long = RecyclerView.NO_ID,
init: StaticItem<VH>.() -> Unit = {}
): StaticItem<VH> where VH : RecyclerView.ViewHolder =
add(StaticItem(vhClass, id)).apply { init.invoke(this) }
inline fun <I, VH> item(
vhClass: Class<VH>,
item: Observable<I>,
id: Long = RecyclerView.NO_ID,
init: Item<I, VH>.() -> Unit = {}
): Item<I, VH> where VH : RecyclerView.ViewHolder =
add(Item(vhClass, item, id)).apply { init.invoke(this) }
inline fun <O, I, VH> optionalItem(
vhClass: Class<VH>,
item: Observable<O>,
noinline unwrap: (O) -> I?,
id: Long = RecyclerView.NO_ID,
init: OptionalItem<O, I, VH>.() -> Unit = {}
): OptionalItem<O, I, VH> where VH : RecyclerView.ViewHolder =
add(OptionalItem(vhClass, item, unwrap, id)).apply { init.invoke(this) }
inline fun <I, VH> items(
vhClass: Class<VH>,
items: List<I>,
init: Items<I, VH>.() -> Unit = {}
): Items<I, VH> where VH : RecyclerView.ViewHolder =
items(vhClass, Observable.just(items), init)
inline fun <I, VH> items(
vhClass: Class<VH>,
items: Observable<List<I>>,
init: Items<I, VH>.() -> Unit
): Items<I, VH> where VH : RecyclerView.ViewHolder =
add(Items(vhClass, items)).apply { init.invoke(this) }
fun <R : AdapterPart> add(part: R): R {
parts.add(part)
return part
}
}
| mit | c3105511b143c1675dde6e7db599ffb7 | 31.892857 | 83 | 0.596091 | 3.633136 | false | false | false | false |
ktorio/ktor | ktor-http/common/src/io/ktor/http/Headers.kt | 1 | 2922 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.http
import io.ktor.util.*
/**
* Represents HTTP headers as a map from case-insensitive names to collection of [String] values
*/
public interface Headers : StringValues {
public companion object {
/**
* Empty [Headers] instance
*/
@Suppress("DEPRECATION_ERROR")
public val Empty: Headers = EmptyHeaders
/**
* Builds a [Headers] instance with the given [builder] function
* @param builder specifies a function to build a map
*/
public inline fun build(builder: HeadersBuilder.() -> Unit): Headers = HeadersBuilder().apply(builder).build()
}
}
@Suppress("KDocMissingDocumentation")
public class HeadersBuilder(size: Int = 8) : StringValuesBuilderImpl(true, size) {
override fun build(): Headers {
return HeadersImpl(values)
}
override fun validateName(name: String) {
super.validateName(name)
HttpHeaders.checkHeaderName(name)
}
override fun validateValue(value: String) {
super.validateValue(value)
HttpHeaders.checkHeaderValue(value)
}
}
@Suppress("KDocMissingDocumentation")
@Deprecated(
"Empty headers is internal",
replaceWith = ReplaceWith("Headers.Empty"),
level = DeprecationLevel.ERROR
)
public object EmptyHeaders : Headers {
override val caseInsensitiveName: Boolean get() = true
override fun getAll(name: String): List<String>? = null
override fun names(): Set<String> = emptySet()
override fun entries(): Set<Map.Entry<String, List<String>>> = emptySet()
override fun isEmpty(): Boolean = true
override fun toString(): String = "Headers ${entries()}"
}
/**
* Returns empty headers
*/
public fun headersOf(): Headers = Headers.Empty
/**
* Returns [Headers] instance containing only one header with the specified [name] and [value]
*/
public fun headersOf(name: String, value: String): Headers = HeadersSingleImpl(name, listOf(value))
/**
* Returns [Headers] instance containing only one header with the specified [name] and [values]
*/
public fun headersOf(name: String, values: List<String>): Headers = HeadersSingleImpl(name, values)
/**
* Returns [Headers] instance from [pairs]
*/
public fun headersOf(vararg pairs: Pair<String, List<String>>): Headers = HeadersImpl(pairs.asList().toMap())
@Suppress("KDocMissingDocumentation")
public class HeadersImpl(
values: Map<String, List<String>> = emptyMap()
) : Headers, StringValuesImpl(true, values) {
override fun toString(): String = "Headers ${entries()}"
}
@Suppress("KDocMissingDocumentation")
public class HeadersSingleImpl(
name: String,
values: List<String>
) : Headers, StringValuesSingleImpl(true, name, values) {
override fun toString(): String = "Headers ${entries()}"
}
| apache-2.0 | 950cdba131c672099a93e23d55ac17ca | 30.419355 | 118 | 0.690623 | 4.290749 | false | false | false | false |
ktorio/ktor | ktor-utils/common/test/io/ktor/util/GMTDateParserTest.kt | 1 | 1793 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.util
import io.ktor.util.date.*
import kotlin.test.*
class GMTDateParserTest {
@Test
fun testFormats() {
val formats = arrayOf(
"***, dd MMM YYYY hh:mm:ss zzz",
"****, dd-MMM-YYYY hh:mm:ss zzz",
"*** MMM d hh:mm:ss YYYY",
"***, dd-MMM-YYYY hh:mm:ss zzz",
"***, dd-MMM-YYYY hh-mm-ss zzz",
"***, dd MMM YYYY hh:mm:ss zzz",
"*** dd-MMM-YYYY hh:mm:ss zzz",
"*** dd MMM YYYY hh:mm:ss zzz",
"*** dd-MMM-YYYY hh-mm-ss zzz",
"***,dd-MMM-YYYY hh:mm:ss zzz",
"*** MMM d YYYY hh:mm:ss zzz"
)
val eleven = GMTDate(1, 45, 12, 11, Month.APRIL, 2018)
val first = GMTDate(1, 45, 12, 1, Month.APRIL, 2018)
val dates = listOf(
"Wed, 11 Apr 2018 12:45:01 GMT" to eleven,
"Wedn, 11-Apr-2018 12:45:01 GMT" to eleven,
"Wed Apr 1 12:45:01 2018" to first,
"Wed, 11-Apr-2018 12:45:01 GMT" to eleven,
"Wed, 11-Apr-2018 12-45-01 GMT" to eleven,
"Wed, 11 Apr 2018 12:45:01 GMT" to eleven,
"Wed 11-Apr-2018 12:45:01 GMT" to eleven,
"Wed 11 Apr 2018 12:45:01 GMT" to eleven,
"Wed 11-Apr-2018 12-45-01 GMT" to eleven,
"Wed,11-Apr-2018 12:45:01 GMT" to eleven,
"Wed Apr 1 2018 12:45:01 GMT" to first
)
for (index in dates.indices) {
val parser = GMTDateParser(formats[index])
val (dateString, expected) = dates[index]
val date = parser.parse(dateString)
assertEquals(expected, date)
}
}
}
| apache-2.0 | b98e2bebf2363dcfa8aee8773290c6b1 | 33.480769 | 118 | 0.520915 | 3.173451 | false | true | false | false |
ClearVolume/scenery | src/test/kotlin/graphics/scenery/tests/examples/stresstests/ExampleRunner.kt | 1 | 7844 | package graphics.scenery.tests.examples.stresstests
import graphics.scenery.SceneryBase
import graphics.scenery.SceneryElement
import graphics.scenery.backends.Renderer
import graphics.scenery.utils.ExtractsNatives
import graphics.scenery.utils.LazyLogger
import graphics.scenery.utils.SystemHelpers
import kotlinx.coroutines.*
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.reflections.Reflections
import java.nio.file.Files
import java.nio.file.Paths
import kotlin.system.exitProcess
import kotlin.test.assertFalse
import kotlin.time.Duration
import kotlin.time.ExperimentalTime
import kotlin.time.milliseconds
@OptIn(ExperimentalTime::class)
@RunWith(Parameterized::class)
class ExampleRunner(
private val clazz: Class<*>,
private val clazzName: String,
private val renderer: String,
private val pipeline: String
) {
private val logger by LazyLogger()
@Test
fun runExample() = runBlocking {
logger.info("Running scenery example ${clazz.simpleName} with renderer $renderer and pipeline $pipeline")
var runtime = Duration.milliseconds(0)
logger.info("Memory: ${Runtime.getRuntime().freeMemory().toFloat()/1024.0f/1024.0f}M/${Runtime.getRuntime().totalMemory().toFloat()/1024.0f/1024.0f}/${Runtime.getRuntime().maxMemory().toFloat()/1024.0f/1024.0f}M (free/total/max) available.")
System.setProperty("scenery.Headless", "true")
System.setProperty("scenery.Renderer", renderer)
System.setProperty("scenery.Renderer.Config", pipeline)
val rendererDirectory = "$directoryName/$renderer-${pipeline.substringBefore(".")}"
val instance: SceneryBase = clazz.getConstructor().newInstance() as SceneryBase
var exampleRunnable: Job? = null
var failure = false
try {
val handler = CoroutineExceptionHandler { _, e ->
logger.error("${clazz.simpleName}: Received exception $e")
logger.error("Stack trace: ${e.stackTraceToString()}")
failure = true
// we fail very hard here to prevent process clogging the CI
exitProcess(-1)
}
exampleRunnable = GlobalScope.launch(handler) {
instance.assertions[SceneryBase.AssertionCheckPoint.BeforeStart]?.forEach {
it.invoke()
}
instance.main()
}
while (!instance.running || !instance.sceneInitialized() || instance.hub.get(SceneryElement.Renderer) == null) {
delay(200)
}
val r = (instance.hub.get(SceneryElement.Renderer) as Renderer)
while(!r.firstImageReady) {
delay(200)
}
delay(2000)
r.screenshot("$rendererDirectory/${clazz.simpleName}.png")
Thread.sleep(2000)
logger.info("Sending close to ${clazz.simpleName}")
instance.close()
instance.assertions[SceneryBase.AssertionCheckPoint.AfterClose]?.forEach {
it.invoke()
}
while (instance.running && !failure) {
if (runtime > maxRuntimePerTest) {
exampleRunnable.cancelAndJoin()
logger.error("Maximum runtime of $maxRuntimePerTest exceeded, aborting test run.")
failure = true
}
runtime += 200.milliseconds
delay(200)
}
if(failure) {
exampleRunnable.cancelAndJoin()
} else {
exampleRunnable.join()
}
} catch (e: ThreadDeath) {
logger.info("JOGL threw ThreadDeath")
}
logger.info("${clazz.simpleName} closed.")
assertFalse(failure, "ExampleRunner aborted due to exceptions in tests or exceeding maximum per-test runtime of $maxRuntimePerTest.")
}
companion object {
private val logger by LazyLogger()
var maxRuntimePerTest =
Duration.minutes(System.getProperty("scenery.ExampleRunner.maxRuntimePerTest", "5").toInt())
val reflections = Reflections("graphics.scenery.tests")
// blacklist contains examples that require user interaction or additional devices
val blocklist = mutableListOf(
// these examples don't work in headless mode
"SwingTexturedCubeExample",
"TexturedCubeJavaExample",
// these examples need additional hardware
"VRControllerExample",
"EyeTrackingExample",
"ARExample",
// these examples require user input and/or files
"LocalisationExample",
"ReaderExample",
"BDVExample",
"BigAndSmallVolumeExample",
"VolumeSamplingExample",
"VideoRecordingExample",
// these examples don't render anything
"AttributesExample",
"DFTExample",
"DFTMDExample"
) + System.getProperty("scenery.ExampleRunner.Blocklist", "").split(",")
val allowedTests = System.getProperty("scenery.ExampleRunner.AllowedTests")?.split(",")
val testGroup: String = System.getProperty("scenery.ExampleRunner.TestGroup", "basic")
// find all basic and advanced examples, exclude blacklist
val examples = reflections
.getSubTypesOf(SceneryBase::class.java)
.filter { !it.canonicalName.contains("stresstests")
&& !it.canonicalName.contains("cluster")
&& it.name.substringBeforeLast(".").contains(testGroup)
}
.filter { !blocklist.contains(it.simpleName) }.toMutableList()
.filter { allowedTests?.contains(it.simpleName) ?: true }
val renderers = System.getProperty("scenery.Renderer")?.split(",") ?: when(ExtractsNatives.getPlatform()) {
ExtractsNatives.Platform.WINDOWS,
ExtractsNatives.Platform.LINUX -> listOf("VulkanRenderer", "OpenGLRenderer")
ExtractsNatives.Platform.MACOS -> listOf("OpenGLRenderer")
ExtractsNatives.Platform.UNKNOWN -> {
throw UnsupportedOperationException("Don't know what to do on this platform, sorry.")
}
}
val configurations = System.getProperty("scenery.ExampleRunner.Configurations")?.split(",") ?: listOf("DeferredShading.yml", "DeferredShadingStereo.yml")
val directoryName = System.getProperty("scenery.ExampleRunner.OutputDir") ?: "ExampleRunner-${SystemHelpers.formatDateTime(delimiter = "_")}"
@Parameterized.Parameters(name = "{index}: {1} ({2}/{3})")
@JvmStatic
fun availableExamples(): Collection<Array<*>> {
val configs = examples.flatMap { example ->
renderers.flatMap { renderer ->
configurations.map { config ->
logger.debug("Adding ${example.simpleName} with $renderer/$config")
arrayOf(example, example.simpleName, renderer, config)
}
}
}
logger.info("Discovered ${renderers.size} renderers with ${configurations.size} different pipelines, for ${examples.size} examples from group $testGroup, resulting in ${configs.size} run configurations.")
return configs
}
@Parameterized.BeforeParam
@JvmStatic
fun createOutputDirectory() {
renderers.forEach { renderer ->
configurations.forEach { config ->
val rendererDirectory = "$directoryName/$renderer-${config.substringBefore(".")}"
Files.createDirectories(Paths.get(rendererDirectory))
}
}
}
}
}
| lgpl-3.0 | c49cb29b6995ffb05122f7e50fd07953 | 39.225641 | 249 | 0.618944 | 5.120104 | false | true | false | false |
google/ground-android | ground/src/main/java/com/google/android/ground/system/SettingsManager.kt | 1 | 3355 | /*
* 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.android.ground.system
import android.content.IntentSender.SendIntentException
import com.google.android.gms.common.api.ResolvableApiException
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationSettingsRequest
import com.google.android.ground.rx.RxCompletable.completeOrError
import com.google.android.ground.system.rx.RxSettingsClient
import io.reactivex.Completable
import io.reactivex.CompletableEmitter
import javax.inject.Inject
import javax.inject.Singleton
import timber.log.Timber
private val LOCATION_SETTINGS_REQUEST_CODE = SettingsManager::class.java.hashCode() and 0xffff
/**
* Manages enabling of settings and related flows to/from the Activity.
*
* Note: Currently only supports location settings, but could be expanded to support other settings
* types in the future.
*/
@Singleton
class SettingsManager
@Inject
constructor(
private val activityStreams: ActivityStreams,
private val settingsClient: RxSettingsClient
) {
/**
* Try to enable location settings. If location settings are already enabled, this will complete
* immediately on subscribe.
*/
fun enableLocationSettings(locationRequest: LocationRequest): Completable {
Timber.d("Checking location settings")
val settingsRequest =
LocationSettingsRequest.Builder().addLocationRequest(locationRequest).build()
return settingsClient.checkLocationSettings(settingsRequest).toCompletable().onErrorResumeNext {
onCheckSettingsFailure(it)
}
}
private fun onCheckSettingsFailure(throwable: Throwable): Completable =
if (throwable is ResolvableApiException) {
val requestCode = LOCATION_SETTINGS_REQUEST_CODE
startResolution(requestCode, throwable).andThen(getNextResult(requestCode))
} else {
Completable.error(throwable)
}
private fun startResolution(
requestCode: Int,
resolvableException: ResolvableApiException
): Completable =
Completable.create { emitter: CompletableEmitter ->
Timber.d("Prompting user to enable settings")
activityStreams.withActivity {
try {
resolvableException.startResolutionForResult(it, requestCode)
emitter.onComplete()
} catch (e: SendIntentException) {
emitter.onError(e)
}
}
}
private fun getNextResult(requestCode: Int): Completable =
activityStreams
.getNextActivityResult(requestCode)
.flatMapCompletable {
completeOrError({ it.isOk() }, SettingsChangeRequestCanceled::class.java)
}
.doOnComplete { Timber.d("Settings change request successful") }
.doOnError { Timber.e(it, "Settings change request failed") }
}
class SettingsChangeRequestCanceled : Exception()
| apache-2.0 | b013d478be5864fcdb3f14b81349478f | 35.075269 | 100 | 0.754993 | 4.666203 | false | false | false | false |
dkandalov/katas | kotlin/src/katas/kotlin/adventofcode/day4/Part2.kt | 1 | 527 | package katas.kotlin.adventofcode.day4
import nonstdlib.*
fun main() {
(372304..847060).count(::isValidPassword).printed()
}
fun isValidPassword(n: Int): Boolean {
val digits = n.digits
val digitGroups = digits.fold(emptyList<MutableList<Int>>()) { acc, it ->
if (acc.lastOrNull()?.lastOrNull() == it) {
acc.last().add(it)
acc
} else acc + listOf(mutableListOf(it))
}
return digitGroups.any { it.size == 2 } && digits.windowed(size = 2).all { it[0] <= it[1] }
}
| unlicense | 54ab28bf3c6ee6f2b22365167729370a | 25.35 | 95 | 0.601518 | 3.467105 | false | false | false | false |
dahlstrom-g/intellij-community | platform/platform-impl/src/com/intellij/featureStatistics/fusCollectors/EventsRateThrottle.kt | 9 | 1206 | // 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.featureStatistics.fusCollectors
class EventsRateThrottle(
private val amount: Int,
private val perMillis: Long
) {
private val timestamps = LongArray(amount)
private var currentSize = 0
private var lastIndex = 0
@Synchronized
fun tryPass(now: Long): Boolean {
if (isTimestampApplicable(now)) {
clearTimestamps(now)
if (currentSize < amount) {
addTimestamp(now)
return true
}
}
return false
}
private fun addTimestamp(now: Long) {
lastIndex = (lastIndex + 1) % amount
timestamps[lastIndex] = now
if (currentSize < amount) {
currentSize += 1
}
}
private fun clearTimestamps(now: Long) {
var headIndex = (amount + lastIndex + 1 - currentSize) % amount
while (currentSize > 0 && timestamps[headIndex] + perMillis <= now) {
headIndex = (headIndex + 1) % amount
currentSize -= 1
}
}
private fun isTimestampApplicable(timestamp: Long): Boolean =
currentSize == 0 || timestamp >= timestamps[lastIndex]
} | apache-2.0 | 577f2c93de0ccce0a6caefdc861817a7 | 25.23913 | 158 | 0.669983 | 4.246479 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveEmptyPrimaryConstructorIntention.kt | 1 | 1473 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection
import org.jetbrains.kotlin.idea.util.isExpectDeclaration
import org.jetbrains.kotlin.psi.KtPrimaryConstructor
import org.jetbrains.kotlin.psi.psiUtil.containingClass
@Suppress("DEPRECATION")
class RemoveEmptyPrimaryConstructorInspection : IntentionBasedInspection<KtPrimaryConstructor>(
RemoveEmptyPrimaryConstructorIntention::class
), CleanupLocalInspectionTool
class RemoveEmptyPrimaryConstructorIntention : SelfTargetingOffsetIndependentIntention<KtPrimaryConstructor>(
KtPrimaryConstructor::class.java,
KotlinBundle.lazyMessage("remove.empty.primary.constructor")
) {
override fun applyTo(element: KtPrimaryConstructor, editor: Editor?) = element.delete()
override fun isApplicableTo(element: KtPrimaryConstructor) = when {
element.valueParameters.isNotEmpty() -> false
element.annotations.isNotEmpty() -> false
element.modifierList?.text?.isBlank() == false -> false
element.containingClass()?.secondaryConstructors?.isNotEmpty() == true -> false
element.isExpectDeclaration() -> false
else -> true
}
}
| apache-2.0 | fa429de29bca76935843440fc53ea0c1 | 43.636364 | 120 | 0.794976 | 5.31769 | false | false | false | false |
DreierF/MyTargets | app/src/main/java/de/dreier/mytargets/features/settings/backup/provider/DriveServiceHelper.kt | 1 | 5397 | /*
* Copyright (C) 2019 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.features.settings.backup.provider
import android.content.ContentResolver
import android.content.Intent
import android.net.Uri
import android.provider.OpenableColumns
import com.google.android.gms.tasks.Task
import com.google.android.gms.tasks.Tasks
import com.google.api.services.drive.Drive
import com.google.api.services.drive.model.File
import com.google.api.services.drive.model.FileList
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.util.concurrent.Callable
import java.util.concurrent.Executors
/**
* A utility for performing read/write operations on Drive files via the REST API and opening a
* file picker UI via Storage Access Framework.
*/
class DriveServiceHelper(private val mDriveService: Drive) {
private val executor = Executors.newSingleThreadExecutor()
/**
* Creates a text file in the user's My Drive folder and returns its file ID.
*/
fun createFile(): Task<String> {
return Tasks.call(executor, Callable<String> {
val metadata = File()
.setParents(listOf("root"))
.setMimeType("text/plain")
.setName("Untitled file")
val googleFile = mDriveService.files().create(metadata).execute()
?: throw IOException("Null result when requesting file creation.")
googleFile.id
})
}
/**
* Opens the file identified by `fileId` and returns a [Pair] of its name and
* contents.
*/
fun readFile(fileId: String, consume: (InputStream) -> Unit): Task<Unit> {
return Tasks.call(executor, Callable<Unit> {
val inputStream = mDriveService.files().get(fileId).executeMediaAsInputStream()
consume(inputStream)
})
}
/**
* Updates the file identified by `fileId` with the given `name` and `content`.
*/
fun deleteFile(fileId: String): Task<Void> {
return Tasks.call(executor, Callable<Void> {
mDriveService.files().delete(fileId).execute()
null
})
}
/**
* Returns a [FileList] containing all the visible files in the user's My Drive.
*
*
* The returned list will only contain files visible to this app, i.e. those which were
* created by this app. To perform operations on files not created by the app, the project must
* request Drive Full Scope in the [Google
* Developer's Console](https://play.google.com/apps/publish) and be submitted to Google for verification.
*/
fun queryFiles(): Task<FileList> {
return Tasks.call(
executor,
Callable<FileList> {
mDriveService.files().list()
.setQ("mimeType = '${GoogleDriveBackup.MYTARGETS_MIME_TYPE}'")
.setFields("files(id,name,modifiedTime,trashed,size)")
.setSpaces("drive,appDataFolder").execute()
})
}
/**
* Returns an [Intent] for opening the Storage Access Framework file picker.
*/
fun createFilePickerIntent(): Intent {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "text/plain"
return intent
}
/**
* Opens the file at the `uri` returned by a Storage Access Framework [Intent]
* created by [.createFilePickerIntent] using the given `contentResolver`.
*/
fun openFileUsingStorageAccessFramework(
contentResolver: ContentResolver, uri: Uri
): Task<Pair<String, String>> {
return Tasks.call(executor, Callable<Pair<String, String>> {
// Retrieve the document's display name from its metadata.
var name = ""
contentResolver.query(uri, null, null, null, null).use()
{ cursor ->
if (cursor != null && cursor.moveToFirst()) {
val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
name = cursor.getString(nameIndex)
} else {
throw IOException("Empty cursor returned for file.")
}
}
// Read the document's contents as a String.
var content = ""
contentResolver.openInputStream(uri)!!.use()
{ `is` ->
BufferedReader(InputStreamReader(`is`)).use { reader ->
val stringBuilder = StringBuilder()
var line: String? = reader.readLine()
while (line != null) {
stringBuilder.append(line)
line = reader.readLine()
}
content = stringBuilder.toString()
}
}
Pair(name, content)
})
}
} | gpl-2.0 | fb98f6d2130c65ec3fa2e710080e694d | 35.721088 | 106 | 0.622198 | 4.705318 | false | false | false | false |
zbeboy/ISY | src/main/java/top/zbeboy/isy/service/graduate/design/GraduationDesignDatumServiceImpl.kt | 1 | 21424 | package top.zbeboy.isy.service.graduate.design
import org.apache.commons.lang.math.NumberUtils
import org.jooq.*
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Propagation
import org.springframework.transaction.annotation.Transactional
import org.springframework.util.ObjectUtils
import org.springframework.util.StringUtils
import top.zbeboy.isy.domain.tables.daos.GraduationDesignDatumDao
import top.zbeboy.isy.service.plugin.DataTablesPlugin
import top.zbeboy.isy.web.bean.graduate.design.proposal.GraduationDesignDatumBean
import javax.annotation.Resource
import top.zbeboy.isy.domain.Tables.*
import top.zbeboy.isy.domain.tables.pojos.GraduationDesignDatum
import top.zbeboy.isy.service.util.SQLQueryUtils
import top.zbeboy.isy.web.util.DataTablesUtils
import java.util.*
/**
* Created by zbeboy 2018-01-29 .
**/
@Service("graduationDesignDatumService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
open class GraduationDesignDatumServiceImpl @Autowired constructor(dslContext: DSLContext) : DataTablesPlugin<GraduationDesignDatumBean>(), GraduationDesignDatumService {
private val create: DSLContext = dslContext
@Resource
open lateinit var graduationDesignDatumDao: GraduationDesignDatumDao
override fun findById(id: String): GraduationDesignDatum {
return graduationDesignDatumDao.findById(id)
}
override fun findByIdRelation(id: String): Optional<Record> {
return create.select()
.from(GRADUATION_DESIGN_DATUM)
.join(FILES)
.on(GRADUATION_DESIGN_DATUM.FILE_ID.eq(FILES.FILE_ID))
.join(GRADUATION_DESIGN_TUTOR)
.on(GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_TUTOR_ID.eq(GRADUATION_DESIGN_TUTOR.GRADUATION_DESIGN_TUTOR_ID))
.join(GRADUATION_DESIGN_TEACHER)
.on(GRADUATION_DESIGN_TUTOR.GRADUATION_DESIGN_TEACHER_ID.eq(GRADUATION_DESIGN_TEACHER.GRADUATION_DESIGN_TEACHER_ID))
.where(GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_DATUM_ID.eq(id))
.fetchOptional()
}
override fun findByGraduationDesignTutorIdAndGraduationDesignDatumTypeId(graduationDesignTutorId: String, graduationDesignDatumTypeId: Int): Optional<Record> {
return create.select()
.from(GRADUATION_DESIGN_DATUM)
.join(GRADUATION_DESIGN_TUTOR)
.on(GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_TUTOR_ID.eq(GRADUATION_DESIGN_TUTOR.GRADUATION_DESIGN_TUTOR_ID))
.where(GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_TUTOR_ID.eq(graduationDesignTutorId).and(GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_DATUM_TYPE_ID.eq(graduationDesignDatumTypeId)))
.fetchOptional()
}
override fun findAllByPage(dataTablesUtils: DataTablesUtils<GraduationDesignDatumBean>, graduationDesignDatumBean: GraduationDesignDatumBean): Result<Record> {
var a = searchCondition(dataTablesUtils)
a = otherCondition(a, graduationDesignDatumBean)
return if (ObjectUtils.isEmpty(a)) {
val selectJoinStep = create.select()
.from(GRADUATION_DESIGN_DATUM)
.join(FILES)
.on(GRADUATION_DESIGN_DATUM.FILE_ID.eq(FILES.FILE_ID))
.join(GRADUATION_DESIGN_DATUM_TYPE)
.on(GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_DATUM_TYPE_ID.eq(GRADUATION_DESIGN_DATUM_TYPE.GRADUATION_DESIGN_DATUM_TYPE_ID))
sortCondition(dataTablesUtils, null, selectJoinStep, DataTablesPlugin.JOIN_TYPE)
pagination(dataTablesUtils, null, selectJoinStep, DataTablesPlugin.JOIN_TYPE)
selectJoinStep.fetch()
} else {
val selectConditionStep = create.select()
.from(GRADUATION_DESIGN_DATUM)
.join(FILES)
.on(GRADUATION_DESIGN_DATUM.FILE_ID.eq(FILES.FILE_ID))
.join(GRADUATION_DESIGN_DATUM_TYPE)
.on(GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_DATUM_TYPE_ID.eq(GRADUATION_DESIGN_DATUM_TYPE.GRADUATION_DESIGN_DATUM_TYPE_ID))
.where(a)
sortCondition(dataTablesUtils, selectConditionStep, null, DataTablesPlugin.CONDITION_TYPE)
pagination(dataTablesUtils, selectConditionStep, null, DataTablesPlugin.CONDITION_TYPE)
selectConditionStep.fetch()
}
}
override fun countAll(graduationDesignDatumBean: GraduationDesignDatumBean): Int {
val count: Record1<Int>
val a = otherCondition(null, graduationDesignDatumBean)
count = if (ObjectUtils.isEmpty(a)) {
create.selectCount()
.from(GRADUATION_DESIGN_DATUM)
.fetchOne()
} else {
create.selectCount()
.from(GRADUATION_DESIGN_DATUM)
.join(FILES)
.on(GRADUATION_DESIGN_DATUM.FILE_ID.eq(FILES.FILE_ID))
.join(GRADUATION_DESIGN_DATUM_TYPE)
.on(GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_DATUM_TYPE_ID.eq(GRADUATION_DESIGN_DATUM_TYPE.GRADUATION_DESIGN_DATUM_TYPE_ID))
.where(a)
.fetchOne()
}
return count.value1()
}
override fun countByCondition(dataTablesUtils: DataTablesUtils<GraduationDesignDatumBean>, graduationDesignDatumBean: GraduationDesignDatumBean): Int {
val count: Record1<Int>
var a = searchCondition(dataTablesUtils)
a = otherCondition(a, graduationDesignDatumBean)
count = if (ObjectUtils.isEmpty(a)) {
val selectJoinStep = create.selectCount()
.from(GRADUATION_DESIGN_DATUM)
selectJoinStep.fetchOne()
} else {
val selectConditionStep = create.selectCount()
.from(GRADUATION_DESIGN_DATUM)
.join(FILES)
.on(GRADUATION_DESIGN_DATUM.FILE_ID.eq(FILES.FILE_ID))
.join(GRADUATION_DESIGN_DATUM_TYPE)
.on(GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_DATUM_TYPE_ID.eq(GRADUATION_DESIGN_DATUM_TYPE.GRADUATION_DESIGN_DATUM_TYPE_ID))
.where(a)
selectConditionStep.fetchOne()
}
return count.value1()
}
override fun findTeamAllByPage(dataTablesUtils: DataTablesUtils<GraduationDesignDatumBean>, graduationDesignDatumBean: GraduationDesignDatumBean): Result<Record> {
var a = searchCondition(dataTablesUtils)
a = otherCondition(a, graduationDesignDatumBean)
return if (ObjectUtils.isEmpty(a)) {
val selectJoinStep = create.select()
.from(GRADUATION_DESIGN_DATUM)
.join(FILES)
.on(GRADUATION_DESIGN_DATUM.FILE_ID.eq(FILES.FILE_ID))
.join(GRADUATION_DESIGN_DATUM_TYPE)
.on(GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_DATUM_TYPE_ID.eq(GRADUATION_DESIGN_DATUM_TYPE.GRADUATION_DESIGN_DATUM_TYPE_ID))
.join(GRADUATION_DESIGN_TUTOR)
.on(GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_TUTOR_ID.eq(GRADUATION_DESIGN_TUTOR.GRADUATION_DESIGN_TUTOR_ID))
.join(GRADUATION_DESIGN_TEACHER)
.on(GRADUATION_DESIGN_TUTOR.GRADUATION_DESIGN_TEACHER_ID.eq(GRADUATION_DESIGN_TEACHER.GRADUATION_DESIGN_TEACHER_ID))
.join(STUDENT)
.on(GRADUATION_DESIGN_TUTOR.STUDENT_ID.eq(STUDENT.STUDENT_ID))
.join(USERS)
.on(STUDENT.USERNAME.eq(USERS.USERNAME))
.join(ORGANIZE)
.on(STUDENT.ORGANIZE_ID.eq(ORGANIZE.ORGANIZE_ID))
sortCondition(dataTablesUtils, null, selectJoinStep, DataTablesPlugin.JOIN_TYPE)
pagination(dataTablesUtils, null, selectJoinStep, DataTablesPlugin.JOIN_TYPE)
selectJoinStep.fetch()
} else {
val selectConditionStep = create.select()
.from(GRADUATION_DESIGN_DATUM)
.join(FILES)
.on(GRADUATION_DESIGN_DATUM.FILE_ID.eq(FILES.FILE_ID))
.join(GRADUATION_DESIGN_DATUM_TYPE)
.on(GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_DATUM_TYPE_ID.eq(GRADUATION_DESIGN_DATUM_TYPE.GRADUATION_DESIGN_DATUM_TYPE_ID))
.join(GRADUATION_DESIGN_TUTOR)
.on(GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_TUTOR_ID.eq(GRADUATION_DESIGN_TUTOR.GRADUATION_DESIGN_TUTOR_ID))
.join(GRADUATION_DESIGN_TEACHER)
.on(GRADUATION_DESIGN_TUTOR.GRADUATION_DESIGN_TEACHER_ID.eq(GRADUATION_DESIGN_TEACHER.GRADUATION_DESIGN_TEACHER_ID))
.join(STUDENT)
.on(GRADUATION_DESIGN_TUTOR.STUDENT_ID.eq(STUDENT.STUDENT_ID))
.join(USERS)
.on(STUDENT.USERNAME.eq(USERS.USERNAME))
.join(ORGANIZE)
.on(STUDENT.ORGANIZE_ID.eq(ORGANIZE.ORGANIZE_ID))
.where(a)
sortCondition(dataTablesUtils, selectConditionStep, null, DataTablesPlugin.CONDITION_TYPE)
pagination(dataTablesUtils, selectConditionStep, null, DataTablesPlugin.CONDITION_TYPE)
selectConditionStep.fetch()
}
}
override fun countTeamAll(graduationDesignDatumBean: GraduationDesignDatumBean): Int {
val count: Record1<Int>
val a = otherCondition(null, graduationDesignDatumBean)
count = if (ObjectUtils.isEmpty(a)) {
create.selectCount()
.from(GRADUATION_DESIGN_DATUM)
.fetchOne()
} else {
create.selectCount()
.from(GRADUATION_DESIGN_DATUM)
.join(FILES)
.on(GRADUATION_DESIGN_DATUM.FILE_ID.eq(FILES.FILE_ID))
.join(GRADUATION_DESIGN_DATUM_TYPE)
.on(GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_DATUM_TYPE_ID.eq(GRADUATION_DESIGN_DATUM_TYPE.GRADUATION_DESIGN_DATUM_TYPE_ID))
.join(GRADUATION_DESIGN_TUTOR)
.on(GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_TUTOR_ID.eq(GRADUATION_DESIGN_TUTOR.GRADUATION_DESIGN_TUTOR_ID))
.join(GRADUATION_DESIGN_TEACHER)
.on(GRADUATION_DESIGN_TUTOR.GRADUATION_DESIGN_TEACHER_ID.eq(GRADUATION_DESIGN_TEACHER.GRADUATION_DESIGN_TEACHER_ID))
.join(STUDENT)
.on(GRADUATION_DESIGN_TUTOR.STUDENT_ID.eq(STUDENT.STUDENT_ID))
.join(USERS)
.on(STUDENT.USERNAME.eq(USERS.USERNAME))
.join(ORGANIZE)
.on(STUDENT.ORGANIZE_ID.eq(ORGANIZE.ORGANIZE_ID))
.where(a)
.fetchOne()
}
return count.value1()
}
override fun countTeamByCondition(dataTablesUtils: DataTablesUtils<GraduationDesignDatumBean>, graduationDesignDatumBean: GraduationDesignDatumBean): Int {
val count: Record1<Int>
var a = searchCondition(dataTablesUtils)
a = otherCondition(a, graduationDesignDatumBean)
count = if (ObjectUtils.isEmpty(a)) {
val selectJoinStep = create.selectCount()
.from(GRADUATION_DESIGN_DATUM)
selectJoinStep.fetchOne()
} else {
val selectConditionStep = create.selectCount()
.from(GRADUATION_DESIGN_DATUM)
.join(FILES)
.on(GRADUATION_DESIGN_DATUM.FILE_ID.eq(FILES.FILE_ID))
.join(GRADUATION_DESIGN_DATUM_TYPE)
.on(GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_DATUM_TYPE_ID.eq(GRADUATION_DESIGN_DATUM_TYPE.GRADUATION_DESIGN_DATUM_TYPE_ID))
.join(GRADUATION_DESIGN_TUTOR)
.on(GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_TUTOR_ID.eq(GRADUATION_DESIGN_TUTOR.GRADUATION_DESIGN_TUTOR_ID))
.join(GRADUATION_DESIGN_TEACHER)
.on(GRADUATION_DESIGN_TUTOR.GRADUATION_DESIGN_TEACHER_ID.eq(GRADUATION_DESIGN_TEACHER.GRADUATION_DESIGN_TEACHER_ID))
.join(STUDENT)
.on(GRADUATION_DESIGN_TUTOR.STUDENT_ID.eq(STUDENT.STUDENT_ID))
.join(USERS)
.on(STUDENT.USERNAME.eq(USERS.USERNAME))
.join(ORGANIZE)
.on(STUDENT.ORGANIZE_ID.eq(ORGANIZE.ORGANIZE_ID))
.where(a)
selectConditionStep.fetchOne()
}
return count.value1()
}
override fun update(graduationDesignDatum: GraduationDesignDatum) {
graduationDesignDatumDao.update(graduationDesignDatum)
}
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
override fun save(graduationDesignDatum: GraduationDesignDatum) {
graduationDesignDatumDao.insert(graduationDesignDatum)
}
override fun deleteById(id: String) {
graduationDesignDatumDao.deleteById(id)
}
/**
* 其它条件
*
* @param graduationDesignDatumBean 条件
* @return 条件
*/
fun otherCondition(a: Condition?, graduationDesignDatumBean: GraduationDesignDatumBean): Condition? {
var tempCondition = a
if (!ObjectUtils.isEmpty(graduationDesignDatumBean)) {
if (StringUtils.hasLength(graduationDesignDatumBean.graduationDesignTutorId)) {
tempCondition = if (!ObjectUtils.isEmpty(tempCondition)) {
tempCondition!!.and(GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_TUTOR_ID.eq(graduationDesignDatumBean.graduationDesignTutorId))
} else {
GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_TUTOR_ID.eq(graduationDesignDatumBean.graduationDesignTutorId)
}
}
if (StringUtils.hasLength(graduationDesignDatumBean.graduationDesignReleaseId)) {
tempCondition = if (!ObjectUtils.isEmpty(tempCondition)) {
tempCondition!!.and(GRADUATION_DESIGN_TEACHER.GRADUATION_DESIGN_RELEASE_ID.eq(graduationDesignDatumBean.graduationDesignReleaseId))
} else {
GRADUATION_DESIGN_TEACHER.GRADUATION_DESIGN_RELEASE_ID.eq(graduationDesignDatumBean.graduationDesignReleaseId)
}
}
if (!ObjectUtils.isEmpty(graduationDesignDatumBean.staffId) && graduationDesignDatumBean.staffId > 0) {
tempCondition = if (!ObjectUtils.isEmpty(tempCondition)) {
tempCondition!!.and(GRADUATION_DESIGN_TEACHER.STAFF_ID.eq(graduationDesignDatumBean.staffId))
} else {
GRADUATION_DESIGN_TEACHER.STAFF_ID.eq(graduationDesignDatumBean.staffId)
}
}
}
return tempCondition
}
/**
* 全局搜索条件
*
* @param dataTablesUtils datatables工具类
* @return 搜索条件
*/
override fun searchCondition(dataTablesUtils: DataTablesUtils<GraduationDesignDatumBean>): Condition? {
var a: Condition? = null
val search = dataTablesUtils.search
if (!ObjectUtils.isEmpty(search)) {
val originalFileName = StringUtils.trimWhitespace(search!!.getString("originalFileName"))
val graduationDesignDatumTypeName = StringUtils.trimWhitespace(search.getString("graduationDesignDatumTypeName"))
val studentName = StringUtils.trimWhitespace(search.getString("studentName"))
val studentNumber = StringUtils.trimWhitespace(search.getString("studentNumber"))
if (StringUtils.hasLength(originalFileName)) {
a = FILES.ORIGINAL_FILE_NAME.like(SQLQueryUtils.likeAllParam(originalFileName))
}
if (StringUtils.hasLength(graduationDesignDatumTypeName)) {
val graduationDesignDatumTypeId = NumberUtils.toInt(graduationDesignDatumTypeName)
if (graduationDesignDatumTypeId > 0) {
a = if (ObjectUtils.isEmpty(a)) {
GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_DATUM_TYPE_ID.eq(graduationDesignDatumTypeId)
} else {
a!!.and(GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_DATUM_TYPE_ID.eq(graduationDesignDatumTypeId))
}
}
}
if (StringUtils.hasLength(studentName)) {
a = if (ObjectUtils.isEmpty(a)) {
USERS.REAL_NAME.like(SQLQueryUtils.likeAllParam(studentName))
} else {
a!!.and(USERS.REAL_NAME.like(SQLQueryUtils.likeAllParam(studentName)))
}
}
if (StringUtils.hasLength(studentNumber)) {
a = if (ObjectUtils.isEmpty(a)) {
STUDENT.STUDENT_NUMBER.like(SQLQueryUtils.likeAllParam(studentNumber))
} else {
a!!.and(STUDENT.STUDENT_NUMBER.like(SQLQueryUtils.likeAllParam(studentNumber)))
}
}
}
return a
}
/**
* 数据排序
*
* @param dataTablesUtils datatables工具类
* @param selectConditionStep 条件
*/
override fun sortCondition(dataTablesUtils: DataTablesUtils<GraduationDesignDatumBean>, selectConditionStep: SelectConditionStep<Record>?, selectJoinStep: SelectJoinStep<Record>?, type: Int) {
val orderColumnName = dataTablesUtils.orderColumnName
val orderDir = dataTablesUtils.orderDir
val isAsc = "asc".equals(orderDir, ignoreCase = true)
var sortField: Array<SortField<*>?>? = null
if (StringUtils.hasLength(orderColumnName)) {
if ("real_name".equals(orderColumnName!!, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = USERS.REAL_NAME.asc()
sortField[1] = GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_DATUM_ID.asc()
} else {
sortField[0] = USERS.REAL_NAME.desc()
sortField[1] = GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_DATUM_ID.desc()
}
}
if ("student_number".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(1)
if (isAsc) {
sortField[0] = STUDENT.STUDENT_NUMBER.asc()
} else {
sortField[0] = STUDENT.STUDENT_NUMBER.desc()
}
}
if ("organize_name".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = ORGANIZE.ORGANIZE_NAME.asc()
sortField[1] = GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_DATUM_ID.asc()
} else {
sortField[0] = ORGANIZE.ORGANIZE_NAME.desc()
sortField[1] = GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_DATUM_ID.desc()
}
}
if ("original_file_name".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = FILES.ORIGINAL_FILE_NAME.asc()
sortField[1] = GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_DATUM_ID.asc()
} else {
sortField[0] = GRADUATION_DESIGN_PRESUBJECT.PRESUBJECT_TITLE.desc()
sortField[1] = GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_DATUM_ID.desc()
}
}
if ("graduation_design_datum_type_name".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_DATUM_TYPE_ID.asc()
sortField[1] = GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_DATUM_ID.asc()
} else {
sortField[0] = GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_DATUM_TYPE_ID.desc()
sortField[1] = GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_DATUM_ID.desc()
}
}
if ("version".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(2)
if (isAsc) {
sortField[0] = GRADUATION_DESIGN_DATUM.VERSION.asc()
sortField[1] = GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_DATUM_ID.asc()
} else {
sortField[0] = GRADUATION_DESIGN_DATUM.VERSION.desc()
sortField[1] = GRADUATION_DESIGN_DATUM.GRADUATION_DESIGN_DATUM_ID.desc()
}
}
if ("update_time".equals(orderColumnName, ignoreCase = true)) {
sortField = arrayOfNulls(1)
if (isAsc) {
sortField[0] = GRADUATION_DESIGN_DATUM.UPDATE_TIME.asc()
} else {
sortField[0] = GRADUATION_DESIGN_DATUM.UPDATE_TIME.desc()
}
}
}
sortToFinish(selectConditionStep, selectJoinStep, type, *sortField!!)
}
} | mit | 80eeeef2608507cad9540c763c01d4a4 | 49.748219 | 196 | 0.614679 | 4.613258 | false | false | false | false |
esafirm/android-playground | app/src/main/java/com/esafirm/androidplayground/network/OkHttpCacheSetup.kt | 1 | 1131 | package com.esafirm.androidplayground.network
import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File
/**
* This turns out to be just a desktop playground
*/
fun main() {
val cache = File("/Users/esafirman/Desktop", "http_cache")
if (cache.exists().not()) {
cache.mkdirs()
}
val client = OkHttpClient.Builder()
.cache(Cache(
directory = File("/Users/esafirman/Desktop", "http_cache"),
maxSize = 50L * 1024L * 1024L // 50 MiB
))
.build()
client.request("Calling #1")
client.request("Calling #1")
Thread.sleep(500)
}
private fun OkHttpClient.request(id: String) {
println(id)
val request = Request.Builder()
.url("http://localhost:8080/")
.header("X-Custom-Id", id)
.build()
val res = newCall(request).execute()
println("headers: ${res.headers.toMap()}")
println("body: ${res.body?.string()}")
println("""
cache res: ${res.cacheResponse}
network res: ${res.networkResponse}
""".trimIndent())
} | mit | 554e7a815d6736b0c116e8ff2d848887 | 23.085106 | 79 | 0.585323 | 3.996466 | false | false | false | false |
esafirm/android-playground | app/src/main/java/com/esafirm/androidplayground/serialize/ObjectSerializationController.kt | 1 | 1332 | package com.esafirm.androidplayground.serialize
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.esafirm.androidplayground.common.BaseController
import com.esafirm.androidplayground.libs.Logger
import com.esafirm.androidplayground.utils.button
import com.esafirm.androidplayground.utils.logger
import com.esafirm.androidplayground.utils.row
import kotlinx.serialization.Serializable
@Serializable
data class ObjectWithDefault(
val a: String = "a",
val b: String? = "b"
)
class ObjectSerializationController : BaseController() {
private val adapter = KotlinJsonAdapterFactory()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View {
return row {
button("Serialize") {
val defaultObj = ObjectWithDefault("abc ")
val result = adapter.of(ObjectWithDefault.serializer()).to(defaultObj)
Logger.log("default obj a:${defaultObj.a} b:${defaultObj.b}")
Logger.log(result)
}
button("Deserialize") {
val json = """
{ "a": "abc" }
""".trimIndent()
Logger.log(adapter.of(ObjectWithDefault.serializer()).from(json))
}
logger()
}
}
}
| mit | 98f9c063aa8d0d585170997fa3e041cd | 30.714286 | 86 | 0.652402 | 4.791367 | false | false | false | false |
neilellis/kontrol | sensors/src/main/kotlin/kontrol/impl/sensor/HttpStatusSensor.kt | 1 | 2071 | /*
* Copyright 2014 Cazcade Limited (http://cazcade.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kontrol.sensor
import kontrol.api.Sensor
import kontrol.api.Machine
import kontrol.api.sensor.SensorValue
import java.net.URL
import java.util.Locale
import kontrol.HttpUtil
import java.net.URI
/**
* @todo document.
* @author <a href="http://uk.linkedin.com/in/neilellis">Neil Ellis</a>
*/
public class HttpStatusSensor(val path: String, val port: Int = 80) : Sensor {
override fun name(): String {
return if (this.port == 80) "http-status" else ("http-status-" + port);
}
override fun value(machine: Machine): SensorValue {
try {
return SensorValue(name(), when {
machine.hostname().isNotEmpty() -> {
val url: URI;
if (path.startsWith("http:") || path.startsWith("https:")) {
url = URL(path).toURI()
} else {
url = URL("http", machine.hostname(), port, path).toURI()
}
val status = HttpUtil.getStatus(url, Locale.getDefault(), 30 * 60 * 1000)
// println("url responded with $status")
status;
}
else -> {
null
}
});
} catch (e: Exception) {
println("HttpStatusSensor: ${e.javaClass} for ${machine.name()}")
return SensorValue(name(), -1);
}
}
} | apache-2.0 | d51ff9b7fc4f64990462fd1c5b174808 | 31.375 | 93 | 0.57605 | 4.397028 | false | false | false | false |
java-graphics/assimp | src/main/kotlin/assimp/format/fbx/fbxImporter.kt | 2 | 5626 | /*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2017, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
package assimp.format.fbx
import assimp.*
import assimp.format.AiConfig
import java.nio.*
/** @file FbxImporter.h
* @brief Declaration of the FBX main importer class */
// TinyFormatter.h
//namespace Formatter {
// template < typename T, typename TR, typename A> class basic_formatter
// typedef class basic_formatter<char, std::char_traits<char>, std::allocator<char> > format
//}
// -------------------------------------------------------------------------------------------
/** Load the Autodesk FBX file format.
See http://en.wikipedia.org/wiki/FBX
*/
// -------------------------------------------------------------------------------------------
class FbxImporter : BaseImporter() {
val settings = ImportSettings()
override fun canRead(file: String, ioSystem: IOSystem, checkSig: Boolean): Boolean {
val extension = getExtension(file)
if (extension == info.fileExtensions[0]) return true
else if (extension.isEmpty() || checkSig) {
TODO()
// at least ASCII-FBX files usually have a 'FBX' somewhere in their head
// const char * tokens [] = { "fbx" };
// return SearchFileHeaderForToken(pIOHandler, pFile, tokens, 1);
}
return false
}
override val info
get() = AiImporterDesc(
name = "Autodesk FBX Importer",
flags = AiImporterFlags.SupportTextFlavour.i,
fileExtensions = listOf("fbx")
)
override fun setupProperties(imp: Importer) {
with(settings) {
with(AiConfig.Import.Fbx.Read) {
readAllLayers = imp[ALL_GEOMETRY_LAYERS] ?: true
readAllMaterials = imp[ALL_MATERIALS] ?: false
readMaterials = imp[MATERIALS] ?: true
readTextures = imp[TEXTURES] ?: true
readCameras = imp[CAMERAS] ?: true
readLights = imp[LIGHTS] ?: true
readAnimations = imp[ANIMATIONS] ?: true
}
with(AiConfig.Import.Fbx) {
strictMode = imp[STRICT_MODE] ?: false
preservePivots = imp[PRESERVE_PIVOTS] ?: true
optimizeEmptyAnimationCurves = imp[OPTIMIZE_EMPTY_ANIMATION_CURVES] ?: true
searchEmbeddedTextures = imp[SEARCH_EMBEDDED_TEXTURES] ?: false
}
}
}
override fun internReadFile(file: String, ioSystem: IOSystem, scene: AiScene) {
/* read entire file into memory - no streaming for this, fbx files can grow large, but the assimp output data
structure then becomes very large, too. Assimp doesn't support streaming for its output data structures so
the net win with streaming input data would be very low. */
val input = ioSystem.open(file).readBytes()
/* broadphase tokenizing pass in which we identify the core syntax elements of FBX (brackets, commas,
key:value mappings) */
val tokens = ArrayList<Token>()
// try {
buffer = input
var isBinary = false
if (input.startsWith("Kaydara FBX Binary")) {
isBinary = true
tokenizeBinary(tokens, input)
} else tokenize(tokens, input)
// use this information to construct a very rudimentary parse-tree representing the FBX scope structure
val parser = Parser(tokens, isBinary)
// take the raw parse-tree and convert it to a FBX DOM
val doc = Document(parser, settings)
// convert the FBX DOM to aiScene
convertToAssimpScene(scene, doc)
//
// std::for_each(tokens.begin(),tokens.end(),Util::delete_fun<Token>());
// }
// catch(exc: Exception) {
//// std::for_each(tokens.begin(),tokens.end(),Util::delete_fun<Token>());
// throw Exception(exc.toString())
// }
}
}
lateinit var buffer: ByteBuffer | bsd-3-clause | 6ad22dbec2fe53e56266fe842c9c0ee9 | 38.076389 | 118 | 0.625133 | 4.723762 | false | false | false | false |
apollographql/apollo-android | apollo-ast/src/main/kotlin/com/apollographql/apollo3/ast/Schema.kt | 1 | 6389 | package com.apollographql.apollo3.ast
import com.apollographql.apollo3.annotations.ApolloExperimental
import com.apollographql.apollo3.ast.internal.buffer
import okio.Buffer
/**
* A wrapper around a schema GQLDocument that:
* - always contain builtin types contrary to introspection that will not contain directives and SDL that will not contain
* any builtin definitions
* - always has a schema definition
* - has type extensions merged
* - has some helper functions to retrieve a type by name and/or possible types
*
* @param definitions a list of validated and merged definitions
*/
class Schema(
private val definitions: List<GQLDefinition>,
) {
val typeDefinitions: Map<String, GQLTypeDefinition> = definitions
.filterIsInstance<GQLTypeDefinition>()
.associateBy { it.name }
val directiveDefinitions: Map<String, GQLDirectiveDefinition> = definitions
.filterIsInstance<GQLDirectiveDefinition>()
.associateBy { it.name }
val queryTypeDefinition: GQLTypeDefinition = rootOperationTypeDefinition("query")
?: throw SchemaValidationException("No query root type found")
val mutationTypeDefinition: GQLTypeDefinition? = rootOperationTypeDefinition("mutation")
val subscriptionTypeDefinition: GQLTypeDefinition? = rootOperationTypeDefinition("subscription")
fun toGQLDocument(): GQLDocument = GQLDocument(
definitions = definitions,
filePath = null
).withoutBuiltinDefinitions()
private fun rootOperationTypeDefinition(operationType: String): GQLTypeDefinition? {
return definitions.filterIsInstance<GQLSchemaDefinition>().single()
.rootOperationTypeDefinitions
.singleOrNull {
it.operationType == operationType
}
?.namedType
?.let { namedType ->
definitions.filterIsInstance<GQLObjectTypeDefinition>().single { it.name == namedType }
}
}
fun typeDefinition(name: String): GQLTypeDefinition {
return typeDefinitions[name]
?: throw SchemaValidationException("Cannot find type `$name`")
}
fun possibleTypes(typeDefinition: GQLTypeDefinition): Set<String> {
return when (typeDefinition) {
is GQLUnionTypeDefinition -> typeDefinition.memberTypes.map { it.name }.toSet()
is GQLInterfaceTypeDefinition -> typeDefinitions.values.filter {
it is GQLObjectTypeDefinition && it.implementsInterfaces.contains(typeDefinition.name)
|| it is GQLInterfaceTypeDefinition && it.implementsInterfaces.contains(typeDefinition.name)
}.flatMap {
// Recurse until we reach the concrete types
// This could certainly be improved
possibleTypes(it).toList()
}.toSet()
is GQLObjectTypeDefinition -> setOf(typeDefinition.name)
is GQLScalarTypeDefinition -> setOf(typeDefinition.name)
is GQLEnumTypeDefinition -> typeDefinition.enumValues.map { it.name }.toSet()
else -> {
throw SchemaValidationException("Cannot determine possibleTypes of $typeDefinition.name")
}
}
}
fun possibleTypes(name: String): Set<String> {
return possibleTypes(typeDefinition(name))
}
fun implementedTypes(name: String): Set<String> {
val typeDefinition = typeDefinition(name)
return when (typeDefinition) {
is GQLObjectTypeDefinition -> typeDefinition.implementsInterfaces.flatMap { implementedTypes(it) }.toSet() + name
is GQLInterfaceTypeDefinition -> typeDefinition.implementsInterfaces.flatMap { implementedTypes(it) }.toSet() + name
is GQLUnionTypeDefinition,
is GQLScalarTypeDefinition,
is GQLEnumTypeDefinition,
-> setOf(name)
else -> error("Cannot determine implementedTypes of $name")
}
}
/**
* Returns the key fields for the given type
*
* If this type has one or multiple @[TYPE_POLICY] annotation(s), they are used, else it recurses in implemented interfaces until it
* finds some.
*
* Returns the emptySet if this type has no key fields.
*/
fun keyFields(name: String): Set<String> {
val typeDefinition = typeDefinition(name)
return when (typeDefinition) {
is GQLObjectTypeDefinition -> {
val kf = typeDefinition.directives.toKeyFields()
if (kf != null) {
kf
} else {
val kfs = typeDefinition.implementsInterfaces.map { it to keyFields(it) }.filter { it.second.isNotEmpty() }
if (kfs.isNotEmpty()) {
check(kfs.size == 1) {
val candidates = kfs.map { "${it.first}: ${it.second}" }.joinToString("\n")
"Object '$name' inherits different keys from different interfaces:\n$candidates\nSpecify @$TYPE_POLICY explicitely"
}
}
kfs.singleOrNull()?.second ?: emptySet()
}
}
is GQLInterfaceTypeDefinition -> {
val kf = typeDefinition.directives.toKeyFields()
if (kf != null) {
kf
} else {
val kfs = typeDefinition.implementsInterfaces.map { it to keyFields(it) }.filter { it.second.isNotEmpty() }
if (kfs.isNotEmpty()) {
check(kfs.size == 1) {
val candidates = kfs.map { "${it.first}: ${it.second}" }.joinToString("\n")
"Interface '$name' inherits different keys from different interfaces:\n$candidates\nSpecify @$TYPE_POLICY explicitely"
}
}
kfs.singleOrNull()?.second ?: emptySet()
}
}
is GQLUnionTypeDefinition -> typeDefinition.directives.toKeyFields() ?: emptySet()
else -> error("Type '$name' cannot have key fields")
}
}
/**
* Returns the key Fields or null if there's no directive
*/
private fun List<GQLDirective>.toKeyFields(): Set<String>? {
val directives = filter { it.name == TYPE_POLICY }
if (directives.isEmpty()) {
return null
}
@OptIn(ApolloExperimental::class)
return directives.flatMap {
(it.arguments!!.arguments.first().value as GQLStringValue).value.buffer().parseAsGQLSelections().valueAssertNoErrors().map { gqlSelection ->
// No need to check here, this should be done during validation
(gqlSelection as GQLField).name
}
}.toSet()
}
companion object {
const val TYPE_POLICY = "typePolicy"
const val FIELD_POLICY = "fieldPolicy"
const val FIELD_POLICY_FOR_FIELD = "forField"
const val FIELD_POLICY_KEY_ARGS = "keyArgs"
}
}
| mit | f8de55a92a1eb3ce20e424d7fcd24e96 | 37.957317 | 146 | 0.680232 | 4.673738 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/io/github/chrislo27/rhre3/sfxdb/datamodel/impl/CuePointer.kt | 2 | 2864 | package io.github.chrislo27.rhre3.sfxdb.datamodel.impl
import io.github.chrislo27.rhre3.entity.model.IVolumetric
import io.github.chrislo27.rhre3.sfxdb.SFXDatabase
import io.github.chrislo27.rhre3.sfxdb.json.CuePointerObject
fun CuePointerObject.toDatamodel(): CuePointer = CuePointer(this)
fun List<CuePointerObject>.mapToDatamodel(): List<CuePointer> = this.map(::CuePointer)
fun List<CuePointerObject>.mapToDatamodel(starSubstitution: String): List<CuePointer> = this.map { CuePointer(it, starSubstitution) }
fun List<CuePointer>.mapToJsonObject(): List<CuePointerObject> = this.map(CuePointer::toJsonObject)
fun List<CuePointer>.mapToJsonObject(starSubstitution: String): List<CuePointerObject> = this.map(CuePointer::toJsonObject).onEach {
if (it.id.startsWith(starSubstitution)) {
it.id = "*" + it.id.substringAfter(starSubstitution)
}
}
class CuePointer {
val id: String
val beat: Float
val backingDuration: Float
val track: Int
val semitone: Int
val volume: Int
val duration: Float
get() =
if (backingDuration <= 0f) {
SFXDatabase.data.objectMap[id]?.duration ?: error("$id does not exist")
} else {
backingDuration
}
val metadata: Map<String, Any?>
constructor(obj: CuePointerObject, starSubstitution: String?) {
id = if (starSubstitution == null) obj.id else obj.id.replace("*", starSubstitution)
beat = obj.beat
backingDuration = obj.duration
semitone = obj.semitone
volume = obj.volume.coerceAtLeast(0)
track = obj.track
metadata = obj.metadata ?: mapOf()
}
constructor(obj: CuePointerObject) : this(obj, null)
constructor(id: String, beat: Float, duration: Float = 0f, semitone: Int = 0, track: Int = 0,
volume: Int = IVolumetric.DEFAULT_VOLUME,
metadata: Map<String, Any?> = mapOf()) {
this.id = id
this.beat = beat
this.backingDuration = duration
this.semitone = semitone
this.track = track
this.volume = volume.coerceAtLeast(0)
this.metadata = metadata
}
fun toJsonObject(): CuePointerObject {
return CuePointerObject().also {
it.id = this.id
it.beat = this.beat
it.duration = this.backingDuration
it.semitone = this.semitone
it.volume = this.volume
it.track = this.track
it.metadata = this.metadata
}
}
fun copy(id: String = this.id, beat: Float = this.beat, duration: Float = this.duration, semitone: Int = this.semitone, track: Int = this.track,
volume: Int = this.volume,
metadata: Map<String, Any?> = this.metadata): CuePointer = CuePointer(id, beat, duration, semitone, track, volume, metadata)
} | gpl-3.0 | edecfe9adb95c6f0dcd5cca53e434c97 | 34.8125 | 148 | 0.644902 | 3.834003 | false | false | false | false |
allotria/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/comment/ui/GHPRDiffEditorReviewComponentsFactoryImpl.kt | 2 | 5414 | // 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.github.pullrequest.comment.ui
import com.intellij.diff.util.Side
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.util.NlsActions
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.codereview.comment.wrapComponentUsingRoundedPanel
import org.jetbrains.plugins.github.api.data.GHPullRequestReviewEvent
import org.jetbrains.plugins.github.api.data.GHUser
import org.jetbrains.plugins.github.api.data.request.GHPullRequestDraftReviewComment
import org.jetbrains.plugins.github.api.data.request.GHPullRequestDraftReviewThread
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.pullrequest.data.provider.GHPRReviewDataProvider
import org.jetbrains.plugins.github.pullrequest.ui.changes.GHPRCreateDiffCommentParametersHelper
import org.jetbrains.plugins.github.ui.avatars.GHAvatarIconsProvider
import org.jetbrains.plugins.github.util.successOnEdt
import javax.swing.JComponent
class GHPRDiffEditorReviewComponentsFactoryImpl
internal constructor(private val reviewDataProvider: GHPRReviewDataProvider,
private val createCommentParametersHelper: GHPRCreateDiffCommentParametersHelper,
private val avatarIconsProvider: GHAvatarIconsProvider,
private val currentUser: GHUser)
: GHPRDiffEditorReviewComponentsFactory {
override fun createThreadComponent(thread: GHPRReviewThreadModel): JComponent =
GHPRReviewThreadComponent.create(thread, reviewDataProvider, avatarIconsProvider, currentUser).apply {
border = JBUI.Borders.empty(8, 8)
}.let(::wrapComponentUsingRoundedPanel)
override fun createSingleCommentComponent(side: Side, line: Int, startLine: Int, hideCallback: () -> Unit): JComponent {
val textFieldModel = GHSubmittableTextFieldModel {
val filePath = createCommentParametersHelper.filePath
if (line == startLine) {
val commitSha = createCommentParametersHelper.commitSha
val diffLine = createCommentParametersHelper.findPosition(side, line) ?: error("Can't determine comment position")
reviewDataProvider.createReview(EmptyProgressIndicator(), GHPullRequestReviewEvent.COMMENT, null, commitSha,
listOf(GHPullRequestDraftReviewComment(it, filePath, diffLine))).successOnEdt {
hideCallback()
}
}
else {
reviewDataProvider.createThread(EmptyProgressIndicator(), null, it, line + 1, side, startLine + 1, filePath).successOnEdt {
hideCallback()
}
}
}
return createCommentComponent(textFieldModel, GithubBundle.message("pull.request.diff.editor.review.comment"), hideCallback)
}
override fun createNewReviewCommentComponent(side: Side, line: Int, startLine: Int, hideCallback: () -> Unit): JComponent {
val textFieldModel = GHSubmittableTextFieldModel {
val filePath = createCommentParametersHelper.filePath
val commitSha = createCommentParametersHelper.commitSha
if (line == startLine) {
val diffLine = createCommentParametersHelper.findPosition(side, line) ?: error("Can't determine comment position")
reviewDataProvider.createReview(EmptyProgressIndicator(), null, null, commitSha,
listOf(GHPullRequestDraftReviewComment(it, filePath, diffLine))).successOnEdt {
hideCallback()
}
}
else {
reviewDataProvider.createReview(EmptyProgressIndicator(), null, null, commitSha, null,
listOf(GHPullRequestDraftReviewThread(it, line + 1, filePath, side, startLine + 1, side)))
.successOnEdt {
hideCallback()
}
}
}
return createCommentComponent(textFieldModel, GithubBundle.message("pull.request.diff.editor.review.start"), hideCallback)
}
override fun createReviewCommentComponent(reviewId: String, side: Side, line: Int, startLine: Int, hideCallback: () -> Unit): JComponent {
val textFieldModel = GHSubmittableTextFieldModel {
val filePath = createCommentParametersHelper.filePath
if (line == startLine) {
val commitSha = createCommentParametersHelper.commitSha
val diffLine = createCommentParametersHelper.findPosition(side, line) ?: error("Can't determine comment position")
reviewDataProvider.addComment(EmptyProgressIndicator(), reviewId, it, commitSha, filePath, diffLine).successOnEdt {
hideCallback()
}
}
else {
reviewDataProvider.createThread(EmptyProgressIndicator(), reviewId, it, line + 1, side, startLine + 1, filePath).successOnEdt {
hideCallback()
}
}
}
return createCommentComponent(textFieldModel, GithubBundle.message("pull.request.diff.editor.review.comment"), hideCallback)
}
private fun createCommentComponent(
textFieldModel: GHSubmittableTextFieldModel,
@NlsActions.ActionText actionName: String,
hideCallback: () -> Unit
): JComponent =
GHSubmittableTextFieldFactory(textFieldModel).create(avatarIconsProvider, currentUser, actionName) {
hideCallback()
}.apply {
border = JBUI.Borders.empty(8)
}.let(::wrapComponentUsingRoundedPanel)
}
| apache-2.0 | 5fa401c4988cb8c92c6ebd0c336fde41 | 50.075472 | 140 | 0.737348 | 5.230918 | false | false | false | false |
android/wear-os-samples | ComposeAdvanced/app/src/main/java/com/example/android/wearable/composeadvanced/presentation/ui/watch/WatchDetailScreen.kt | 1 | 4419 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.wearable.composeadvanced.presentation.ui.watch
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.wear.compose.material.Icon
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.material.Text
import com.example.android.wearable.composeadvanced.R
import com.example.android.wearable.composeadvanced.data.WatchModel
import com.google.android.horologist.compose.navscaffold.scrollableColumn
@Composable
fun WatchDetailScreen(
viewModel: WatchDetailViewModel,
scrollState: ScrollState,
focusRequester: FocusRequester
) {
val watch by viewModel.watch
WatchDetailScreen(
watch = watch,
scrollState = scrollState,
focusRequester = focusRequester
)
}
/**
* Displays the icon, title, and description of the watch model.
*/
@Composable
fun WatchDetailScreen(
watch: WatchModel?,
scrollState: ScrollState,
focusRequester: FocusRequester,
modifier: Modifier = Modifier
) {
Column(
modifier = modifier
.fillMaxSize()
.scrollableColumn(focusRequester, scrollState)
.verticalScroll(scrollState)
.padding(
top = 26.dp,
start = 8.dp,
end = 8.dp,
bottom = 26.dp
),
verticalArrangement = Arrangement.Top
) {
if (watch == null) {
Text(
modifier = Modifier
.fillMaxSize()
.align(Alignment.CenterHorizontally),
color = Color.White,
textAlign = TextAlign.Center,
text = stringResource(R.string.invalid_watch_label)
)
} else {
Icon(
painter = painterResource(id = watch.icon),
tint = MaterialTheme.colors.primary,
contentDescription = stringResource(R.string.watch_icon_content_description),
modifier = Modifier
.fillMaxWidth()
.size(24.dp)
.wrapContentSize(align = Alignment.Center)
)
Spacer(modifier = Modifier.size(4.dp))
Text(
modifier = Modifier
.fillMaxWidth()
.align(Alignment.CenterHorizontally),
color = MaterialTheme.colors.primary,
textAlign = TextAlign.Center,
fontSize = 22.sp,
text = watch.name
)
Spacer(modifier = Modifier.size(4.dp))
Text(
modifier = Modifier
.fillMaxWidth()
.align(Alignment.CenterHorizontally),
color = Color.White,
textAlign = TextAlign.Center,
text = watch.description
)
}
}
}
| apache-2.0 | a79490e7e2486b993ab3f49b40f1391b | 33.795276 | 93 | 0.65671 | 4.93192 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/native/src/internal/StackTraceRecovery.kt | 1 | 884 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.internal
import kotlin.coroutines.*
internal actual fun <E: Throwable> recoverStackTrace(exception: E, continuation: Continuation<*>): E = exception
internal actual fun <E: Throwable> recoverStackTrace(exception: E): E = exception
internal actual fun <E : Throwable> unwrap(exception: E): E = exception
internal actual suspend inline fun recoverAndThrow(exception: Throwable): Nothing = throw exception
@Suppress("UNUSED")
internal actual interface CoroutineStackFrame {
public actual val callerFrame: CoroutineStackFrame?
public actual fun getStackTraceElement(): StackTraceElement?
}
@Suppress("ACTUAL_WITHOUT_EXPECT")
internal actual typealias StackTraceElement = Any
internal actual fun Throwable.initCause(cause: Throwable) {
}
| apache-2.0 | 7ed678a1134daa4193e269fb87b63d35 | 35.833333 | 112 | 0.783937 | 4.628272 | false | false | false | false |
leafclick/intellij-community | platform/platform-impl/src/com/intellij/application/options/RegistryManagerImpl.kt | 1 | 1778 | // 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.application.options
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.registry.Registry
import com.intellij.util.ArrayUtilRt
import org.jdom.Element
import java.util.*
@State(name = "Registry", storages = [Storage("ide.general.xml")])
private class RegistryManagerImpl : PersistentStateComponent<Element>, RegistryManager {
override fun `is`(key: String): Boolean {
return Registry.get(key).asBoolean()
}
override fun intValue(key: String) = Registry.get(key).asInteger()
override fun get(key: String) = Registry.get(key)
override fun getState() = Registry.getInstance().state
override fun noStateLoaded() {
Registry.getInstance().markAsLoaded()
}
override fun loadState(state: Element) {
val registry = Registry.getInstance()
registry.loadState(state)
log(registry)
}
private fun log(registry: Registry) {
val userProperties = registry.userProperties
if (userProperties.size <= (if (userProperties.containsKey("ide.firstStartup")) 1 else 0)) {
return
}
val keys = ArrayUtilRt.toStringArray(userProperties.keys)
Arrays.sort(keys)
val builder = StringBuilder("Registry values changed by user: ")
for (key in keys) {
if ("ide.firstStartup" == key) {
continue
}
builder.append(key).append(" = ").append(userProperties[key]).append(", ")
}
logger<RegistryManager>().info(builder.substring(0, builder.length - 2))
}
} | apache-2.0 | 39cceb323d35979c6f46032dc1742997 | 33.211538 | 140 | 0.728346 | 4.21327 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/produce_dynamic/simple/hello.kt | 1 | 972 |
// Top level functions.
fun hello() {
println("Hello, dynamic!")
}
fun getString() = "Kotlin/Native"
// Class with inheritance.
open class Base {
open fun foo() = println("Base.foo")
open fun fooParam(arg0: String, arg1: Int) = println("Base.fooParam: $arg0 $arg1")
}
class Child : Base() {
override fun fooParam(arg0: String, arg1: Int) = println("Child.fooParam: $arg0 $arg1")
val roProperty: Int
get() = 42
var rwProperty: Int = 0
get() = field
set(value) { field = value + 1 }
}
// Interface.
interface I {
fun foo(arg0: String, arg1: Int, arg2: I)
fun fooImpl() = foo("Hi", 239, this)
}
open class Impl1: I {
override fun foo(arg0: String, arg1: Int, arg2: I) {
println("Impl1.I: $arg0 $arg1 ${arg2::class.qualifiedName}")
}
}
class Impl2 : Impl1() {
override fun foo(arg0: String, arg1: Int, arg2: I) {
println("Impl2.I: $arg0 $arg1 ${arg2::class.qualifiedName}")
}
} | apache-2.0 | 8f82e83411dbc9fd33a2670f0f000ee6 | 21.113636 | 91 | 0.600823 | 3.009288 | false | false | false | false |
K0zka/kotlin-sonar | src/main/kotlin/io/github/K0zka/kotlinsonar/KotlinIssueSensor.kt | 1 | 844 | package io.github.K0zka.kotlinsonar
import org.slf4j.LoggerFactory
import org.sonar.api.batch.Sensor
import org.sonar.api.batch.SensorContext
import org.sonar.api.batch.fs.FileSystem
import org.sonar.api.component.ResourcePerspectives
import org.sonar.api.resources.Project
class KotlinIssueSensor(
private val fileSystem: FileSystem,
private val perspectives: ResourcePerspectives) : Sensor {
companion object {
private val logger = LoggerFactory.getLogger(KotlinIssueSensor::class.java)!!
}
override fun shouldExecuteOnProject(project: Project): Boolean
= fileSystem.hasFiles { it.language() == kotlinLanguageName }
override fun analyse(project: Project, context: SensorContext) {
for (input in fileSystem.inputFiles { it.language() == kotlinLanguageName }) {
logger.debug("Analysing {}", input.relativePath())
}
}
} | apache-2.0 | ddc811a2ce4f1b9a6eef6364c36b70c8 | 31.5 | 80 | 0.781991 | 3.718062 | false | false | false | false |
pyamsoft/padlock | padlock/src/main/java/com/pyamsoft/padlock/pin/confirm/PinConfirmDialog.kt | 1 | 4138 | /*
* Copyright 2019 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.pyamsoft.padlock.pin.confirm
import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams
import androidx.annotation.CheckResult
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.DialogFragment
import com.pyamsoft.padlock.Injector
import com.pyamsoft.padlock.PadLockComponent
import com.pyamsoft.padlock.R
import com.pyamsoft.padlock.R.layout
import com.pyamsoft.padlock.pin.toolbar.PinToolbarUiComponent
import com.pyamsoft.padlock.pin.toolbar.PinToolbarUiComponent.Callback
import com.pyamsoft.pydroid.ui.app.noTitle
import com.pyamsoft.pydroid.ui.app.requireArguments
import javax.inject.Inject
class PinConfirmDialog : DialogFragment(),
Callback,
PinConfirmUiComponent.Callback {
@field:Inject internal lateinit var toolbarComponent: PinToolbarUiComponent
@field:Inject internal lateinit var component: PinConfirmUiComponent
private var finishOnDismiss: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
isCancelable = true
finishOnDismiss = requireArguments().getBoolean(
FINISH_ON_DISMISS, false)
}
override fun onResume() {
super.onResume()
// The dialog is super small for some reason. We have to set the size manually, in onResume
dialog.window?.apply {
setLayout(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT
)
setGravity(Gravity.CENTER)
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(layout.layout_constraint, container, false)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return super.onCreateDialog(savedInstanceState)
.noTitle()
}
override fun onViewCreated(
view: View,
savedInstanceState: Bundle?
) {
super.onViewCreated(view, savedInstanceState)
val layoutRoot = view.findViewById<ConstraintLayout>(R.id.layout_constraint)
Injector.obtain<PadLockComponent>(view.context.applicationContext)
.plusPinComponent()
.owner(viewLifecycleOwner)
.parent(layoutRoot)
.finishOnDismiss(finishOnDismiss)
.build()
.inject(this)
component.bind(viewLifecycleOwner, savedInstanceState, this)
toolbarComponent.bind(viewLifecycleOwner, savedInstanceState, this)
toolbarComponent.layout(layoutRoot)
component.layout(layoutRoot, toolbarComponent.id())
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
component.saveState(outState)
toolbarComponent.saveState(outState)
}
override fun onDismiss(dialog: DialogInterface?) {
super.onDismiss(dialog)
if (finishOnDismiss) {
activity?.finish()
}
}
override fun onClose() {
dismiss()
}
override fun onAttemptSubmit() {
component.submit()
}
companion object {
const val TAG = "PinConfirmDialog"
private const val FINISH_ON_DISMISS = "finish_dismiss"
@JvmStatic
@CheckResult
fun newInstance(finishOnDismiss: Boolean): PinConfirmDialog {
return PinConfirmDialog()
.apply {
arguments = Bundle().apply {
putBoolean(FINISH_ON_DISMISS, finishOnDismiss)
}
}
}
}
}
| apache-2.0 | 7b1aaf8bc9a3eb60e43548841e826902 | 28.140845 | 95 | 0.738763 | 4.592675 | false | false | false | false |
exponent/exponent | packages/expo-navigation-bar/android/src/main/java/expo/modules/navigationbar/NavigationBarModule.kt | 2 | 6843 | package expo.modules.navigationbar
import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.WindowInsets
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsControllerCompat
import expo.modules.core.ExportedModule
import expo.modules.core.ModuleRegistry
import expo.modules.core.Promise
import expo.modules.core.errors.CurrentActivityNotFoundException
import expo.modules.core.interfaces.ActivityProvider
import expo.modules.core.interfaces.ExpoMethod
import expo.modules.core.interfaces.services.EventEmitter
class NavigationBarModule(context: Context) : ExportedModule(context) {
private lateinit var mActivityProvider: ActivityProvider
private lateinit var mEventEmitter: EventEmitter
override fun getName(): String {
return NAME
}
override fun onCreate(moduleRegistry: ModuleRegistry) {
mActivityProvider = moduleRegistry.getModule(ActivityProvider::class.java)
?: throw IllegalStateException("Could not find implementation for ActivityProvider.")
mEventEmitter = moduleRegistry.getModule(EventEmitter::class.java) ?: throw IllegalStateException("Could not find implementation for EventEmitter.")
}
// Ensure that rejections are passed up to JS rather than terminating the native client.
private fun safeRunOnUiThread(promise: Promise, block: (activity: Activity) -> Unit) {
val activity = mActivityProvider.currentActivity
if (activity == null) {
promise.reject(CurrentActivityNotFoundException())
return
}
activity.runOnUiThread {
block(activity)
}
}
@ExpoMethod
fun setBackgroundColorAsync(color: Int, promise: Promise) {
safeRunOnUiThread(promise) {
NavigationBar.setBackgroundColor(it, color, { promise.resolve(null) }, { m -> promise.reject(ERROR_TAG, m) })
}
}
@ExpoMethod
fun getBackgroundColorAsync(promise: Promise) {
safeRunOnUiThread(promise) {
val color = colorToHex(it.window.navigationBarColor)
promise.resolve(color)
}
}
@ExpoMethod
fun setBorderColorAsync(color: Int, promise: Promise) {
safeRunOnUiThread(promise) {
NavigationBar.setBorderColor(it, color, { promise.resolve(null) }, { m -> promise.reject(ERROR_TAG, m) })
}
}
@ExpoMethod
fun getBorderColorAsync(promise: Promise) {
safeRunOnUiThread(promise) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
val color = colorToHex(it.window.navigationBarDividerColor)
promise.resolve(color)
} else {
promise.reject(ERROR_TAG, "'getBorderColorAsync' is only available on Android API 28 or higher")
}
}
}
@ExpoMethod
fun setButtonStyleAsync(buttonStyle: String, promise: Promise) {
safeRunOnUiThread(promise) {
NavigationBar.setButtonStyle(
it, buttonStyle,
{
promise.resolve(null)
},
{ m -> promise.reject(ERROR_TAG, m) }
)
}
}
@ExpoMethod
fun getButtonStyleAsync(promise: Promise) {
safeRunOnUiThread(promise) {
WindowInsetsControllerCompat(it.window, it.window.decorView).let { controller ->
val style = if (controller.isAppearanceLightNavigationBars) "dark" else "light"
promise.resolve(style)
}
}
}
@ExpoMethod
fun setVisibilityAsync(visibility: String, promise: Promise) {
safeRunOnUiThread(promise) {
NavigationBar.setVisibility(it, visibility, { promise.resolve(null) }, { m -> promise.reject(ERROR_TAG, m) })
}
}
@ExpoMethod
fun getVisibilityAsync(promise: Promise) {
safeRunOnUiThread(promise) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val visibility = if (it.window.decorView.rootWindowInsets.isVisible(WindowInsets.Type.navigationBars())) "visible" else "hidden"
promise.resolve(visibility)
} else {
// TODO: Verify this works
@Suppress("DEPRECATION") val visibility = if ((View.SYSTEM_UI_FLAG_HIDE_NAVIGATION and it.window.decorView.systemUiVisibility) == 0) "visible" else "hidden"
promise.resolve(visibility)
}
}
}
@ExpoMethod
fun setPositionAsync(position: String, promise: Promise) {
safeRunOnUiThread(promise) {
NavigationBar.setPosition(it, position, { promise.resolve(null) }, { m -> promise.reject(ERROR_TAG, m) })
}
}
@ExpoMethod
fun unstable_getPositionAsync(promise: Promise) {
safeRunOnUiThread(promise) {
val position = if (ViewCompat.getFitsSystemWindows(it.window.decorView)) "relative" else "absolute"
promise.resolve(position)
}
}
@ExpoMethod
fun setBehaviorAsync(behavior: String, promise: Promise) {
safeRunOnUiThread(promise) {
NavigationBar.setBehavior(it, behavior, { promise.resolve(null) }, { m -> promise.reject(ERROR_TAG, m) })
}
}
@ExpoMethod
fun getBehaviorAsync(promise: Promise) {
safeRunOnUiThread(promise) {
WindowInsetsControllerCompat(it.window, it.window.decorView).let { controller ->
val behavior = when (controller.systemBarsBehavior) {
// TODO: Maybe relative / absolute
WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE -> "overlay-swipe"
WindowInsetsControllerCompat.BEHAVIOR_SHOW_BARS_BY_SWIPE -> "inset-swipe"
// WindowInsetsControllerCompat.BEHAVIOR_SHOW_BARS_BY_TOUCH -> "inset-touch"
else -> "inset-touch"
}
promise.resolve(behavior)
}
}
}
/* Events */
@ExpoMethod
fun startObserving(promise: Promise) {
safeRunOnUiThread(promise) {
val decorView = it.window.decorView
@Suppress("DEPRECATION")
decorView.setOnSystemUiVisibilityChangeListener { visibility: Int ->
var isNavigationBarVisible = (visibility and View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0
var stringVisibility = if (isNavigationBarVisible) "visible" else "hidden"
mEventEmitter.emit(
VISIBILITY_EVENT_NAME,
Bundle().apply {
putString("visibility", stringVisibility)
putInt("rawVisibility", visibility)
}
)
}
promise.resolve(null)
}
}
@ExpoMethod
fun stopObserving(promise: Promise) {
safeRunOnUiThread(promise) {
val decorView = it.window.decorView
@Suppress("DEPRECATION")
decorView.setOnSystemUiVisibilityChangeListener(null)
promise.resolve(null)
}
}
companion object {
private const val NAME = "ExpoNavigationBar"
private const val VISIBILITY_EVENT_NAME = "ExpoNavigationBar.didChange"
private const val ERROR_TAG = "ERR_NAVIGATION_BAR"
fun colorToHex(color: Int): String {
return String.format("#%02x%02x%02x", Color.red(color), Color.green(color), Color.blue(color))
}
}
}
| bsd-3-clause | 9303cc12eb48b43ca032d5f385d2680b | 32.544118 | 164 | 0.700716 | 4.380922 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/multiplatform/diamondModuleDependency2/common-1/common-1.kt | 2 | 528 | @file:Suppress("UNUSED_PARAMETER")
package sample
interface AA
interface BB
interface CC
interface DD
expect interface <!LINE_MARKER("descr='Is subclassed by B [common-2-1] C [common-2-2] D Click or press ... to navigate'"), LINE_MARKER("descr='Has actuals in common'")!>A<!> {
fun <!LINE_MARKER("descr='Has actuals in common'")!>foo_A<!>()
}
fun take0(x: A): AA = null!!
fun take1(x: A): AA = null!!
fun take2(x: A): AA = null!!
fun take3(x: A): AA = null!!
fun take4(x: A): AA = null!!
fun test(x: A) {
take4(x)
} | apache-2.0 | 07488bbac87d8d8bab3f317ebf5e2ab5 | 24.190476 | 176 | 0.640152 | 2.901099 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceUtil.kt | 1 | 10480 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.introduce
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ScrollType
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils
import org.jetbrains.kotlin.idea.refactoring.chooseContainerElementIfNecessary
import org.jetbrains.kotlin.idea.refactoring.selectElement
import org.jetbrains.kotlin.idea.util.psi.patternMatching.KotlinPsiRange
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.utils.SmartList
fun showErrorHint(project: Project, editor: Editor, @NlsContexts.DialogMessage message: String, @NlsContexts.DialogTitle title: String) {
CodeInsightUtils.showErrorHint(project, editor, message, title, null)
}
fun showErrorHintByKey(project: Project, editor: Editor, messageKey: String, @NlsContexts.DialogTitle title: String) {
showErrorHint(project, editor, KotlinBundle.message(messageKey), title)
}
fun selectElementsWithTargetSibling(
@NlsContexts.DialogTitle operationName: String,
editor: Editor,
file: KtFile,
@NlsContexts.DialogTitle title: String,
elementKinds: Collection<CodeInsightUtils.ElementKind>,
elementValidator: (List<PsiElement>) -> String?,
getContainers: (elements: List<PsiElement>, commonParent: PsiElement) -> List<PsiElement>,
continuation: (elements: List<PsiElement>, targetSibling: PsiElement) -> Unit
) {
fun onSelectionComplete(elements: List<PsiElement>, targetContainer: PsiElement) {
val physicalElements = elements.map { it.substringContextOrThis }
val parent = PsiTreeUtil.findCommonParent(physicalElements)
?: throw AssertionError("Should have at least one parent: ${physicalElements.joinToString("\n")}")
if (parent == targetContainer) {
continuation(elements, physicalElements.first())
return
}
val outermostParent = parent.getOutermostParentContainedIn(targetContainer)
if (outermostParent == null) {
showErrorHintByKey(file.project, editor, "cannot.refactor.no.container", operationName)
return
}
continuation(elements, outermostParent)
}
selectElementsWithTargetParent(operationName, editor, file, title, elementKinds, elementValidator, getContainers, ::onSelectionComplete)
}
fun selectElementsWithTargetParent(
@NlsContexts.DialogTitle operationName: String,
editor: Editor,
file: KtFile,
@NlsContexts.DialogTitle title: String,
elementKinds: Collection<CodeInsightUtils.ElementKind>,
elementValidator: (List<PsiElement>) -> String?,
getContainers: (elements: List<PsiElement>, commonParent: PsiElement) -> List<PsiElement>,
continuation: (elements: List<PsiElement>, targetParent: PsiElement) -> Unit
) {
fun showErrorHintByKey(key: String) {
showErrorHintByKey(file.project, editor, key, operationName)
}
fun selectTargetContainer(elements: List<PsiElement>) {
elementValidator(elements)?.let {
showErrorHint(file.project, editor, it, operationName)
return
}
val physicalElements = elements.map { it.substringContextOrThis }
val parent = PsiTreeUtil.findCommonParent(physicalElements)
?: throw AssertionError("Should have at least one parent: ${physicalElements.joinToString("\n")}")
val containers = getContainers(physicalElements, parent)
if (containers.isEmpty()) {
showErrorHintByKey("cannot.refactor.no.container")
return
}
chooseContainerElementIfNecessary(
containers,
editor,
title,
true
) {
continuation(elements, it)
}
}
fun selectMultipleElements() {
val startOffset = editor.selectionModel.selectionStart
val endOffset = editor.selectionModel.selectionEnd
val elements = elementKinds.flatMap { CodeInsightUtils.findElements(file, startOffset, endOffset, it).toList() }
if (elements.isEmpty()) {
return when (elementKinds.singleOrNull()) {
CodeInsightUtils.ElementKind.EXPRESSION -> showErrorHintByKey("cannot.refactor.no.expression")
CodeInsightUtils.ElementKind.TYPE_ELEMENT -> showErrorHintByKey("cannot.refactor.no.type")
else -> showErrorHint(
file.project,
editor,
KotlinBundle.message("text.refactoring.can.t.be.performed.on.the.selected.code.element"),
title
)
}
}
selectTargetContainer(elements)
}
fun selectSingleElement() {
selectElement(editor, file, false, elementKinds) { expr ->
if (expr != null) {
selectTargetContainer(listOf(expr))
} else {
if (!editor.selectionModel.hasSelection()) {
if (elementKinds.singleOrNull() == CodeInsightUtils.ElementKind.EXPRESSION) {
val elementAtCaret = file.findElementAt(editor.caretModel.offset)
elementAtCaret?.getParentOfTypeAndBranch<KtProperty> { nameIdentifier }?.let {
return@selectElement selectTargetContainer(listOf(it))
}
}
editor.selectionModel.selectLineAtCaret()
}
selectMultipleElements()
}
}
}
editor.scrollingModel.scrollToCaret(ScrollType.MAKE_VISIBLE)
selectSingleElement()
}
fun PsiElement.findExpressionByCopyableDataAndClearIt(key: Key<Boolean>): KtExpression? {
val result = findDescendantOfType<KtExpression> { it.getCopyableUserData(key) != null } ?: return null
result.putCopyableUserData(key, null)
return result
}
fun PsiElement.findElementByCopyableDataAndClearIt(key: Key<Boolean>): PsiElement? {
val result = findDescendantOfType<PsiElement> { it.getCopyableUserData(key) != null } ?: return null
result.putCopyableUserData(key, null)
return result
}
fun PsiElement.findExpressionsByCopyableDataAndClearIt(key: Key<Boolean>): List<KtExpression> {
val results = collectDescendantsOfType<KtExpression> { it.getCopyableUserData(key) != null }
results.forEach { it.putCopyableUserData(key, null) }
return results
}
fun findExpressionOrStringFragment(file: KtFile, startOffset: Int, endOffset: Int): KtExpression? {
val entry1 = file.findElementAt(startOffset)?.getNonStrictParentOfType<KtStringTemplateEntry>() ?: return null
val entry2 = file.findElementAt(endOffset - 1)?.getNonStrictParentOfType<KtStringTemplateEntry>() ?: return null
if (entry1 == entry2 && entry1 is KtStringTemplateEntryWithExpression) return entry1.expression
val stringTemplate = entry1.parent as? KtStringTemplateExpression ?: return null
if (entry2.parent != stringTemplate) return null
val templateOffset = stringTemplate.startOffset
if (stringTemplate.getContentRange().equalsToRange(startOffset - templateOffset, endOffset - templateOffset)) return stringTemplate
val prefixOffset = startOffset - entry1.startOffset
if (entry1 !is KtLiteralStringTemplateEntry && prefixOffset > 0) return null
val suffixOffset = endOffset - entry2.startOffset
if (entry2 !is KtLiteralStringTemplateEntry && suffixOffset < entry2.textLength) return null
val prefix = entry1.text.substring(0, prefixOffset)
val suffix = entry2.text.substring(suffixOffset)
return ExtractableSubstringInfo(entry1, entry2, prefix, suffix).createExpression()
}
fun KotlinPsiRange.getPhysicalTextRange(): TextRange {
return (elements.singleOrNull() as? KtExpression)?.extractableSubstringInfo?.contentRange ?: getTextRange()
}
fun ExtractableSubstringInfo.replaceWith(replacement: KtExpression): KtExpression {
return with(this) {
val psiFactory = KtPsiFactory(replacement)
val parent = startEntry.parent
psiFactory.createStringTemplate(prefix).entries.singleOrNull()?.let { parent.addBefore(it, startEntry) }
val refEntry = psiFactory.createBlockStringTemplateEntry(replacement)
val addedRefEntry = parent.addBefore(refEntry, startEntry) as KtStringTemplateEntryWithExpression
psiFactory.createStringTemplate(suffix).entries.singleOrNull()?.let { parent.addAfter(it, endEntry) }
parent.deleteChildRange(startEntry, endEntry)
addedRefEntry.expression!!
}
}
fun KtExpression.mustBeParenthesizedInInitializerPosition(): Boolean {
if (this !is KtBinaryExpression) return false
if (left?.mustBeParenthesizedInInitializerPosition() == true) return true
return PsiChildRange(left, operationReference).any { (it is PsiWhiteSpace) && it.textContains('\n') }
}
fun isObjectOrNonInnerClass(e: PsiElement): Boolean = e is KtObjectDeclaration || (e is KtClass && !e.isInner())
fun <T : KtDeclaration> insertDeclaration(declaration: T, targetSibling: PsiElement): T {
val targetParent = targetSibling.parent
val anchorCandidates = SmartList<PsiElement>()
anchorCandidates.add(targetSibling)
if (targetSibling is KtEnumEntry) {
anchorCandidates.add(targetSibling.siblings().last { it is KtEnumEntry })
}
val anchor = anchorCandidates.minByOrNull { it.startOffset }!!.parentsWithSelf.first { it.parent == targetParent }
val targetContainer = anchor.parent!!
@Suppress("UNCHECKED_CAST")
return (targetContainer.addBefore(declaration, anchor) as T).apply {
targetContainer.addBefore(KtPsiFactory(declaration).createWhiteSpace("\n\n"), anchor)
}
}
internal fun validateExpressionElements(elements: List<PsiElement>): String? {
if (elements.any { it is KtConstructor<*> || it is KtParameter || it is KtTypeAlias || it is KtPropertyAccessor }) {
return KotlinBundle.message("text.refactoring.is.not.applicable.to.this.code.fragment")
}
return null
}
| apache-2.0 | f07c5641f12534b4f2fbc3e1f8b604f2 | 41.95082 | 158 | 0.714218 | 5.221724 | false | false | false | false |
smmribeiro/intellij-community | platform/diff-impl/src/com/intellij/diff/actions/ShowBlankDiffWindowAction.kt | 2 | 19122 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.diff.actions
import com.intellij.diff.*
import com.intellij.diff.FrameDiffTool.DiffViewer
import com.intellij.diff.actions.impl.MutableDiffRequestChain
import com.intellij.diff.contents.DiffContent
import com.intellij.diff.contents.DocumentContent
import com.intellij.diff.contents.FileContent
import com.intellij.diff.requests.ContentDiffRequest
import com.intellij.diff.requests.DiffRequest
import com.intellij.diff.tools.simple.SimpleDiffTool
import com.intellij.diff.tools.util.DiffDataKeys
import com.intellij.diff.tools.util.DiffNotifications
import com.intellij.diff.tools.util.base.DiffViewerBase
import com.intellij.diff.tools.util.base.DiffViewerListener
import com.intellij.diff.tools.util.side.ThreesideTextDiffViewer
import com.intellij.diff.tools.util.side.TwosideTextDiffViewer
import com.intellij.diff.util.*
import com.intellij.icons.AllIcons
import com.intellij.ide.CopyPasteManagerEx
import com.intellij.ide.IdeEventQueue
import com.intellij.ide.dnd.FileCopyPasteUtil
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.diff.DiffBundle
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorDropHandler
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.fileChooser.FileChooser
import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.fileEditor.impl.EditorWindow
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.JBPopupMenu
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.EditorNotificationPanel
import com.intellij.ui.UIBundle
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.containers.LinkedListWithSum
import com.intellij.util.containers.map2Array
import com.intellij.util.text.DateFormatUtil
import java.awt.datatransfer.DataFlavor
import java.awt.datatransfer.Transferable
import java.awt.event.MouseEvent
import java.io.File
import javax.swing.JComponent
import kotlin.math.max
class ShowBlankDiffWindowAction : DumbAwareAction() {
init {
isEnabledInModalContext = true
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project
val editor = e.getData(CommonDataKeys.EDITOR)
val files = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY)
val content1: DocumentContent
val content2: DocumentContent
var baseContent: DocumentContent? = null
if (files != null && files.size == 3) {
content1 = createFileContent(project, files[0]) ?: createEditableContent(project)
baseContent = createFileContent(project, files[1]) ?: createEditableContent(project)
content2 = createFileContent(project, files[2]) ?: createEditableContent(project)
}
else if (files != null && files.size == 2) {
content1 = createFileContent(project, files[0]) ?: createEditableContent(project)
content2 = createFileContent(project, files[1]) ?: createEditableContent(project)
}
else if (editor != null && editor.selectionModel.hasSelection()) {
val defaultText = editor.selectionModel.selectedText ?: ""
content1 = createEditableContent(project, defaultText)
content2 = createEditableContent(project)
}
else {
content1 = createEditableContent(project)
content2 = createEditableContent(project)
}
val chain = BlankDiffWindowUtil.createBlankDiffRequestChain(content1, content2, baseContent)
chain.putUserData(DiffUserDataKeys.PLACE, "BlankDiffWindow")
chain.putUserData(DiffUserDataKeysEx.FORCE_DIFF_TOOL, SimpleDiffTool.INSTANCE)
chain.putUserData(DiffUserDataKeysEx.PREFERRED_FOCUS_SIDE, Side.LEFT)
chain.putUserData(DiffUserDataKeysEx.DISABLE_CONTENTS_EQUALS_NOTIFICATION, true)
DiffManagerEx.getInstance().showDiffBuiltin(project, chain, DiffDialogHints.DEFAULT)
}
}
internal class SwitchToBlankEditorAction : BlankSwitchContentActionBase() {
override fun isEnabled(currentContent: DiffContent): Boolean = currentContent is FileContent
override fun createNewContent(project: Project?, contextComponent: JComponent): DiffContent {
return createEditableContent(project, "")
}
}
internal class SwitchToFileEditorAction : BlankSwitchContentActionBase() {
override fun isEnabled(currentContent: DiffContent): Boolean = true
override fun createNewContent(project: Project?, contextComponent: JComponent): DiffContent? {
val descriptor = FileChooserDescriptor(true, false, false, false, false, false)
descriptor.title = DiffBundle.message("select.file.to.compare")
descriptor.description = ""
val file = FileChooser.chooseFile(descriptor, contextComponent, project, null) ?: return null
return createFileContent(project, file)
}
}
internal class SwitchToRecentEditorActionGroup : ActionGroup(), DumbAware {
override fun update(e: AnActionEvent) {
val helper = MutableDiffRequestChain.createHelper(e.dataContext)
if (helper == null) {
e.presentation.isEnabledAndVisible = false
return
}
if (helper.chain.getUserData(BlankDiffWindowUtil.BLANK_KEY) != true) {
e.presentation.isEnabledAndVisible = false
return
}
e.presentation.isEnabledAndVisible = true
}
override fun getChildren(e: AnActionEvent?): Array<AnAction> {
return BlankDiffWindowUtil.getRecentFiles().map2Array { MySwitchAction(it) }
}
@Suppress("DialogTitleCapitalization")
private class MySwitchAction(val content: RecentBlankContent) : BlankSwitchContentActionBase() {
init {
val text = content.text
val dateAppendix = DateFormatUtil.formatPrettyDateTime(content.timestamp)
val presentable = when {
text.length < 40 -> DiffBundle.message("blank.diff.recent.content.summary.text.date", text.trim(), dateAppendix)
else -> {
val shortenedText = StringUtil.shortenTextWithEllipsis(text.trim(), 30, 0)
DiffBundle.message("blank.diff.recent.content.summary.text.length.date", shortenedText, text.length, dateAppendix)
}
}
templatePresentation.text = presentable
}
override fun isEnabled(currentContent: DiffContent): Boolean = true
override fun createNewContent(project: Project?, contextComponent: JComponent): DiffContent {
return createEditableContent(project, content.text)
}
}
}
internal abstract class BlankSwitchContentActionBase : DumbAwareAction() {
override fun update(e: AnActionEvent) {
val helper = MutableDiffRequestChain.createHelper(e.dataContext)
if (helper == null) {
e.presentation.isEnabledAndVisible = false
return
}
if (helper.chain.getUserData(BlankDiffWindowUtil.BLANK_KEY) != true) {
e.presentation.isEnabledAndVisible = false
return
}
val editor = e.getData(CommonDataKeys.EDITOR)
val viewer = e.getData(DiffDataKeys.DIFF_VIEWER)
if (viewer is TwosideTextDiffViewer) {
val side = Side.fromValue(viewer.editors, editor)
val currentContent = side?.select(helper.chain.content1, helper.chain.content2)
e.presentation.isEnabledAndVisible = currentContent != null && isEnabled(currentContent)
}
else if (viewer is ThreesideTextDiffViewer) {
val side = ThreeSide.fromValue(viewer.editors, editor)
val currentContent = side?.select(helper.chain.content1, helper.chain.baseContent, helper.chain.content2)
e.presentation.isEnabledAndVisible = currentContent != null && isEnabled(currentContent)
}
else {
e.presentation.isEnabledAndVisible = false
}
}
override fun actionPerformed(e: AnActionEvent) {
val helper = MutableDiffRequestChain.createHelper(e.dataContext)!!
val editor = e.getRequiredData(CommonDataKeys.EDITOR)
val viewer = e.getRequiredData(DiffDataKeys.DIFF_VIEWER)
perform(editor, viewer, helper)
}
fun perform(editor: Editor, viewer: DiffViewer, helper: MutableDiffRequestChain.Helper) {
if (viewer is TwosideTextDiffViewer) {
val side = Side.fromValue(viewer.editors, editor) ?: return
val newContent = createNewContent(viewer.project, viewer.component) ?: return
helper.setContent(newContent, side)
}
else if (viewer is ThreesideTextDiffViewer) {
val side = ThreeSide.fromValue(viewer.editors, editor) ?: return
val newContent = createNewContent(viewer.project, viewer.component) ?: return
helper.setContent(newContent, side)
}
helper.fireRequestUpdated()
}
abstract fun isEnabled(currentContent: DiffContent): Boolean
protected abstract fun createNewContent(project: Project?, contextComponent: JComponent): DiffContent?
}
internal class BlankToggleThreeSideModeAction : DumbAwareAction() {
override fun update(e: AnActionEvent) {
val helper = MutableDiffRequestChain.createHelper(e.dataContext)
val viewer = e.getData(DiffDataKeys.DIFF_VIEWER) as? DiffViewerBase
if (helper == null || viewer == null) {
e.presentation.isEnabledAndVisible = false
return
}
if (helper.chain.getUserData(BlankDiffWindowUtil.BLANK_KEY) != true) {
e.presentation.isEnabledAndVisible = false
return
}
e.presentation.text = if (helper.chain.baseContent != null) {
ActionsBundle.message("action.ToggleThreeSideInBlankDiffWindow.text.disable")
}
else {
ActionsBundle.message("action.ToggleThreeSideInBlankDiffWindow.text.enable")
}
e.presentation.isEnabledAndVisible = true
}
override fun actionPerformed(e: AnActionEvent) {
val helper = MutableDiffRequestChain.createHelper(e.dataContext)!!
val viewer = e.getRequiredData(DiffDataKeys.DIFF_VIEWER) as DiffViewerBase
if (helper.chain.baseContent != null) {
helper.chain.baseContent = null
helper.chain.baseTitle = null
}
else {
helper.setContent(createEditableContent(viewer.project), ThreeSide.BASE)
}
helper.fireRequestUpdated()
}
}
class ShowBlankDiffWindowDiffExtension : DiffExtension() {
override fun onViewerCreated(viewer: DiffViewer, context: DiffContext, request: DiffRequest) {
val helper = MutableDiffRequestChain.createHelper(context, request) ?: return
if (helper.chain.getUserData(BlankDiffWindowUtil.BLANK_KEY) != true) return
if (viewer is TwosideTextDiffViewer) {
DnDHandler2(viewer, helper, Side.LEFT).install()
DnDHandler2(viewer, helper, Side.RIGHT).install()
}
else if (viewer is ThreesideTextDiffViewer) {
DnDHandler3(viewer, helper, ThreeSide.LEFT).install()
DnDHandler3(viewer, helper, ThreeSide.BASE).install()
DnDHandler3(viewer, helper, ThreeSide.RIGHT).install()
}
if (viewer is DiffViewerBase) {
RecentContentHandler(viewer, helper).install()
}
}
}
private class DnDHandler2(val viewer: TwosideTextDiffViewer,
val helper: MutableDiffRequestChain.Helper,
val side: Side) : EditorDropHandler {
fun install() {
val editor = viewer.getEditor(side) as? EditorImpl ?: return
editor.setDropHandler(this)
}
override fun canHandleDrop(transferFlavors: Array<out DataFlavor>): Boolean {
return FileCopyPasteUtil.isFileListFlavorAvailable(transferFlavors)
}
override fun handleDrop(t: Transferable, project: Project?, editorWindow: EditorWindow?) {
val success = doHandleDnD(t)
if (success) helper.fireRequestUpdated()
}
private fun doHandleDnD(transferable: Transferable): Boolean {
val files = FileCopyPasteUtil.getFileList(transferable)
if (files != null) {
if (files.size == 1) {
val newContent = createFileContent(viewer.project, files[0]) ?: return false
helper.setContent(newContent, side)
return true
}
if (files.size >= 2) {
val newContent1 = createFileContent(viewer.project, files[0]) ?: return false
val newContent2 = createFileContent(viewer.project, files[1]) ?: return false
helper.setContent(newContent1, Side.LEFT)
helper.setContent(newContent2, Side.RIGHT)
return true
}
}
return false
}
}
private class DnDHandler3(val viewer: ThreesideTextDiffViewer,
val helper: MutableDiffRequestChain.Helper,
val side: ThreeSide) : EditorDropHandler {
fun install() {
val editor = viewer.getEditor(side) as? EditorImpl ?: return
editor.setDropHandler(this)
}
override fun canHandleDrop(transferFlavors: Array<out DataFlavor>): Boolean {
return FileCopyPasteUtil.isFileListFlavorAvailable(transferFlavors)
}
override fun handleDrop(t: Transferable, project: Project?, editorWindow: EditorWindow?) {
val success = doHandleDnD(t)
if (success) helper.fireRequestUpdated()
}
private fun doHandleDnD(transferable: Transferable): Boolean {
val files = FileCopyPasteUtil.getFileList(transferable)
if (files != null) {
if (files.size == 1) {
val newContent = createFileContent(viewer.project, files[0]) ?: return false
helper.setContent(newContent, side)
return true
}
if (files.size == 3) {
val newContent1 = createFileContent(viewer.project, files[0]) ?: return false
val newBaseContent = createFileContent(viewer.project, files[1]) ?: return false
val newContent2 = createFileContent(viewer.project, files[2]) ?: return false
helper.setContent(newContent1, ThreeSide.LEFT)
helper.setContent(newBaseContent, ThreeSide.BASE)
helper.setContent(newContent2, ThreeSide.RIGHT)
return true
}
}
return false
}
}
private class RecentContentHandler(val viewer: DiffViewerBase,
val helper: MutableDiffRequestChain.Helper) {
fun install() {
viewer.addListener(MyListener())
}
private inner class MyListener : DiffViewerListener() {
override fun onDispose() {
BlankDiffWindowUtil.saveRecentContents(viewer.request)
}
}
}
internal data class RecentBlankContent(val text: @NlsSafe String, val timestamp: Long)
object BlankDiffWindowUtil {
val BLANK_KEY = Key.create<Boolean>("Diff.BlankWindow")
@JvmField
val REMEMBER_CONTENT_KEY = Key.create<Boolean>("Diff.BlankWindow.BlankContent")
@JvmStatic
fun createBlankDiffRequestChain(content1: DocumentContent,
content2: DocumentContent,
baseContent: DocumentContent? = null): MutableDiffRequestChain {
val chain = MutableDiffRequestChain(content1, baseContent, content2)
chain.putUserData(BLANK_KEY, true)
return chain
}
private val ourRecentFiles = LinkedListWithSum<RecentBlankContent> { it.text.length }
internal fun getRecentFiles(): List<RecentBlankContent> = ourRecentFiles.toList()
@RequiresEdt
fun saveRecentContents(request: DiffRequest) {
if (request is ContentDiffRequest) {
for (content in request.contents) {
saveRecentContent(content)
}
}
}
@RequiresEdt
fun saveRecentContent(content: DiffContent) {
if (content !is DocumentContent) return
if (!DiffUtil.isUserDataFlagSet(REMEMBER_CONTENT_KEY, content)) return
val text = content.document.text
if (text.isBlank()) return
val oldValue = ourRecentFiles.find { it.text == text }
if (oldValue != null) {
ourRecentFiles.remove(oldValue)
ourRecentFiles.add(0, oldValue)
}
else {
ourRecentFiles.add(0, RecentBlankContent(text, System.currentTimeMillis()))
deleteAfterAllowedMaximum()
}
}
private fun deleteAfterAllowedMaximum() {
val maxCount = max(1, Registry.intValue("blank.diff.history.max.items"))
val maxMemory = max(0, Registry.intValue("blank.diff.history.max.memory"))
CopyPasteManagerEx.deleteAfterAllowedMaximum(ourRecentFiles, maxCount, maxMemory) { item ->
RecentBlankContent(UIBundle.message("clipboard.history.purged.item"), item.timestamp)
}
}
}
private fun createEditableContent(project: Project?, text: String = ""): DocumentContent {
val content = DiffContentFactoryEx.getInstanceEx().documentContent(project, false).buildFromText(text, false)
content.putUserData(BlankDiffWindowUtil.REMEMBER_CONTENT_KEY, true)
DiffUtil.addNotification(DiffNotificationProvider { viewer -> createBlankNotificationProvider(viewer, content) }, content)
return content
}
private fun createFileContent(project: Project?, file: File): DocumentContent? {
val virtualFile = VfsUtil.findFileByIoFile(file, true) ?: return null
return createFileContent(project, virtualFile)
}
private fun createFileContent(project: Project?, file: VirtualFile): DocumentContent? {
return DiffContentFactory.getInstance().createDocument(project, file)
}
private fun createBlankNotificationProvider(viewer: DiffViewer?, content: DocumentContent): JComponent? {
if (viewer !is DiffViewerBase) return null
val helper = MutableDiffRequestChain.createHelper(viewer.context, viewer.request) ?: return null
val editor = when (viewer) {
is TwosideTextDiffViewer -> {
val index = viewer.contents.indexOf(content)
if (index == -1) return null
viewer.editors[index]
}
is ThreesideTextDiffViewer -> {
val index = viewer.contents.indexOf(content)
if (index == -1) return null
viewer.editors[index]
}
else -> return null
}
if (editor.document.textLength != 0) return null
val panel = EditorNotificationPanel(editor, null, null)
panel.createActionLabel(DiffBundle.message("notification.action.text.blank.diff.select.file")) {
SwitchToFileEditorAction().perform(editor, viewer, helper)
}
if (BlankDiffWindowUtil.getRecentFiles().isNotEmpty()) {
panel.createActionLabel(DiffBundle.message("notification.action.text.blank.diff.recent")) {
val menu = ActionManager.getInstance().createActionPopupMenu(ActionPlaces.UNKNOWN, SwitchToRecentEditorActionGroup())
menu.setTargetComponent(editor.component)
val event = IdeEventQueue.getInstance().trueCurrentEvent
if (event is MouseEvent) {
JBPopupMenu.showByEvent(event, menu.component)
}
else {
JBPopupMenu.showByEditor(editor, menu.component)
}
}.apply {
setIcon(AllIcons.General.LinkDropTriangle)
isIconAtRight = true
setUseIconAsLink(true)
}
}
editor.document.addDocumentListener(object : DocumentListener {
override fun documentChanged(event: DocumentEvent) {
editor.document.removeDocumentListener(this)
DiffNotifications.hideNotification(panel)
}
}, viewer)
return panel
}
| apache-2.0 | 86f18577b71155e215a0caf8d99da3b8 | 37.552419 | 124 | 0.73805 | 4.433573 | false | false | false | false |
smmribeiro/intellij-community | java/idea-ui/src/com/intellij/ide/starters/shared/ui/LibraryDescriptionPanel.kt | 6 | 6643 | // 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.starters.shared.ui
import com.intellij.ide.starters.JavaStartersBundle
import com.intellij.ide.starters.shared.LibraryInfo
import com.intellij.icons.AllIcons
import com.intellij.openapi.roots.ui.componentsList.components.ScrollablePanel
import com.intellij.openapi.ui.ex.MultiLineLabel
import com.intellij.openapi.util.NlsSafe
import com.intellij.ui.HyperlinkLabel
import com.intellij.ui.JBColor
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.panels.VerticalLayout
import com.intellij.util.ui.*
import com.intellij.util.ui.UIUtil.DEFAULT_HGAP
import com.intellij.util.ui.UIUtil.DEFAULT_VGAP
import com.intellij.util.ui.components.BorderLayoutPanel
import java.awt.*
import javax.swing.JPanel
import javax.swing.JTextArea
import javax.swing.SwingUtilities
import kotlin.math.max
internal class LibraryDescriptionPanel : ScrollablePanel(VerticalLayout(DEFAULT_VGAP)) {
private val descriptionHeader: JBLabel = JBLabel()
private val descriptionText: JTextArea = JTextArea()
private val descriptionVersion: MultiLineLabel = MultiLineLabel()
private val linksPanel: JPanel = JPanel(WrappedFlowLayout())
private val emptyState: StatusText = object : StatusText(this) {
override fun isStatusVisible(): Boolean {
return UIUtil.uiChildren(this@LibraryDescriptionPanel)
.filter { obj: Component -> obj.isVisible }
.isEmpty
}
}
init {
this.border = JBUI.Borders.empty(DEFAULT_VGAP)
val headerPanel = JPanel(BorderLayout())
descriptionHeader.font = StartupUiUtil.getLabelFont().deriveFont(Font.BOLD)
descriptionHeader.border = JBUI.Borders.empty(DEFAULT_VGAP, 0)
descriptionVersion.icon = AllIcons.General.BalloonWarning
descriptionVersion.border = JBUI.Borders.empty(DEFAULT_VGAP, 0, DEFAULT_VGAP * 2, 0)
descriptionVersion.isVisible = false
headerPanel.add(descriptionHeader, BorderLayout.NORTH)
headerPanel.add(descriptionVersion, BorderLayout.CENTER)
add(headerPanel)
descriptionText.background = JBColor.PanelBackground
descriptionText.isFocusable = false
descriptionText.lineWrap = true
descriptionText.wrapStyleWord = true
descriptionText.isEditable = false
descriptionText.font = JBUI.Fonts.label()
add(descriptionText)
linksPanel.border = JBUI.Borders.emptyTop(DEFAULT_VGAP * 2)
add(linksPanel)
emptyState.text = JavaStartersBundle.message("hint.no.library.selected")
showEmptyState()
}
fun update(library: LibraryInfo, @NlsSafe versionConstraint: String?) {
descriptionHeader.text = library.title
descriptionVersion.text = versionConstraint ?: ""
descriptionVersion.isVisible = versionConstraint != null
descriptionText.text = library.description
addDescriptionLinks(linksPanel, library)
showDescriptionUi()
}
fun update(@NlsSafe title: String, description: String?) {
descriptionHeader.text = title
descriptionVersion.text = ""
descriptionVersion.isVisible = false
descriptionText.text = description
linksPanel.removeAll()
showDescriptionUi()
}
fun reset() {
descriptionHeader.text = ""
descriptionVersion.text = ""
descriptionText.text = ""
descriptionVersion.isVisible = false
linksPanel.removeAll()
showEmptyState()
}
private fun showEmptyState() {
for (component in this.components) {
component.isVisible = false
}
revalidate()
repaint()
}
private fun showDescriptionUi() {
for (component in this.components) {
component.isVisible = true
}
revalidate()
repaint()
}
override fun paintComponent(g: Graphics?) {
super.paintComponent(g)
emptyState.paint(this, g)
}
override fun getComponentGraphics(graphics: Graphics?): Graphics {
return JBSwingUtilities.runGlobalCGTransform(this, super.getComponentGraphics(graphics))
}
private fun addDescriptionLinks(linksPanel: JPanel, item: LibraryInfo) {
linksPanel.removeAll()
for (link in item.links) {
if (link.url.contains('{')) continue // URL templates are not supported
val linkLabel = HyperlinkLabel(link.title ?: link.type.getTitle())
linkLabel.font = JBUI.Fonts.smallFont()
linkLabel.setHyperlinkTarget(link.url)
linkLabel.toolTipText = link.url
linksPanel.add(BorderLayoutPanel().apply {
addToCenter(linkLabel)
border = JBUI.Borders.empty(0, 0, 0, DEFAULT_HGAP / 2)
})
}
linksPanel.revalidate()
linksPanel.repaint()
}
// do not add horizontal gap - it is inserted before the first component
private class WrappedFlowLayout : FlowLayout(LEADING, 0, DEFAULT_VGAP) {
override fun preferredLayoutSize(target: Container): Dimension {
val baseSize = super.preferredLayoutSize(target)
if (alignOnBaseline) return baseSize
return getWrappedSize(target)
}
private fun getWrappedSize(target: Container): Dimension {
val parent = SwingUtilities.getUnwrappedParent(target)
val maxWidth = parent.width - (parent.insets.left + parent.insets.right)
return getDimension(target, maxWidth)
}
private fun getDimension(target: Container, maxWidth: Int): Dimension {
val insets = target.insets
var height = insets.top + insets.bottom
var width = insets.left + insets.right
var rowHeight = 0
var rowWidth = insets.left + insets.right
var isVisible = false
var start = true
synchronized(target.treeLock) {
for (i in 0 until target.componentCount) {
val component = target.getComponent(i)
if (component.isVisible) {
isVisible = true
val size = component.preferredSize
if (rowWidth + hgap + size.width > maxWidth && !start) {
height += vgap + rowHeight
width = max(width, rowWidth)
rowWidth = insets.left + insets.right
rowHeight = 0
}
rowWidth += hgap + size.width
rowHeight = max(rowHeight, size.height)
start = false
}
}
height += vgap + rowHeight
width = max(width, rowWidth)
if (!isVisible) {
return super.preferredLayoutSize(target)
}
return Dimension(width, height)
}
}
override fun minimumLayoutSize(target: Container): Dimension {
return if (alignOnBaseline) super.minimumLayoutSize(target) else getWrappedSize(target)
}
}
} | apache-2.0 | f42b04f93e7e348fec0726f52fcc87aa | 32.22 | 158 | 0.707813 | 4.537568 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/collections/SimplifyCallChainFix.kt | 2 | 5584 | // 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.inspections.collections
import com.intellij.codeInsight.actions.OptimizeImportsProcessor
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.moveFunctionLiteralOutsideParentheses
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.base.util.reformatted
import org.jetbrains.kotlin.idea.formatter.commitAndUnblockDocument
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.PsiChildRange
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class SimplifyCallChainFix(
private val conversion: AbstractCallChainChecker.Conversion,
private val removeReceiverOfFirstCall: Boolean = false,
private val runOptimizeImports: Boolean = false,
private val modifyArguments: KtPsiFactory.(KtCallExpression) -> Unit = {}
) : LocalQuickFix {
private val shortenedText = conversion.replacement.substringAfterLast(".")
override fun getName() = KotlinBundle.message("simplify.call.chain.fix.text", shortenedText)
override fun getFamilyName() = name
fun apply(qualifiedExpression: KtQualifiedExpression) {
val factory = KtPsiFactory(qualifiedExpression)
val firstExpression = qualifiedExpression.receiverExpression
val operationSign = if (removeReceiverOfFirstCall) "" else when (firstExpression) {
is KtSafeQualifiedExpression -> "?."
is KtQualifiedExpression -> "."
else -> ""
}
val receiverExpressionOrEmptyString =
if (!removeReceiverOfFirstCall && firstExpression is KtQualifiedExpression) firstExpression.receiverExpression.text else ""
val firstCallExpression = AbstractCallChainChecker.getCallExpression(firstExpression) ?: return
factory.modifyArguments(firstCallExpression)
val firstCallArgumentList = firstCallExpression.valueArgumentList
val secondCallExpression = qualifiedExpression.selectorExpression as? KtCallExpression ?: return
val secondCallArgumentList = secondCallExpression.valueArgumentList
val secondCallTrailingComma = secondCallArgumentList?.trailingComma
secondCallTrailingComma?.delete()
fun KtValueArgumentList.getTextInsideParentheses(): String {
val range = PsiChildRange(leftParenthesis?.nextSibling ?: firstChild, rightParenthesis?.prevSibling ?: lastChild)
return range.joinToString(separator = "") { it.text }
}
val lambdaExpression = firstCallExpression.lambdaArguments.singleOrNull()?.getLambdaExpression()
val additionalArgument = conversion.additionalArgument
val secondCallHasArguments = secondCallArgumentList?.arguments?.isNotEmpty() == true
val firstCallHasArguments = firstCallArgumentList?.arguments?.isNotEmpty() == true
val argumentsText = listOfNotNull(
secondCallArgumentList.takeIf { secondCallHasArguments }?.getTextInsideParentheses(),
firstCallArgumentList.takeIf { firstCallHasArguments }?.getTextInsideParentheses(),
additionalArgument.takeIf { !firstCallHasArguments && !secondCallHasArguments },
lambdaExpression?.text
).joinToString(separator = ",")
val newCallText = conversion.replacement
val newQualifiedOrCallExpression = factory.createExpression(
"$receiverExpressionOrEmptyString$operationSign$newCallText($argumentsText)"
)
val project = qualifiedExpression.project
val file = qualifiedExpression.containingKtFile
var result = qualifiedExpression.replaced(newQualifiedOrCallExpression)
if (lambdaExpression != null || additionalArgument != null) {
val callExpression = when (result) {
is KtQualifiedExpression -> result.callExpression
is KtCallExpression -> result
else -> null
}
callExpression?.moveFunctionLiteralOutsideParentheses()
}
if (secondCallTrailingComma != null && !firstCallHasArguments) {
val call = result.safeAs<KtQualifiedExpression>()?.callExpression ?: result.safeAs<KtCallExpression>()
call?.valueArgumentList?.arguments?.lastOrNull()?.add(factory.createComma())
}
if (conversion.addNotNullAssertion) {
result = result.replaced(factory.createExpressionByPattern("$0!!", result))
}
if (conversion.removeNotNullAssertion) {
val parent = result.parent
if (parent is KtPostfixExpression && parent.operationToken == KtTokens.EXCLEXCL) {
result = parent.replaced(result)
}
}
result.containingKtFile.commitAndUnblockDocument()
if (result.isValid) ShortenReferences.DEFAULT.process(result.reformatted() as KtElement)
if (runOptimizeImports) {
OptimizeImportsProcessor(project, file).run()
}
}
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
(descriptor.psiElement as? KtQualifiedExpression)?.let(this::apply)
}
} | apache-2.0 | efb78c9427217917a90c527e7cfca388 | 48.866071 | 158 | 0.729585 | 5.727179 | false | false | false | false |
jotomo/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/EditTriggerDialog.kt | 1 | 4576 | package info.nightscout.androidaps.plugins.general.automation.dialogs
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.databinding.AutomationDialogEditTriggerBinding
import info.nightscout.androidaps.dialogs.DialogFragmentWithDate
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationUpdateTrigger
import info.nightscout.androidaps.plugins.general.automation.events.EventTriggerChanged
import info.nightscout.androidaps.plugins.general.automation.events.EventTriggerClone
import info.nightscout.androidaps.plugins.general.automation.events.EventTriggerRemove
import info.nightscout.androidaps.plugins.general.automation.triggers.Trigger
import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerConnector
import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerDummy
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.extensions.plusAssign
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import org.json.JSONObject
import javax.inject.Inject
class EditTriggerDialog : DialogFragmentWithDate() {
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var mainApp: MainApp
@Inject lateinit var fabricPrivacy: FabricPrivacy
private var disposable: CompositeDisposable = CompositeDisposable()
private var triggers: Trigger? = null
private var _binding: AutomationDialogEditTriggerBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
// load data from bundle
(savedInstanceState ?: arguments)?.let { bundle ->
bundle.getString("trigger")?.let { triggers = TriggerDummy(mainApp).instantiate(JSONObject(it)) }
}
onCreateViewGeneral()
_binding = AutomationDialogEditTriggerBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
disposable += rxBus
.toObservable(EventTriggerChanged::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
binding.layoutTrigger.removeAllViews()
triggers?.generateDialog(binding.layoutTrigger)
}, { fabricPrivacy.logException(it) })
disposable += rxBus
.toObservable(EventTriggerRemove::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
findParent(triggers, it.trigger)?.list?.remove(it.trigger)
binding.layoutTrigger.removeAllViews()
triggers?.generateDialog(binding.layoutTrigger)
}, { fabricPrivacy.logException(it) })
disposable += rxBus
.toObservable(EventTriggerClone::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
findParent(triggers, it.trigger)?.list?.add(it.trigger.duplicate())
binding.layoutTrigger.removeAllViews()
triggers?.generateDialog(binding.layoutTrigger)
}, { fabricPrivacy.logException(it) })
// display root trigger
triggers?.generateDialog(binding.layoutTrigger)
}
override fun onDestroyView() {
super.onDestroyView()
disposable.clear()
_binding = null
}
override fun submit(): Boolean {
triggers?.let { trigger -> rxBus.send(EventAutomationUpdateTrigger(trigger)) }
return true
}
override fun onSaveInstanceState(savedInstanceState: Bundle) {
super.onSaveInstanceState(savedInstanceState)
triggers?.let { savedInstanceState.putString("trigger", it.toJSON()) }
}
private fun findParent(where: Trigger?, what: Trigger): TriggerConnector? {
if (where == null) return null
if (where is TriggerConnector) {
for (i in where.list) {
if (i == what) return where
if (i is TriggerConnector) return findParent(i, what)
}
}
return null
}
} | agpl-3.0 | 4d2d1060f17f0c265694dfdaa249aa64 | 40.234234 | 109 | 0.708479 | 5.223744 | false | false | false | false |
devjn/GithubSearch | app/src/main/kotlin/com/github/devjn/githubsearch/widgets/EndlessRecyclerViewScrollListener.kt | 1 | 4582 | package com.github.devjn.githubsearch.widgets
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.StaggeredGridLayoutManager
/**
* Endless [RecyclerView.OnScrollListener] implementation by @codepath
*/
abstract class EndlessRecyclerViewScrollListener : RecyclerView.OnScrollListener {
// The minimum amount of items to have below your current scroll position
// before loading more.
private var visibleThreshold = 5
// The current offset index of data you have loaded
private var currentPage = 0
// The total number of items in the dataset after the last load
private var previousTotalItemCount = 0
// True if we are still waiting for the last set of data to load.
private var loading = true
// Sets the starting page index
private val startingPageIndex = 0
internal var mLayoutManager: RecyclerView.LayoutManager
constructor(layoutManager: LinearLayoutManager) {
this.mLayoutManager = layoutManager
}
constructor(layoutManager: GridLayoutManager) {
this.mLayoutManager = layoutManager
visibleThreshold *= layoutManager.spanCount
}
constructor(layoutManager: StaggeredGridLayoutManager) {
this.mLayoutManager = layoutManager
visibleThreshold *= layoutManager.spanCount
}
fun getLastVisibleItem(lastVisibleItemPositions: IntArray): Int {
var maxSize = 0
for (i in lastVisibleItemPositions.indices) {
if (i == 0) {
maxSize = lastVisibleItemPositions[i]
} else if (lastVisibleItemPositions[i] > maxSize) {
maxSize = lastVisibleItemPositions[i]
}
}
return maxSize
}
// This happens many times a second during a scroll, so be wary of the code you place here.
// We are given a few useful parameters to help us work out if we need to load some more data,
// but first we check if we are waiting for the previous load to finish.
override fun onScrolled(view: RecyclerView, dx: Int, dy: Int) {
var lastVisibleItemPosition = 0
val totalItemCount = mLayoutManager.itemCount
if (mLayoutManager is StaggeredGridLayoutManager) {
val lastVisibleItemPositions = (mLayoutManager as StaggeredGridLayoutManager).findLastVisibleItemPositions(null)
// get maximum element within the list
lastVisibleItemPosition = getLastVisibleItem(lastVisibleItemPositions)
} else if (mLayoutManager is GridLayoutManager) {
lastVisibleItemPosition = (mLayoutManager as GridLayoutManager).findLastVisibleItemPosition()
} else if (mLayoutManager is LinearLayoutManager) {
lastVisibleItemPosition = (mLayoutManager as LinearLayoutManager).findLastVisibleItemPosition()
}
// If the total item count is zero and the previous isn't, assume the
// list is invalidated and should be reset back to initial state
if (totalItemCount < previousTotalItemCount) {
this.currentPage = this.startingPageIndex
this.previousTotalItemCount = totalItemCount
if (totalItemCount == 0) {
this.loading = true
}
}
// If it’s still loading, we check to see if the dataset count has
// changed, if so we conclude it has finished loading and update the current page
// number and total item count.
if (loading && totalItemCount > previousTotalItemCount) {
loading = false
previousTotalItemCount = totalItemCount
}
// If it isn’t currently loading, we check to see if we have breached
// the visibleThreshold and need to reload more data.
// If we do need to reload some more data, we execute onLoadMore to fetch the data.
// threshold should reflect how many total columns there are too
if (!loading && lastVisibleItemPosition + visibleThreshold > totalItemCount) {
currentPage++
onLoadMore(currentPage, totalItemCount, view)
loading = true
}
}
// Call this method whenever performing new searches
fun resetState() {
this.currentPage = this.startingPageIndex
this.previousTotalItemCount = 0
this.loading = true
}
// Defines the process for actually loading more data based on page
abstract fun onLoadMore(page: Int, totalItemsCount: Int, view: RecyclerView)
} | apache-2.0 | 63ddbfa6348a3c3c4d63ca4778976538 | 41.794393 | 124 | 0.690258 | 5.576127 | false | false | false | false |
hsson/card-balance-app | app/src/main/java/se/creotec/chscardbalance2/Constants.kt | 1 | 2344 | // Copyright (c) 2017 Alexander Håkansson
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
package se.creotec.chscardbalance2
object Constants {
// Set to true to show upgrade screen. Useful when making big changes.
// Don't forget to set to false again for next release.
val VERSION_SHOULD_SHOW_UPGRADE_INTRO = false
val NOTIFICATION_CHANNEL_BALANCE = "balance_channel_id"
val ENDPOINT_BALANCE = "/balance/v2"
val ENDPOINT_MENU = "/menu"
val ENDPOINT_CHARGE = "/charge"
val ENDPOINT_MENU_LANG_EN = "en"
val ENDPOINT_MENU_LANG_SV = "sv"
val ENDPOINT_TIMEOUT: Int = 10 * 1000 // Milliseconds
val CARD_NUMBER_LENGTH: Int = 16
val CARD_CURRENCY_SUFFIX = "SEK"
val ACTION_UPDATE_CARD = BuildConfig.APPLICATION_ID + ".ACTION_UPDATE_CARD"
val ACTION_UPDATE_MENU = BuildConfig.APPLICATION_ID + ".ACTION_UPDATE_MENU"
val ACTION_COPY_CARD_NUMBER = BuildConfig.APPLICATION_ID + ".ACTION_COPY_CARD_NUMBER"
val ACTION_BOOT_COMPLETED = "android.intent.action.BOOT_COMPLETED"
val EXTRAS_CARD_NUMBER_KEY = BuildConfig.APPLICATION_ID + ".EXTRAS_CARD_NUMBER_KEY"
val PREFS_FILE_NAME = "PreferenceConfig"
val PREFS_VERSION_CODE_KEY = "version_code"
val PREFS_VERSION_CODE_NONEXISTING = -1
val PREFS_CARD_DATA_KEY = "card_data"
val PREFS_CARD_LAST_UPDATED_KEY = "card_last_updated"
val PREFS_MENU_LANGUAGE_KEY = "menu_preferred_language"
val PREFS_MENU_LANGUAGE_DEFAULT = ENDPOINT_MENU_LANG_EN
val PREFS_MENU_DATA_KEY = "menu_data"
val PREFS_NOTIFICATIONS_DATA_KEY = "notifications_data"
val PREFS_COOKIE_USERINFO_KEY = "card_login_user_info"
val PREFS_NOTIFICATION_LOW_BALANCE_ENABLED_DEFAULT = true
val PREFS_NOTIFICATION_LOW_BALANCE_LIMIT_DEFAULT: Int = 50
val PREFS_NOTIFICATION_LOW_BALANCE_LIMIT_MIN: Int = 10
val PREFS_NOTIFICATION_LOW_BALANCE_LIMIT_MAX: Int = 200
val PREFS_MENU_LAST_UPDATED_KEY = "menu_last_updated"
val PREFS_CARD_NUMBER_LEGACY_KEY = "se.creotec.chscardbalance.PREFS_CARD_NUMBER"
val PREFS_FILE_NAME_LEGACY = "se.creotec.chscardbalance.SHARED_PREFS_NAME"
val INTENT_RESTAURANT_DATA_KEY = BuildConfig.APPLICATION_ID + ".RESTAURANT_DATA"
val GITHUB_URL = "https://github.com/hsson/card-balance-app/"
val COOKIE_USERINFO = "userInfo"
}
| mit | d5bbbf8887d878b8eb89926df58d18b9 | 42.388889 | 89 | 0.716603 | 3.55 | false | true | false | false |
ThePreviousOne/Untitled | app/src/main/java/eu/kanade/tachiyomi/widget/PTSansTextView.kt | 2 | 1405 | package eu.kanade.tachiyomi.widget
import android.content.Context
import android.graphics.Canvas
import android.graphics.Typeface
import android.util.AttributeSet
import android.widget.TextView
import eu.kanade.tachiyomi.R
import java.util.*
class PTSansTextView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :
TextView(context, attrs) {
companion object {
const val PTSANS_NARROW = 0
const val PTSANS_NARROW_BOLD = 1
// Map where typefaces are cached
private val typefaces = HashMap<Int, Typeface>(2)
}
init {
if (attrs != null) {
val values = context.obtainStyledAttributes(attrs, R.styleable.PTSansTextView)
val typeface = values.getInt(R.styleable.PTSansTextView_typeface, 0)
setTypeface(typefaces.getOrPut(typeface) {
Typeface.createFromAsset(context.assets, when (typeface) {
PTSANS_NARROW -> "fonts/PTSans-Narrow.ttf"
PTSANS_NARROW_BOLD -> "fonts/PTSans-NarrowBold.ttf"
else -> throw IllegalArgumentException("Font not found " + typeface)
})
})
values.recycle()
}
}
override fun draw(canvas: Canvas) {
// Draw two times for a more visible shadow around the text
super.draw(canvas)
super.draw(canvas)
}
}
| gpl-3.0 | 13ea28e80dcaea3352113e1515e9afff | 28.893617 | 95 | 0.634875 | 4.33642 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/frontend-fir/src/org/jetbrains/kotlin/idea/references/KtFirCollectionLiteralReference.kt | 2 | 2990 | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.references
import org.jetbrains.kotlin.fir.declarations.FirFunction
import org.jetbrains.kotlin.fir.declarations.FirSimpleFunction
import org.jetbrains.kotlin.fir.expressions.FirArrayOfCall
import org.jetbrains.kotlin.fir.resolve.firSymbolProvider
import org.jetbrains.kotlin.fir.symbols.CallableId
import org.jetbrains.kotlin.fir.symbols.StandardClassIds
import org.jetbrains.kotlin.fir.symbols.impl.FirFunctionSymbol
import org.jetbrains.kotlin.fir.types.ConeClassLikeType
import org.jetbrains.kotlin.fir.types.coneType
import org.jetbrains.kotlin.fir.types.coneTypeSafe
import org.jetbrains.kotlin.idea.fir.low.level.api.api.getOrBuildFirSafe
import org.jetbrains.kotlin.idea.frontend.api.KtAnalysisSession
import org.jetbrains.kotlin.idea.frontend.api.fir.KtFirAnalysisSession
import org.jetbrains.kotlin.idea.frontend.api.symbols.KtSymbol
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtCollectionLiteralExpression
class KtFirCollectionLiteralReference(
expression: KtCollectionLiteralExpression
) : KtCollectionLiteralReference(expression), KtFirReference {
override fun KtAnalysisSession.resolveToSymbols(): Collection<KtSymbol> {
check(this is KtFirAnalysisSession)
val fir = element.getOrBuildFirSafe<FirArrayOfCall>(firResolveState) ?: return emptyList()
val type = fir.typeRef.coneTypeSafe<ConeClassLikeType>() ?: return listOfNotNull(arrayOfSymbol(arrayOf))
val call = arrayTypeToArrayOfCall[type.lookupTag.classId] ?: arrayOf
return listOfNotNull(arrayOfSymbol(call))
}
private fun KtFirAnalysisSession.arrayOfSymbol(identifier: Name): KtSymbol? {
val fir = firResolveState.rootModuleSession.firSymbolProvider.getTopLevelCallableSymbols(kotlinPackage, identifier).firstOrNull {
/* choose (for byte array)
* public fun byteArrayOf(vararg elements: kotlin.Byte): kotlin.ByteArray
*/
(it as? FirFunctionSymbol<*>)?.fir?.valueParameters?.singleOrNull()?.isVararg == true
}?.fir as? FirSimpleFunction ?: return null
return firSymbolBuilder.buildFunctionSymbol(fir)
}
companion object {
private val kotlinPackage = FqName("kotlin")
private val arrayOf = Name.identifier("arrayOf")
private val arrayTypeToArrayOfCall = run {
StandardClassIds.primitiveArrayTypeByElementType.values + StandardClassIds.unsignedArrayTypeByElementType.values
}.associateWith { it.correspondingArrayOfCallFqName() }
private fun ClassId.correspondingArrayOfCallFqName(): Name =
Name.identifier("${shortClassName.identifier.decapitalize()}Of")
}
} | apache-2.0 | fa764d4f806b6a1153ea22f99866d540 | 49.694915 | 137 | 0.776589 | 4.6 | false | false | false | false |
siosio/intellij-community | java/java-tests/testSrc/com/intellij/util/indexing/MultiProjectIndexTest.kt | 2 | 5816 | // 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.util.indexing
import com.intellij.find.ngrams.TrigramIndex
import com.intellij.ide.plugins.loadExtensionWithText
import com.intellij.openapi.extensions.InternalIgnoreDependencyViolation
import com.intellij.openapi.module.JavaModuleType
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.psi.stubs.StubIndexKey
import com.intellij.psi.stubs.StubUpdatingIndex
import com.intellij.testFramework.*
import com.intellij.testFramework.rules.TempDirectory
import com.intellij.util.ui.UIUtil
import junit.framework.TestCase
import org.junit.Rule
import org.junit.Test
import java.nio.file.Path
import java.util.concurrent.atomic.AtomicInteger
import kotlin.io.path.writeText
import kotlin.test.assertEquals
const val fileNameMarkerPrefix = "TestFoo"
@RunsInEdt
class MultiProjectIndexTest {
@Rule
@JvmField
val tempDir = TempDirectory()
@Rule
@JvmField
val disposable = DisposableRule()
@Rule
@JvmField
val appRule = ApplicationRule()
@Rule
@JvmField
val runInEdt = EdtRule()
@Test
fun `test index extension process files intersection`() {
val text = "<fileBasedIndexInfrastructureExtension implementation=\"" + CountingTestExtension::class.java.name + "\"/>"
Disposer.register(disposable.disposable, loadExtensionWithText(text))
val ext = FileBasedIndexInfrastructureExtension.EP_NAME.findExtension(CountingTestExtension::class.java)!!
val projectPath1 = tempDir.newDirectory("project1").toPath()
val projectPath2 = tempDir.newDirectory("project2").toPath()
val commonContentRoot = tempDir.newDirectory("common-content-root").toPath()
commonContentRoot.resolve("${fileNameMarkerPrefix}1.txt").writeText("hidden gem")
commonContentRoot.resolve("${fileNameMarkerPrefix}2.txt").writeText("foobar")
val project1 = openProject(projectPath1)
val project2 = openProject(projectPath2)
val module1 = PsiTestUtil.addModule(project1, JavaModuleType.getModuleType(), "module1", projectPath1.toVirtualFile())
val module2 = PsiTestUtil.addModule(project2, JavaModuleType.getModuleType(), "module2", projectPath1.toVirtualFile())
PsiTestUtil.addContentRoot(module1, commonContentRoot.toVirtualFile())
assertEquals(0, ext.trigramCounter.get())
assertEquals(2, ext.stubCounter.get()) // stubs should not be build for txt files
val commonBundledFileCount = ext.commonBundledFileCounter.get()
PsiTestUtil.addContentRoot(module2, commonContentRoot.toVirtualFile())
assertEquals(2, ext.trigramCounter.get())
assertEquals(2, ext.stubCounter.get())
assertEquals(commonBundledFileCount, ext.commonBundledFileCounter.get())
ProjectManagerEx.getInstanceEx().forceCloseProject(project1)
ProjectManagerEx.getInstanceEx().forceCloseProject(project2)
TestCase.assertTrue(project1.isDisposed)
TestCase.assertTrue(project2.isDisposed)
}
private fun openProject(path: Path): Project {
val project = PlatformTestUtil.loadAndOpenProject(path, disposable.disposable)
do {
UIUtil.dispatchAllInvocationEvents() // for post-startup activities
}
while (DumbService.getInstance(project).isDumb)
return project
}
private fun Path.toVirtualFile(): VirtualFile = VirtualFileManager.getInstance().refreshAndFindFileByNioPath(this)!!
}
@InternalIgnoreDependencyViolation
internal class CountingTestExtension : FileBasedIndexInfrastructureExtension {
val stubCounter = AtomicInteger()
val trigramCounter = AtomicInteger()
val commonBundledFileCounter = AtomicInteger()
override fun createFileIndexingStatusProcessor(project: Project): FileBasedIndexInfrastructureExtension.FileIndexingStatusProcessor? {
return object : FileBasedIndexInfrastructureExtension.FileIndexingStatusProcessor {
override fun shouldProcessUpToDateFiles(): Boolean = true
override fun processUpToDateFile(file: IndexedFile, inputId: Int, indexId: ID<*, *>): Boolean {
if (file.fileName.startsWith(fileNameMarkerPrefix)) {
if (indexId == TrigramIndex.INDEX_ID) {
trigramCounter.incrementAndGet()
}
else if (indexId == StubUpdatingIndex.INDEX_ID) {
stubCounter.incrementAndGet()
}
}
if (file.fileName == "svg20.rnc" && indexId == TrigramIndex.INDEX_ID) {
commonBundledFileCounter.incrementAndGet()
}
return true
}
override fun tryIndexFileWithoutContent(file: IndexedFile, inputId: Int, indexId: ID<*, *>): Boolean = false
override fun hasIndexForFile(file: VirtualFile, inputId: Int, extension: FileBasedIndexExtension<*, *>): Boolean = false
}
}
override fun <K : Any?, V : Any?> combineIndex(indexExtension: FileBasedIndexExtension<K, V>,
baseIndex: UpdatableIndex<K, V, FileContent>): UpdatableIndex<K, V, FileContent> {
return baseIndex
}
override fun onFileBasedIndexVersionChanged(indexId: ID<*, *>) = Unit
override fun onStubIndexVersionChanged(indexId: StubIndexKey<*, *>) = Unit
override fun initialize(indexLayoutId: String?): FileBasedIndexInfrastructureExtension.InitializationResult =
FileBasedIndexInfrastructureExtension.InitializationResult.SUCCESSFULLY
override fun resetPersistentState() = Unit
override fun resetPersistentState(indexId: ID<*, *>) = Unit
override fun shutdown() = Unit
override fun getVersion(): Int = 0
} | apache-2.0 | 7a5729d142c3d1d62f4444dba8d2d279 | 39.395833 | 158 | 0.761348 | 4.747755 | false | true | false | false |
jwren/intellij-community | plugins/kotlin/base/plugin/src/org/jetbrains/kotlin/idea/compiler/configuration/IdeKotlinVersion.kt | 1 | 8631 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.compiler.configuration
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.io.JarUtil
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.text.VersionComparatorUtil
import org.jetbrains.kotlin.config.ApiVersion
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.config.LanguageVersionSettingsImpl
import org.jetbrains.kotlin.util.capitalizeDecapitalize.toLowerCaseAsciiOnly
import java.util.jar.Attributes
/**
* Tests - [org.jetbrains.kotlin.IdeKotlinVersionTest] + [org.jetbrains.kotlin.test.CompatibilityVerifierVersionComparisonTest]
*/
class IdeKotlinVersion private constructor(
@get:NlsSafe val rawVersion: String,
val kotlinVersion: KotlinVersion,
val kind: Kind,
@get:NlsSafe val buildNumber: String?,
val languageVersion: LanguageVersion,
val apiVersion: ApiVersion
): Comparable<IdeKotlinVersion> {
companion object {
private val KOTLIN_COMPILER_VERSION_PATTERN = (
"^(\\d+)" + // major
"\\.(\\d+)" + // minor
"\\.(\\d+)" + // patch
"(?:-([A-Za-z]\\w+(?:-release)?))?" + // kind suffix
"(?:-(\\d+)?)?$" // build number
).toRegex(RegexOption.IGNORE_CASE)
@JvmStatic
fun get(@NlsSafe rawVersion: String): IdeKotlinVersion {
return parse(rawVersion).getOrThrow()
}
@JvmStatic
fun opt(@NlsSafe rawVersion: String): IdeKotlinVersion? {
return parse(rawVersion).getOrNull()
}
@JvmStatic
fun fromKotlinVersion(version: KotlinVersion): IdeKotlinVersion {
val languageVersion = LanguageVersion.values().first { it.major == version.major && it.minor == version.minor }
return IdeKotlinVersion(
rawVersion = version.toString(),
kotlinVersion = version,
kind = Kind.Release,
buildNumber = null,
languageVersion = languageVersion,
apiVersion = ApiVersion.createByLanguageVersion(languageVersion)
)
}
@JvmStatic
fun fromLanguageVersion(languageVersion: LanguageVersion): IdeKotlinVersion {
return IdeKotlinVersion(
rawVersion = "${languageVersion.major}.${languageVersion.minor}.0",
kotlinVersion = KotlinVersion(languageVersion.major, languageVersion.minor, 0),
kind = Kind.Release,
buildNumber = null,
languageVersion = languageVersion,
apiVersion = ApiVersion.createByLanguageVersion(languageVersion)
)
}
@JvmStatic
fun fromManifest(jarFile: VirtualFile): IdeKotlinVersion? {
val ioFile = VfsUtilCore.virtualToIoFile(jarFile)
val unprocessedVersion = JarUtil.getJarAttribute(ioFile, Attributes.Name.IMPLEMENTATION_VERSION) ?: return null
// "Implementation-Version" in MANIFEST.MF is sometimes written as '1.5.31-release-548(1.5.31)'
val rawVersion = unprocessedVersion.substringBefore('(').trim()
return opt(rawVersion)
}
private fun parseKind(kindSuffix: String, vararg prefixes: String, factory: (Int) -> Kind): Kind? {
for (prefix in prefixes) {
if (kindSuffix.startsWith(prefix)) {
val numberString = kindSuffix.drop(prefix.length).removeSuffix("-release")
if (numberString.isEmpty()) {
return factory(1)
} else {
val number = numberString.toIntOrNull() ?: return null
return factory(number)
}
}
}
error("None of prefixes $prefixes found in kind suffix \"$kindSuffix\"")
}
fun parse(rawVersion: String): Result<IdeKotlinVersion> {
val matchResult = KOTLIN_COMPILER_VERSION_PATTERN.matchEntire(rawVersion)
?: return Result.failure(IllegalArgumentException("Unsupported compiler version: $rawVersion"))
val majorValue = matchResult.groupValues[1].toIntOrNull()
?: return Result.failure(IllegalArgumentException("Invalid major version component: $rawVersion"))
val minorValue = matchResult.groupValues[2].toIntOrNull()
?: return Result.failure(IllegalArgumentException("Invalid minor version component: $rawVersion"))
val patchValue = matchResult.groupValues[3].toIntOrNull()
?: return Result.failure(IllegalArgumentException("Invalid patch version component: $rawVersion"))
val kotlinVersion = KotlinVersion(majorValue, minorValue, patchValue)
val kindSuffix = matchResult.groupValues[4].toLowerCaseAsciiOnly()
val kind = when {
kindSuffix == "release" || kindSuffix == "" -> Kind.Release
kindSuffix == "dev" -> Kind.Dev
kindSuffix == "snapshot" || kindSuffix == "local" -> Kind.Snapshot
kindSuffix.startsWith("rc") -> parseKind(kindSuffix, "rc") { Kind.ReleaseCandidate(it) }
kindSuffix.startsWith("beta") -> parseKind(kindSuffix, "beta") { Kind.Beta(it) }
kindSuffix.startsWith("m") || kindSuffix.startsWith("eap") -> parseKind(kindSuffix, "m", "eap") { Kind.Milestone(it) }
else -> null
} ?: return Result.failure(IllegalArgumentException("Unsupported version kind suffix: \"$kindSuffix\" ($rawVersion)"))
val buildNumber = matchResult.groupValues[5].takeIf { it.isNotEmpty() }
val languageVersion = LanguageVersion.values().firstOrNull { it.major == majorValue && it.minor == minorValue }
?: LanguageVersion.FIRST_SUPPORTED
val apiVersion = ApiVersion.createByLanguageVersion(languageVersion)
val ideKotlinVersion = IdeKotlinVersion(rawVersion, kotlinVersion, kind, buildNumber, languageVersion, apiVersion)
return Result.success(ideKotlinVersion)
}
}
sealed class Kind(val artifactSuffix: String?, val requireBuildNumber: Boolean = false) {
object Release : Kind(artifactSuffix = null)
data class ReleaseCandidate(val number: Int) : Kind(artifactSuffix = if (number == 1) "RC" else "RC$number")
data class Beta(val number: Int) : Kind(artifactSuffix = "Beta$number")
data class Milestone(val number: Int) : Kind(artifactSuffix = "M$number")
object Dev : Kind(artifactSuffix = "dev", requireBuildNumber = true)
object Snapshot : Kind(artifactSuffix = "SNAPSHOT", requireBuildNumber = true)
override fun toString(): String = javaClass.simpleName
}
val baseVersion: String
get() = kotlinVersion.toString()
val artifactVersion: String
get() = buildString {
append(baseVersion)
if (kind.artifactSuffix != null) {
append('-').append(kind.artifactSuffix)
if (kind.requireBuildNumber && buildNumber != null) {
append('-').append(buildNumber)
}
}
}
val isRelease: Boolean
get() = kind == Kind.Release
val isPreRelease: Boolean
get() = !isRelease
val isDev: Boolean
get() = kind == Kind.Dev
val isSnapshot: Boolean
get() = kind == Kind.Snapshot
val languageVersionSettings: LanguageVersionSettings
get() = LanguageVersionSettingsImpl(languageVersion, apiVersion)
override fun equals(other: Any?): Boolean {
if (this === other) return true
val otherVersion = (other as? IdeKotlinVersion) ?: return false
return this.rawVersion == otherVersion.rawVersion
}
override fun hashCode(): Int {
return rawVersion.hashCode()
}
override fun toString(): String {
return rawVersion
}
override fun compareTo(other: IdeKotlinVersion): Int {
return VersionComparatorUtil.compare(this.rawVersion, other.rawVersion)
}
fun compare(otherRawVersion: String): Int {
return VersionComparatorUtil.compare(this.rawVersion, otherRawVersion)
}
fun compare(other: IdeKotlinVersion): Int {
return VersionComparatorUtil.compare(this.rawVersion, other.rawVersion)
}
} | apache-2.0 | 3e1d9389aa3060d30a822aa0f45c8a91 | 42.16 | 134 | 0.637122 | 5.177564 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/stackFrame/ExistingVariables.kt | 6 | 1561 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.stackFrame
import com.intellij.debugger.jdi.LocalVariableProxyImpl
internal sealed class ExistingVariable {
interface This
object UnlabeledThis : ExistingVariable(), This
data class LabeledThis(val label: String) : ExistingVariable(), This
data class Ordinary(val name: String) : ExistingVariable()
}
internal class ExistingVariables(thisVariables: List<LocalVariableProxyImpl>, ordinaryVariables: List<LocalVariableProxyImpl>) {
private val set = HashSet<ExistingVariable>()
var hasThisVariables: Boolean
private set
init {
thisVariables.forEach {
val thisVariable = it as? ThisLocalVariable ?: return@forEach
val label = thisVariable.label
val newExistingVariable: ExistingVariable = when {
label != null -> ExistingVariable.LabeledThis(label)
else -> ExistingVariable.UnlabeledThis
}
set.add(newExistingVariable)
}
hasThisVariables = thisVariables.isNotEmpty()
ordinaryVariables.forEach { set += ExistingVariable.Ordinary(it.name()) }
}
fun add(variable: ExistingVariable): Boolean {
val result = set.add(variable)
if (result && !hasThisVariables && variable is ExistingVariable.This) {
hasThisVariables = true
}
return result
}
} | apache-2.0 | ce944a2d4afd06f5b73a1a1e7d5ea158 | 34.5 | 158 | 0.686739 | 4.939873 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/script/AbstractScriptConfigurationTest.kt | 1 | 14924 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.script
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.module.JavaModuleType
import com.intellij.openapi.module.Module
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.IdeaTestUtil
import com.intellij.testFramework.PlatformTestCase
import com.intellij.testFramework.PsiTestUtil
import com.intellij.util.ThrowableRunnable
import com.intellij.util.ui.UIUtil
import org.jdom.Element
import org.jetbrains.kotlin.idea.completion.test.KotlinCompletionTestCase
import org.jetbrains.kotlin.idea.core.script.IdeScriptReportSink
import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager.Companion.updateScriptDependenciesSynchronously
import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionContributor
import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionsManager
import org.jetbrains.kotlin.idea.core.script.settings.KotlinScriptingSettings
import org.jetbrains.kotlin.idea.base.highlighting.shouldHighlightFile
import org.jetbrains.kotlin.idea.base.plugin.artifacts.KotlinArtifacts
import org.jetbrains.kotlin.idea.base.plugin.artifacts.TestKotlinArtifacts
import org.jetbrains.kotlin.idea.script.AbstractScriptConfigurationTest.Companion.useDefaultTemplate
import org.jetbrains.kotlin.idea.test.KotlinCompilerStandalone
import org.jetbrains.kotlin.idea.test.KotlinTestUtils
import org.jetbrains.kotlin.idea.test.PluginTestCaseBase
import org.jetbrains.kotlin.idea.test.runAll
import org.jetbrains.kotlin.idea.util.projectStructure.getModuleDir
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.scripting.definitions.findScriptDefinition
import org.jetbrains.kotlin.test.TestJdkKind
import org.jetbrains.kotlin.test.util.addDependency
import org.jetbrains.kotlin.test.util.projectLibrary
import java.io.File
import java.nio.file.Paths
import kotlin.script.dependencies.Environment
import kotlin.script.experimental.api.ScriptDiagnostic
// some bugs can only be reproduced when some module and script have intersecting library dependencies
private const val configureConflictingModule = "// CONFLICTING_MODULE"
private fun String.splitOrEmpty(delimeters: String) = split(delimeters).takeIf { it.size > 1 } ?: emptyList()
internal val switches = listOf(
useDefaultTemplate,
configureConflictingModule
)
abstract class AbstractScriptConfigurationTest : KotlinCompletionTestCase() {
companion object {
private const val SCRIPT_NAME = "script.kts"
val validKeys = setOf("javaHome", "sources", "classpath", "imports", "template-classes-names")
const val useDefaultTemplate = "// DEPENDENCIES:"
const val templatesSettings = "// TEMPLATES: "
}
override fun setUpModule() {
// do not create default module
}
private fun findMainScript(testDir: File): File {
testDir.walkTopDown().find { it.name == SCRIPT_NAME }?.let { return it }
return testDir.walkTopDown().singleOrNull { it.name.contains("script") }
?: error("Couldn't find $SCRIPT_NAME file in $testDir")
}
private val sdk by lazy {
runWriteAction {
val sdk = PluginTestCaseBase.addJdk(testRootDisposable) { IdeaTestUtil.getMockJdk18() }
ProjectRootManager.getInstance(project).projectSdk = sdk
sdk
}
}
protected fun configureScriptFile(path: File): VirtualFile {
val mainScriptFile = findMainScript(path)
return configureScriptFile(path, mainScriptFile)
}
protected fun configureScriptFile(path: File, mainScriptFile: File): VirtualFile {
val environment = createScriptEnvironment(mainScriptFile)
registerScriptTemplateProvider(environment)
File(path, "mainModule").takeIf { it.exists() }?.let {
myModule = createTestModuleFromDir(it)
}
path.listFiles { file -> file.name.startsWith("module") }
?.filter { it.exists() }
?.forEach {
val newModule = createTestModuleFromDir(it)
assert(myModule != null) { "Main module should exists" }
ModuleRootModificationUtil.addDependency(myModule, newModule)
}
path.listFiles { file ->
file.name.startsWith("script") && file.name != SCRIPT_NAME
}?.forEach {
createFileAndSyncDependencies(it)
}
// If script is inside module
if (module != null && mainScriptFile.parentFile.name.toLowerCase().contains("module")) {
module.addDependency(
projectLibrary(
"script-runtime",
classesRoot = VfsUtil.findFileByIoFile(TestKotlinArtifacts.kotlinScriptRuntime, true)
)
)
if (environment["template-classes"] != null) {
environment.toVirtualFiles("template-classes").forEach {
module.addDependency(
projectLibrary("script-template-library", classesRoot = it)
)
}
}
}
if (configureConflictingModule in environment) {
if (module == null) {
// Force create module if it doesn't exist
myModule = createTestModuleByName("mainModule")
}
val sharedLib = environment.toVirtualFiles("lib-classes")
val sharedLibSources = environment.toVirtualFiles("lib-source")
check(sharedLib.size == sharedLibSources.size) { "$sharedLib and $sharedLibSources must have the same length" }
sharedLib.zip(sharedLibSources).forEachIndexed { index, (lib, sources) ->
module.addDependency(projectLibrary("sharedLib_$index", classesRoot = lib, sourcesRoot = sources))
}
}
module?.let {
ModuleRootModificationUtil.updateModel(it) { model ->
model.sdk = sdk
}
}
return createFileAndSyncDependencies(mainScriptFile)
}
private fun Environment.toVirtualFiles(name: String): List<VirtualFile> {
val list = this[name] as? List<Any?> ?: error("'$name' must be a List")
return list.map { it as? File ?: error("'$name' list must contain only Files") }
.map { VfsUtil.findFileByIoFile(it, true) ?: error("unable to look up a virtual file for $name: $it") }
}
private val oldScripClasspath: String? = System.getProperty("kotlin.script.classpath")
private var settings: Element? = null
override fun setUp() {
super.setUp()
settings = KotlinScriptingSettings.getInstance(project).state
ScriptDefinitionsManager.getInstance(project).getAllDefinitions().forEach {
KotlinScriptingSettings.getInstance(project).setEnabled(it, false)
}
setUpTestProject()
}
open fun setUpTestProject() {
}
override fun tearDown() {
runAll(
ThrowableRunnable { System.setProperty("kotlin.script.classpath", oldScripClasspath ?: "") },
ThrowableRunnable {
settings?.let {
KotlinScriptingSettings.getInstance(project).loadState(it)
}
},
ThrowableRunnable { super.tearDown() }
)
}
override fun getTestProjectJdk(): Sdk {
return IdeaTestUtil.getMockJdk18()
}
protected fun createTestModuleByName(name: String): Module {
val path = File(project.basePath, name).path
val newModuleDir = runWriteAction { VfsUtil.createDirectoryIfMissing(path) ?: error("unable to create $path") }
val newModule = createModuleAt(name, project, JavaModuleType.getModuleType(), Paths.get(newModuleDir.path))
PsiTestUtil.addSourceContentToRoots(newModule, newModuleDir)
return newModule
}
private fun createTestModuleFromDir(dir: File): Module {
return createTestModuleByName(dir.name).apply {
val findFileByIoFile = LocalFileSystem.getInstance().findFileByIoFile(dir) ?: error("unable to locate $dir")
PlatformTestCase.copyDirContentsTo(findFileByIoFile, contentRoot())
}
}
private fun Module.contentRoot() = ModuleRootManager.getInstance(this).contentRoots.first()
private fun createScriptEnvironment(scriptFile: File): Environment {
val defaultEnvironment = defaultEnvironment(scriptFile.parent)
val env = mutableMapOf<String, Any?>()
scriptFile.forEachLine { line ->
fun iterateKeysInLine(prefix: String) {
if (line.contains(prefix)) {
line.trim().substringAfter(prefix).split(";").forEach { entry ->
val (key, values) = entry.splitOrEmpty(":").map { it.trim() }
assert(key in validKeys) { "Unexpected key: $key" }
env[key] = values.split(",").flatMap {
val str = it.trim()
defaultEnvironment[str] ?: listOf(str)
}
}
}
}
iterateKeysInLine(useDefaultTemplate)
iterateKeysInLine(templatesSettings)
switches.forEach {
if (it in line) {
env[it] = true
}
}
}
if (env[useDefaultTemplate] != true && env["template-classes-names"] == null) {
env["template-classes-names"] = listOf("custom.scriptDefinition.Template")
}
val jdkKind = when ((env["javaHome"] as? List<String>)?.singleOrNull()) {
"9" -> TestJdkKind.FULL_JDK_11 // TODO is that correct?
else -> TestJdkKind.MOCK_JDK
}
runWriteAction {
val jdk = PluginTestCaseBase.addJdk(testRootDisposable) {
PluginTestCaseBase.jdk(jdkKind)
}
env["javaHome"] = File(jdk.homePath!!)
}
env.putAll(defaultEnvironment)
return env
}
private fun defaultEnvironment(path: String): Map<String, List<File>> {
val templateOutDir = File(path, "template").takeIf { it.isDirectory }?.let {
compileLibToDir(it, getScriptingClasspath())
} ?: testDataFile("../defaultTemplate").takeIf { it.isDirectory }?.let {
compileLibToDir(it, getScriptingClasspath())
}
if (templateOutDir != null) {
System.setProperty("kotlin.script.classpath", templateOutDir.path)
} else {
LOG.warn("templateOutDir is not found")
}
val libSrcDir = File(path, "lib").takeIf { it.isDirectory }
val libClasses = libSrcDir?.let { compileLibToDir(it, emptyList()) }
var moduleSrcDir = File(path, "depModule").takeIf { it.isDirectory }
val moduleClasses = moduleSrcDir?.let { compileLibToDir(it, emptyList()) }
if (moduleSrcDir != null) {
val depModule = createTestModuleFromDir(moduleSrcDir)
moduleSrcDir = File(depModule.getModuleDir())
}
return buildMap {
put("runtime-classes", listOf(TestKotlinArtifacts.kotlinStdlib))
put("runtime-source", listOf(TestKotlinArtifacts.kotlinStdlibSources, TestKotlinArtifacts.kotlinStdlibCommonSources))
libClasses?.let { put("lib-classes", listOf(it)) }
libSrcDir?.let { put("lib-source", listOf(it)) }
moduleClasses?.let { put("module-classes", listOf(it)) }
moduleSrcDir?.let { put("module-source", listOf(it)) }
templateOutDir?.let { put("template-classes", listOf(it)) }
}
}
protected fun getScriptingClasspath(): List<File> {
return listOf(
TestKotlinArtifacts.kotlinScriptRuntime,
TestKotlinArtifacts.kotlinScriptingCommon,
TestKotlinArtifacts.kotlinScriptingJvm,
)
}
protected fun createFileAndSyncDependencies(scriptFile: File): VirtualFile {
var script: VirtualFile? = null
if (module != null) {
val contentRoot = module.contentRoot()
script = contentRoot.findChild(scriptFile.name)
}
if (script == null) {
val target = File(project.basePath, scriptFile.name)
scriptFile.copyTo(target)
script = VfsUtil.findFileByIoFile(target, true)
}
script ?: error("Test file with script couldn't be found in test project")
configureByExistingFile(script)
loadScriptConfigurationSynchronously(script)
return script
}
protected open fun loadScriptConfigurationSynchronously(script: VirtualFile) {
updateScriptDependenciesSynchronously(myFile)
// This is needed because updateScriptDependencies invalidates psiFile that was stored in myFile field
VfsUtil.markDirtyAndRefresh(false, true, true, project.baseDir)
myFile = psiManager.findFile(script)
checkHighlighting()
}
protected fun checkHighlighting(file: KtFile = myFile as KtFile) {
val reports = IdeScriptReportSink.getReports(file)
val isFatalErrorPresent = reports.any { it.severity == ScriptDiagnostic.Severity.FATAL }
assert(isFatalErrorPresent || file.shouldHighlightFile()) {
"Highlighting is switched off for ${file.virtualFile.path}\n" +
"reports=$reports\n" +
"scriptDefinition=${file.findScriptDefinition()}"
}
}
private fun compileLibToDir(srcDir: File, classpath: List<File>): File {
val outDir = KotlinTestUtils.tmpDirForReusableFolder("${getTestName(false)}${srcDir.name}Out")
KotlinCompilerStandalone(
listOf(srcDir),
target = outDir,
classpath = classpath + listOf(outDir),
compileKotlinSourcesBeforeJava = false
).compile()
return outDir
}
private fun registerScriptTemplateProvider(environment: Environment) {
val provider = if (environment[useDefaultTemplate] == true) {
FromTextTemplateProvider(environment)
} else {
CustomScriptTemplateProvider(environment)
}
addExtensionPointInTest(
ScriptDefinitionContributor.EP_NAME,
project,
provider,
testRootDisposable
)
ScriptDefinitionsManager.getInstance(project).reloadScriptDefinitions()
UIUtil.dispatchAllInvocationEvents()
}
}
| apache-2.0 | d87002f9d550f7ddde562506894190ab | 39.444444 | 129 | 0.657062 | 5.088305 | false | true | false | false |
androidx/androidx | concurrent/concurrent-futures-ktx/src/test/java/androidx/concurrent/futures/ListenableFutureTest.kt | 3 | 4756 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
package androidx.concurrent.futures
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.yield
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.CoreMatchers.instanceOf
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import kotlin.test.assertFailsWith
@RunWith(JUnit4::class)
@OptIn(DelicateCoroutinesApi::class)
class ListenableFutureTest {
private var actionIndex = AtomicInteger()
private var finished = AtomicBoolean()
@Test
fun testFutureWithResult() {
val future: ResolvableFuture<Int> = ResolvableFuture.create()
val job = GlobalScope.launch {
val result = future.await()
assertThat(result, `is`(10))
}
future.set(10)
runBlocking {
job.join()
}
}
@Test
fun testFutureWithException() {
val future: ResolvableFuture<Int> = ResolvableFuture.create()
val exception = RuntimeException("Something bad happened")
val job = GlobalScope.launch {
try {
future.await()
} catch (throwable: Throwable) {
assertThat(throwable, `is`(instanceOf(RuntimeException::class.java)))
assertThat(throwable.message, `is`(exception.message))
}
}
future.setException(exception)
runBlocking {
job.join()
}
}
@Test
fun testFutureCancellation() {
val future: ResolvableFuture<Int> = ResolvableFuture.create()
val job = GlobalScope.launch {
future.await()
}
future.cancel(true)
runBlocking {
job.join()
assertThat(job.isCancelled, `is`(true))
}
}
@Test
fun testAwaitWithCancellation() = runTest {
val future = ResolvableFuture.create<Int>()
val deferred = async {
future.await()
}
deferred.cancel(TestCancellationException())
assertFailsWith<TestCancellationException> {
deferred.await()
expectUnreached()
}
}
@Test
fun testCancellableAwait() = runBlocking {
expect(1)
val toAwait = ResolvableFuture.create<String>()
val job = launch(start = CoroutineStart.UNDISPATCHED) {
expect(2)
try {
toAwait.await() // suspends
} catch (e: CancellationException) {
expect(5) // should throw cancellation exception
throw e
}
}
expect(3)
job.cancel() // cancel the job
toAwait.set("fail") // too late, the waiting job was already cancelled
expect(4) // job processing of cancellation was scheduled, not executed yet
yield() // yield main thread to job
finish(6)
}
/**
* Asserts that this invocation is `index`-th in the execution sequence (counting from one).
*/
private fun expect(index: Int) {
val wasIndex = actionIndex.incrementAndGet()
check(index == wasIndex) { "Expecting action index $index but it is actually $wasIndex" }
}
/**
* Asserts that this it the last action in the test. It must be invoked by any test that used
* [expect].
*/
private fun finish(index: Int) {
expect(index)
check(!finished.getAndSet(true)) { "Should call 'finish(...)' at most once" }
}
/**
* Asserts that this line is never executed.
*/
private fun expectUnreached() {
error("Should not be reached")
}
private class TestCancellationException : CancellationException()
}
| apache-2.0 | 69cbb44f7160cef4aefe9e099da76914 | 30.706667 | 97 | 0.648234 | 4.760761 | false | true | false | false |
androidx/androidx | compose/foundation/foundation/integration-tests/foundation-demos/src/main/java/androidx/compose/foundation/demos/text/VariableFontsDemo.kt | 3 | 10608 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.demos.text
import android.content.Context
import android.graphics.Typeface
import android.os.Build
import android.os.ParcelFileDescriptor
import android.text.TextPaint
import androidx.annotation.RequiresApi
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.testutils.fonts.R
import androidx.compose.foundation.demos.text.FontVariationSettingsCompot.compatSetFontVariationSettings
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.Checkbox
import androidx.compose.material.Slider
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.ExperimentalTextApi
import androidx.compose.ui.text.font.DeviceFontFamilyName
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontVariation
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import java.io.File
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@OptIn(ExperimentalFoundationApi::class)
@Preview
@Composable
fun VariableFontsDemo() {
if (Build.VERSION.SDK_INT < 26) {
Text("Variable fonts are only supported on API 26+")
}
val (weight, setWeight) = remember { mutableStateOf(1000f) }
val (italic, setItalic) = remember { mutableStateOf(false) }
LazyColumn {
this.stickyHeader {
Column(Modifier.background(Color.White)) {
Slider(
value = weight,
onValueChange = setWeight,
modifier = Modifier.fillMaxWidth(),
valueRange = 1f..1000f
)
Row {
Text("Italic: ")
Checkbox(checked = italic, onCheckedChange = setItalic)
}
}
}
item {
Text("These demos show setting fontVariationSettings on a demo font that " +
"exaggerates 'wght'. Font only supports the codepoint 'A' code=\"0x41\"")
}
item {
TagLine(tag = "ResourceFont")
ResourceFont(weight.toInt(), italic)
}
item {
TagLine(tag = "AssetFont")
AssetFont(weight.toInt(), italic)
}
item {
TagLine(tag = "FileFont")
FileFont(weight.toInt(), italic)
}
if (Build.VERSION.SDK_INT >= 26) {
// PDF is 26+
item {
TagLine(tag = "ParcelFileDescriptorFont")
ParcelFileDescriptorFont(weight.toInt(), italic)
}
}
item {
TagLine(tag = "DeviceNamedFontFamily")
DeviceNamedFontFamilyFont(weight.toInt(), italic)
}
}
}
@OptIn(ExperimentalTextApi::class)
@Composable
fun AssetFont(weight: Int, italic: Boolean) {
Column(Modifier.fillMaxWidth()) {
val context = LocalContext.current
val assetFonts = remember(weight, italic) {
FontFamily(
Font(
"subdirectory/asset_variable_font.ttf",
context.assets,
variationSettings = FontVariation.Settings(
FontVariation.weight(weight.toInt()), /* Changes "A" glyph */
/* italic not supported by font, ignored */
FontVariation.italic(if (italic) 1f else 0f)
)
)
)
}
Text(
"A",
fontSize = 48.sp,
fontFamily = assetFonts,
modifier = Modifier.align(Alignment.CenterHorizontally)
)
}
}
@OptIn(ExperimentalTextApi::class)
@Composable
fun FileFont(weight: Int, italic: Boolean) {
val context = LocalContext.current
val filePath = remember { mutableStateOf<String?> (null) }
LaunchedEffect(Unit) {
filePath.value = mkTempFont(context).path
}
val actualPath = filePath.value ?: return
Column(Modifier.fillMaxWidth()) {
val fileFonts = remember(weight, italic) {
FontFamily(
Font(
File(actualPath),
variationSettings = FontVariation.Settings(
FontVariation.weight(weight.toInt()), /* Changes "A" glyph */
/* italic not supported by font, ignored */
FontVariation.italic(if (italic) 1f else 0f)
)
)
)
}
Text(
"A",
fontSize = 48.sp,
fontFamily = fileFonts,
modifier = Modifier.align(Alignment.CenterHorizontally)
)
}
}
@OptIn(ExperimentalTextApi::class)
@Composable
@RequiresApi(26)
fun ParcelFileDescriptorFont(weight: Int, italic: Boolean) {
val context = LocalContext.current
val filePath = remember { mutableStateOf<String?> (null) }
LaunchedEffect(Unit) {
filePath.value = mkTempFont(context).path
}
val actualPath = filePath.value ?: return
Column(Modifier.fillMaxWidth()) {
val parcelFonts = remember(weight, italic) {
FontFamily(
Font(
File(actualPath).toParcelFileDescriptor(context),
variationSettings = FontVariation.Settings(
FontVariation.weight(weight.toInt()), /* Changes "A" glyph */
/* italic not supported by font, ignored */
FontVariation.italic(if (italic) 1f else 0f)
)
)
)
}
Text(
"A",
fontSize = 48.sp,
fontFamily = parcelFonts,
modifier = Modifier.align(Alignment.CenterHorizontally)
)
}
}
@OptIn(ExperimentalTextApi::class)
@Composable
fun DeviceNamedFontFamilyFont(weight: Int, italic: Boolean) {
Column(Modifier.fillMaxWidth()) {
val deviceFonts = remember(weight, italic) {
FontFamily(
Font(
DeviceFontFamilyName("sans-serif"),
variationSettings = FontVariation.Settings(
FontVariation.weight(weight.toInt()), /* Changes "A" glyph */
/* italic not supported by font, ignored */
FontVariation.italic(if (italic) 1f else 0f)
)
)
)
}
Text(
"Setting variation on system fonts has no effect on (most) Android builds",
fontSize = 12.sp,
fontFamily = deviceFonts,
modifier = Modifier.align(Alignment.CenterHorizontally)
)
val textPaint = remember { TextPaint() }
Canvas(modifier = Modifier
.fillMaxWidth()
.height(40.dp)) {
this.drawIntoCanvas {
val nativeCanvas = drawContext.canvas.nativeCanvas
textPaint.typeface = Typeface.create("sans-serif", Typeface.NORMAL)
textPaint.textSize = 24f
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
textPaint.compatSetFontVariationSettings(
"'wght' $weight, 'ital' ${if (italic) 1f else 0f}"
)
}
nativeCanvas.drawText(
"Platform 'sans-serif' behavior on this device' (nativeCanvas)" /* text */,
0f /* x */,
40f /* y */,
textPaint)
}
}
}
}
@OptIn(ExperimentalTextApi::class)
@Composable
fun ResourceFont(weight: Int, italic: Boolean) {
Column(Modifier.fillMaxWidth()) {
val resourceFonts = remember(weight, italic) {
FontFamily(
Font(
R.font.variable_font,
variationSettings = FontVariation.Settings(
FontVariation.weight(weight.toInt()), /* Changes "A" glyph */
/* italic not supported by font, ignored */
FontVariation.italic(if (italic) 1f else 0f)
)
)
)
}
Text(
"A",
fontSize = 48.sp,
fontFamily = resourceFonts,
modifier = Modifier.align(Alignment.CenterHorizontally)
)
}
}
private suspend fun mkTempFont(context: Context): File = withContext(Dispatchers.IO) {
val temp = File.createTempFile("tmp", ".ttf", context.filesDir)
context.assets.open("subdirectory/asset_variable_font.ttf").use { input ->
val bytes = input.readBytes()
context.openFileOutput(temp.name, Context.MODE_PRIVATE).use { output ->
output.write(bytes)
}
}
temp
}
private fun File.toParcelFileDescriptor(context: Context): ParcelFileDescriptor {
context.openFileInput(name).use { input ->
return ParcelFileDescriptor.dup(input.fd)
}
}
@RequiresApi(26)
object FontVariationSettingsCompot {
fun TextPaint.compatSetFontVariationSettings(variationSettings: String) {
fontVariationSettings = variationSettings
}
} | apache-2.0 | 4fac15798d434a608c2ef65e7570ddf0 | 34.481605 | 104 | 0.601998 | 4.821818 | false | false | false | false |
pokk/SSFM | app/src/main/kotlin/taiwan/no1/app/ssfm/features/search/SearchActivity.kt | 1 | 9462 | package taiwan.no1.app.ssfm.features.search
import android.app.Fragment
import android.os.Bundle
import android.support.design.widget.BottomSheetBehavior
import android.util.SparseArray
import android.view.View
import com.devrapid.dialogbuilder.QuickDialogBindingFragment
import com.devrapid.kotlinknifer.WeakRef
import com.devrapid.kotlinknifer.addFragment
import com.hwangjr.rxbus.RxBus
import com.hwangjr.rxbus.annotation.Subscribe
import com.hwangjr.rxbus.annotation.Tag
import com.tbruyelle.rxpermissions2.RxPermissions
import kotlinx.android.synthetic.main.bottomsheet_track.rl_bottom_sheet
import taiwan.no1.app.ssfm.R
import taiwan.no1.app.ssfm.databinding.ActivitySearchBinding
import taiwan.no1.app.ssfm.databinding.FragmentDialogPlaylistBinding
import taiwan.no1.app.ssfm.features.base.AdvancedActivity
import taiwan.no1.app.ssfm.features.bottomsheet.BottomSheetViewModel
import taiwan.no1.app.ssfm.features.bottomsheet.quickDialogBindingFragment
import taiwan.no1.app.ssfm.misc.constants.Constant.CALLBACK_SPARSE_INDEX_FOG_COLOR
import taiwan.no1.app.ssfm.misc.constants.Constant.CALLBACK_SPARSE_INDEX_IMAGE_URL
import taiwan.no1.app.ssfm.misc.constants.Constant.CALLBACK_SPARSE_INDEX_KEYWORD
import taiwan.no1.app.ssfm.misc.constants.RxBusTag.FRAGMENT_SEARCH_HISTORY
import taiwan.no1.app.ssfm.misc.constants.RxBusTag.FRAGMENT_SEARCH_INDEX
import taiwan.no1.app.ssfm.misc.constants.RxBusTag.FRAGMENT_SEARCH_RESULT
import taiwan.no1.app.ssfm.misc.constants.RxBusTag.VIEWMODEL_CLICK_PLAYLIST_FRAGMENT_DIALOG
import taiwan.no1.app.ssfm.misc.constants.RxBusTag.VIEWMODEL_DISMISS_PLAYLIST_FRAGMENT_DIALOG
import taiwan.no1.app.ssfm.misc.constants.RxBusTag.VIEWMODEL_TRACK_LONG_CLICK
import taiwan.no1.app.ssfm.misc.extension.recyclerview.DataInfo
import taiwan.no1.app.ssfm.models.entities.lastfm.BaseEntity
import taiwan.no1.app.ssfm.models.usecases.AddPlaylistItemCase
import taiwan.no1.app.ssfm.models.usecases.FetchPlaylistCase
import java.util.Stack
import javax.inject.Inject
import javax.inject.Named
/**
* @author jieyi
* @since 9/16/17
*/
class SearchActivity : AdvancedActivity<SearchViewModel, ActivitySearchBinding>() {
@Inject override lateinit var viewModel: SearchViewModel
@Inject lateinit var addPlaylistItemCase: AddPlaylistItemCase
@field:[Inject Named("activity_playlist_usecase")] lateinit var fetchPlaylistCase: FetchPlaylistCase
/** For judging a fragment should be pushed or popped. */
private val fragmentStack by lazy { Stack<Fragment>() }
private val playlistInfo by lazy { DataInfo() }
private val permissions by lazy { RxPermissions(this) }
private var playlistRes = mutableListOf<BaseEntity>()
private var track by WeakRef<BaseEntity>()
private lateinit var dialogFragment: QuickDialogBindingFragment<FragmentDialogPlaylistBinding>
//region Activity lifecycle
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
RxBus.get().register(this)
binding.bottomSheetVm =
BottomSheetViewModel(
this,
permissions,
BottomSheetBehavior.from(rl_bottom_sheet).apply {
state = BottomSheetBehavior.STATE_HIDDEN
} as BottomSheetBehavior<View>,
addPlaylistItemCase)
addFragmentAndToStack(SearchIndexFragment.newInstance())
viewModel.apply {
navigateListener = { fragmentTag, params ->
params?.let { navigate(fragmentTag, params) } ?: navigate(fragmentTag)
}
popFragment = { toFragmentTag -> [email protected](toFragmentTag) }
}
}
override fun onStop() {
super.onStop()
dismissPlaylistDialog("")
}
override fun onDestroy() {
RxBus.get().unregister(this)
super.onDestroy()
binding.bottomSheetVm = null
}
//endregion
//region Base activity implement
override fun provideBindingLayoutId() = this to R.layout.activity_search
//endregion
override fun onBackPressed() {
if (BottomSheetBehavior.STATE_EXPANDED == BottomSheetBehavior.from(rl_bottom_sheet).state) {
BottomSheetBehavior.from(rl_bottom_sheet).state = BottomSheetBehavior.STATE_HIDDEN
return
}
super.onBackPressed()
when (fragmentStack.safePeek()) {
is SearchHistoryFragment -> viewModel.collapseSearchView()
// OPTIMIZE(jieyi): 10/4/17 Just workaround. Clear the focus, only from result view to history view.
is SearchResultFragment -> binding.includeToolbar?.svMusicSearch?.clearFocus()
}
fragmentStack.safePop()
}
private fun navigate(fragmentTag: String, params: SparseArray<Any> = SparseArray()) {
runNewFragment(fragmentTag, params).let { targetFragment ->
if (isSpecificTargetAction(fragmentTag) || fragmentStack.safePeek() is SearchResultFragment) {
if (popFragmentAndFromStack(FRAGMENT_SEARCH_HISTORY))
return@let
}
addFragmentAndToStack(targetFragment, true)
}
}
/**
* Check the specific fragment. The following of the specific fragment are
* 1. When search some tracks in the [SearchHistoryFragment], we don't want to add a same fragment
* again and again.
*
* @param fragmentTag the tag of a fragment.
* @return [true] if the fragment is a specific fragment; otherwise [false].
*/
private fun isSpecificTargetAction(fragmentTag: String): Boolean =
FRAGMENT_SEARCH_HISTORY == fragmentTag && (fragmentStack.safePeek() is SearchHistoryFragment || fragmentStack.safePeek() is SearchResultFragment)
/**
* According to the [tag] to adding a new [Fragment] with the parameters.
*
* @param tag the tag of a fragment.
* @param params the parameters for the new fragment.
*/
private fun runNewFragment(tag: String, params: SparseArray<Any>) = when (tag) {
FRAGMENT_SEARCH_RESULT -> {
val keyword = params[CALLBACK_SPARSE_INDEX_KEYWORD] as String
val imageUrl = params[CALLBACK_SPARSE_INDEX_IMAGE_URL] as String
val fgFogColor = params[CALLBACK_SPARSE_INDEX_FOG_COLOR] as Int
SearchResultFragment.newInstance(keyword, imageUrl, fgFogColor)
}
FRAGMENT_SEARCH_HISTORY -> SearchHistoryFragment.newInstance()
FRAGMENT_SEARCH_INDEX -> SearchIndexFragment.newInstance()
else -> error("There's no kind of the fragment tag.")
}
/**
* Add a fragment to the [getFragmentManager] and [fragmentStack].
*
* @param fragment [Fragment]
* @param needBack when the use clicks the return button, the page will transfer to the previous one.
*/
private fun addFragmentAndToStack(fragment: Fragment, needBack: Boolean = false) {
fragmentManager.addFragment(R.id.fl_container, fragment, needBack)
fragmentStack.push(fragment)
}
private fun popFragmentAndFromStack(toFragmentTag: String): Boolean {
// For staying the same history fragment.
if (FRAGMENT_SEARCH_HISTORY == toFragmentTag && fragmentStack.safePeek() is SearchHistoryFragment)
return true
// This is very special case for clicking a artist or a track from the search index fragment.
// OPTIMIZE(jieyi): 10/18/17 Here may modified better!?
if (FRAGMENT_SEARCH_HISTORY == toFragmentTag && fragmentStack.safePeek() is SearchResultFragment) {
fragmentManager.popBackStackImmediate()
fragmentStack.safePop()
return false
}
fragmentManager.popBackStackImmediate()
fragmentStack.safePop()
return true
}
/**
* @param entity
*
* @event_from [taiwan.no1.app.ssfm.features.search.RecyclerViewSearchMusicResultViewModel.optionClick]
*/
@Subscribe(tags = [Tag(VIEWMODEL_TRACK_LONG_CLICK)])
fun openBottomSheet(entity: Any) {
(entity as BaseEntity).let { binding.bottomSheetVm?.run { obtainMusicEntity = it } }
BottomSheetBehavior.from(rl_bottom_sheet).state = BottomSheetBehavior.STATE_EXPANDED
}
/**
* @param entity
*
* @event_from [taiwan.no1.app.ssfm.features.bottomsheet.BottomSheetViewModel.debounceOpenDialog]
*/
@Subscribe(tags = [Tag(VIEWMODEL_CLICK_PLAYLIST_FRAGMENT_DIALOG)])
fun openPlaylistDialog(entity: Any) {
playlistRes.clear()
dialogFragment = [email protected](entity,
playlistRes,
playlistInfo,
fetchPlaylistCase,
addPlaylistItemCase)
}
/**
* @param any
*
* @event_from [taiwan.no1.app.ssfm.features.bottomsheet.RecyclerViewDialogPlaylistViewModel.debounceAddToPlaylist]
*/
@Subscribe(tags = [Tag(VIEWMODEL_DISMISS_PLAYLIST_FRAGMENT_DIALOG)])
fun dismissPlaylistDialog(any: Any) {
if (::dialogFragment.isInitialized) dialogFragment.dismiss()
}
private fun <E> Stack<E>.safePop() = lastOrNull()?.let { pop() }
private fun <E> Stack<E>.safePeek() = lastOrNull()?.let { peek() }
} | apache-2.0 | dec4fda40ea9ecd02eae215ad1352516 | 43.42723 | 153 | 0.689601 | 4.60214 | false | false | false | false |
androidx/androidx | graphics/graphics-core/src/main/java/androidx/graphics/surface/SurfaceControlV33.kt | 3 | 9151 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.graphics.surface
import android.graphics.Rect
import android.graphics.Region
import android.hardware.HardwareBuffer
import android.hardware.SyncFence
import android.os.Build
import android.view.AttachedSurfaceControl
import android.view.SurfaceControl
import android.view.SurfaceView
import androidx.annotation.RequiresApi
import androidx.graphics.lowlatency.SyncFenceImpl
import androidx.graphics.lowlatency.SyncFenceV33
import java.util.concurrent.Executor
/**
* Implementation of [SurfaceControlImpl] that wraps the SDK's [SurfaceControl] API.
*/
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
internal class SurfaceControlV33 internal constructor(
internal val surfaceControl: SurfaceControl
) : SurfaceControlImpl {
/**
* See [SurfaceControlImpl.isValid]
*/
override fun isValid(): Boolean = surfaceControl.isValid
/**
* See [SurfaceControlImpl.release]
*/
override fun release() {
surfaceControl.release()
}
/**
* See [SurfaceControlImpl.Builder]
*/
class Builder : SurfaceControlImpl.Builder {
private val builder = SurfaceControl.Builder()
/**
* See [SurfaceControlImpl.Builder.setParent]
*/
override fun setParent(surfaceView: SurfaceView): SurfaceControlImpl.Builder {
builder.setParent(surfaceView.surfaceControl)
return this
}
/**
* See [SurfaceControlImpl.Builder.setName]
*/
override fun setName(name: String): Builder {
builder.setName(name)
return this
}
/**
* See [SurfaceControlImpl.Builder.build]
*/
override fun build(): SurfaceControlImpl = SurfaceControlV33(builder.build())
}
/**
* See [SurfaceControlImpl.Transaction]
*/
class Transaction : SurfaceControlImpl.Transaction {
private val mTransaction = SurfaceControl.Transaction()
/**
* See [SurfaceControlImpl.Transaction.setOpaque]
*/
override fun setOpaque(
surfaceControl: SurfaceControlImpl,
isOpaque: Boolean
): SurfaceControlImpl.Transaction {
mTransaction.setOpaque(surfaceControl.asFrameworkSurfaceControl(), isOpaque)
return this
}
/**
* See [SurfaceControlImpl.Transaction.setVisibility]
*/
override fun setVisibility(
surfaceControl: SurfaceControlImpl,
visible: Boolean
): SurfaceControlImpl.Transaction {
mTransaction.setVisibility(surfaceControl.asFrameworkSurfaceControl(), visible)
return this
}
/**
* See [SurfaceControlImpl.Transaction.setBuffer]
*/
override fun setBuffer(
surfaceControl: SurfaceControlImpl,
buffer: HardwareBuffer,
fence: SyncFenceImpl?,
releaseCallback: (() -> Unit)?
): Transaction {
mTransaction.setBuffer(
surfaceControl.asFrameworkSurfaceControl(),
buffer,
fence?.asSyncFence()
) {
releaseCallback?.invoke()
}
return this
}
/**
* See [SurfaceControlImpl.Transaction.setLayer]
*/
override fun setLayer(
surfaceControl: SurfaceControlImpl,
z: Int
): SurfaceControlImpl.Transaction {
mTransaction.setLayer(surfaceControl.asFrameworkSurfaceControl(), z)
return this
}
/**
* See [SurfaceControlImpl.Transaction.reparent]
*/
override fun reparent(
surfaceControl: SurfaceControlImpl,
newParent: SurfaceControlImpl?
): Transaction {
mTransaction.reparent(
surfaceControl.asFrameworkSurfaceControl(),
newParent?.asFrameworkSurfaceControl()
)
return this
}
/**
* See [SurfaceControlImpl.Transaction.reparent]
*/
override fun reparent(
surfaceControl: SurfaceControlImpl,
attachedSurfaceControl: AttachedSurfaceControl
): SurfaceControlImpl.Transaction {
val reparentTransaction = attachedSurfaceControl
.buildReparentTransaction(surfaceControl.asFrameworkSurfaceControl())
if (reparentTransaction != null) {
mTransaction.merge(reparentTransaction)
}
return this
}
/**
* See [SurfaceControlImpl.Transaction.addTransactionCommittedListener]
*/
override fun addTransactionCommittedListener(
executor: Executor,
listener: SurfaceControlCompat.TransactionCommittedListener
): SurfaceControlImpl.Transaction {
mTransaction.addTransactionCommittedListener(executor) {
listener.onTransactionCommitted()
}
return this
}
/**
* See [SurfaceControlImpl.Transaction.setDamageRegion]
*/
override fun setDamageRegion(
surfaceControl: SurfaceControlImpl,
region: Region?
): SurfaceControlImpl.Transaction {
mTransaction.setDamageRegion(surfaceControl.asFrameworkSurfaceControl(), region)
return this
}
/**
* See [SurfaceControlImpl.Transaction.setAlpha]
*/
override fun setAlpha(
surfaceControl: SurfaceControlImpl,
alpha: Float
): SurfaceControlImpl.Transaction {
mTransaction.setAlpha(surfaceControl.asFrameworkSurfaceControl(), alpha)
return this
}
/**
* See [SurfaceControlImpl.Transaction.setCrop]
*/
override fun setCrop(
surfaceControl: SurfaceControlImpl,
crop: Rect?
): SurfaceControlImpl.Transaction {
mTransaction.setCrop(surfaceControl.asFrameworkSurfaceControl(), crop)
return this
}
/**
* See [SurfaceControlImpl.Transaction.setPosition]
*/
override fun setPosition(
surfaceControl: SurfaceControlImpl,
x: Float,
y: Float
): SurfaceControlImpl.Transaction {
mTransaction.setPosition(surfaceControl.asFrameworkSurfaceControl(), x, y)
return this
}
/**
* See [SurfaceControlImpl.Transaction.setScale]
*/
override fun setScale(
surfaceControl: SurfaceControlImpl,
scaleX: Float,
scaleY: Float
): SurfaceControlImpl.Transaction {
mTransaction.setScale(surfaceControl.asFrameworkSurfaceControl(), scaleX, scaleY)
return this
}
/**
* See [SurfaceControlImpl.Transaction.setBufferTransform]
*/
override fun setBufferTransform(
surfaceControl: SurfaceControlImpl,
@SurfaceControlCompat.Companion.BufferTransform transformation: Int
): SurfaceControlImpl.Transaction {
mTransaction.setBufferTransform(
surfaceControl.asFrameworkSurfaceControl(),
transformation
)
return this
}
/**
* See [SurfaceControlImpl.Transaction.commit]
*/
override fun commit() {
mTransaction.apply()
}
/**
* See [SurfaceControlImpl.Transaction.close]
*/
override fun close() {
mTransaction.close()
}
/**
* See [SurfaceControlImpl.Transaction.commitTransactionOnDraw]
*/
override fun commitTransactionOnDraw(attachedSurfaceControl: AttachedSurfaceControl) {
attachedSurfaceControl.applyTransactionOnDraw(mTransaction)
}
private fun SurfaceControlImpl.asFrameworkSurfaceControl(): SurfaceControl =
if (this is SurfaceControlV33) {
surfaceControl
} else {
throw IllegalArgumentException("Parent implementation is not for Android T")
}
private fun SyncFenceImpl.asSyncFence(): SyncFence =
if (this is SyncFenceV33) {
mSyncFence
} else {
throw
IllegalArgumentException("Expected SyncFenceCompat implementation for API level 33")
}
}
} | apache-2.0 | caa25f8c57e0f1109719153bdb66cdaa | 30.66782 | 100 | 0.612283 | 5.370305 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/plugins/projectTemplates/ProjectTemplatesPlugin.kt | 4 | 2247 | // 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.tools.projectWizard.plugins.projectTemplates
import org.jetbrains.kotlin.tools.projectWizard.KotlinNewProjectWizardBundle
import org.jetbrains.kotlin.tools.projectWizard.core.*
import org.jetbrains.kotlin.tools.projectWizard.core.entity.PipelineTask
import org.jetbrains.kotlin.tools.projectWizard.core.entity.properties.Property
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.PluginSetting
import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.KotlinPlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.withAllSubModules
import org.jetbrains.kotlin.tools.projectWizard.projectTemplates.ProjectTemplate
class ProjectTemplatesPlugin(context: Context) : Plugin(context) {
override val path = pluginPath
companion object : PluginSettingsOwner() {
override val pluginPath = "projectTemplates"
val template by dropDownSetting<ProjectTemplate>(
KotlinNewProjectWizardBundle.message("plugin.templates.setting.template"),
GenerationPhase.INIT_TEMPLATE,
parser = valueParserM { _, _ ->
Failure(ParseError(KotlinNewProjectWizardBundle.message("error.text.project.templates.is.not.supported.in.yaml.for.now")))
},
) {
values = ProjectTemplate.ALL
isRequired = false
tooltipText = KotlinNewProjectWizardBundle.message("plugin.templates.setting.template.tooltip")
}
}
override val settings: List<PluginSetting<*, *>> = listOf(template)
override val pipelineTasks: List<PipelineTask> = listOf()
override val properties: List<Property<*>> = listOf()
}
fun SettingsWriter.applyProjectTemplate(projectTemplate: ProjectTemplate) {
projectTemplate.setsValues.forEach { (setting, value) ->
setting.setValue(value)
}
KotlinPlugin.modules.settingValue.withAllSubModules(includeSourcesets = true).forEach { module ->
module.apply { initDefaultValuesForSettings() }
}
} | apache-2.0 | 5b34b3cb29dd90eab449072be2119d63 | 47.869565 | 158 | 0.757454 | 4.916849 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/core/breakpoints/KotlinFieldBreakpoint.kt | 1 | 13900 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.debugger.core.breakpoints
import com.intellij.debugger.DebuggerManagerEx
import com.intellij.debugger.JavaDebuggerBundle
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl
import com.intellij.debugger.impl.PositionUtil
import com.intellij.debugger.requests.Requestor
import com.intellij.debugger.ui.breakpoints.BreakpointCategory
import com.intellij.debugger.ui.breakpoints.BreakpointWithHighlighter
import com.intellij.debugger.ui.breakpoints.FieldBreakpoint
import com.intellij.icons.AllIcons
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.xdebugger.breakpoints.XBreakpoint
import com.sun.jdi.AbsentInformationException
import com.sun.jdi.Method
import com.sun.jdi.ReferenceType
import com.sun.jdi.event.*
import com.sun.jdi.request.EventRequest
import com.sun.jdi.request.MethodEntryRequest
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.analysis.api.analyze
import org.jetbrains.kotlin.analysis.api.symbols.KtKotlinPropertySymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtValueParameterSymbol
import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil
import org.jetbrains.kotlin.idea.debugger.base.util.safeAllLineLocations
import com.intellij.openapi.application.runReadAction
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.psi.*
import javax.swing.Icon
class KotlinFieldBreakpoint(
project: Project,
breakpoint: XBreakpoint<KotlinPropertyBreakpointProperties>
) : BreakpointWithHighlighter<KotlinPropertyBreakpointProperties>(project, breakpoint) {
companion object {
private val LOG = Logger.getInstance(KotlinFieldBreakpoint::class.java)
private val CATEGORY: Key<FieldBreakpoint> = BreakpointCategory.lookup("field_breakpoints")
}
private enum class BreakpointType {
FIELD,
METHOD
}
private var breakpointType: BreakpointType = BreakpointType.FIELD
override fun isValid(): Boolean {
return super.isValid() && evaluationElement != null
}
override fun reload() {
super.reload()
val callable = evaluationElement ?: return
val callableName = callable.name ?: return
setFieldName(callableName)
if (callable is KtProperty && callable.isTopLevel) {
properties.myClassName = JvmFileClassUtil.getFileClassInfoNoResolve(callable.getContainingKtFile()).fileClassFqName.asString()
} else {
val ktClass: KtClassOrObject? = PsiTreeUtil.getParentOfType(callable, KtClassOrObject::class.java)
if (ktClass is KtClassOrObject) {
val fqName = ktClass.fqName
if (fqName != null) {
properties.myClassName = fqName.asString()
}
}
}
isInstanceFiltersEnabled = false
}
override fun createRequestForPreparedClass(debugProcess: DebugProcessImpl?, refType: ReferenceType?) {
if (debugProcess == null || refType == null) return
breakpointType = evaluationElement?.let(::computeBreakpointType) ?: return
val vm = debugProcess.virtualMachineProxy
try {
if (properties.watchInitialization) {
val sourcePosition = sourcePosition
if (sourcePosition != null) {
debugProcess.positionManager
.locationsOfLine(refType, sourcePosition)
.filter { it.method().isConstructor || it.method().isStaticInitializer }
.forEach {
val request = debugProcess.requestsManager.createBreakpointRequest(this, it)
debugProcess.requestsManager.enableRequest(request)
if (LOG.isDebugEnabled) {
LOG.debug("Breakpoint request added")
}
}
}
}
when (breakpointType) {
BreakpointType.FIELD -> {
val field = refType.fieldByName(getFieldName())
if (field != null) {
val manager = debugProcess.requestsManager
if (properties.watchModification && vm.canWatchFieldModification()) {
val request = manager.createModificationWatchpointRequest(this, field)
debugProcess.requestsManager.enableRequest(request)
if (LOG.isDebugEnabled) {
LOG.debug("Modification request added")
}
}
if (properties.watchAccess && vm.canWatchFieldAccess()) {
val request = manager.createAccessWatchpointRequest(this, field)
debugProcess.requestsManager.enableRequest(request)
if (LOG.isDebugEnabled) {
LOG.debug("Field access request added (field = ${field.name()}; refType = ${refType.name()})")
}
}
}
}
BreakpointType.METHOD -> {
val fieldName = getFieldName()
if (properties.watchAccess) {
val getter = refType.methodsByName(JvmAbi.getterName(fieldName)).firstOrNull()
if (getter != null) {
createMethodBreakpoint(debugProcess, refType, getter)
}
}
if (properties.watchModification) {
val setter = refType.methodsByName(JvmAbi.setterName(fieldName)).firstOrNull()
if (setter != null) {
createMethodBreakpoint(debugProcess, refType, setter)
}
}
}
}
} catch (ex: Exception) {
LOG.debug(ex)
}
}
private fun computeBreakpointType(property: KtCallableDeclaration): BreakpointType {
return runReadAction {
analyze(property) {
val hasBackingField = when (val symbol = property.getSymbol()) {
is KtValueParameterSymbol -> symbol.generatedPrimaryConstructorProperty?.hasBackingField ?: false
is KtKotlinPropertySymbol -> symbol.hasBackingField
else -> false
}
if (hasBackingField) BreakpointType.FIELD else BreakpointType.METHOD
}
}
}
private fun createMethodBreakpoint(debugProcess: DebugProcessImpl, refType: ReferenceType, accessor: Method) {
val manager = debugProcess.requestsManager
val line = accessor.safeAllLineLocations().firstOrNull()
if (line != null) {
val request = manager.createBreakpointRequest(this, line)
debugProcess.requestsManager.enableRequest(request)
if (LOG.isDebugEnabled) {
LOG.debug("Breakpoint request added")
}
} else {
var entryRequest: MethodEntryRequest? = findRequest(debugProcess, MethodEntryRequest::class.java, this)
if (entryRequest == null) {
entryRequest = manager.createMethodEntryRequest(this)!!
if (LOG.isDebugEnabled) {
LOG.debug("Method entry request added (method = ${accessor.name()}; refType = ${refType.name()})")
}
} else {
entryRequest.disable()
}
entryRequest.addClassFilter(refType)
manager.enableRequest(entryRequest)
}
}
private inline fun <reified T : EventRequest> findRequest(
debugProcess: DebugProcessImpl,
requestClass: Class<T>,
requestor: Requestor
): T? {
val requests = debugProcess.requestsManager.findRequests(requestor)
for (eventRequest in requests) {
if (eventRequest::class.java == requestClass) {
return eventRequest as T
}
}
return null
}
override fun evaluateCondition(context: EvaluationContextImpl, event: LocatableEvent): Boolean {
if (breakpointType == BreakpointType.METHOD && !matchesEvent(event)) {
return false
}
return super.evaluateCondition(context, event)
}
private fun matchesEvent(event: LocatableEvent): Boolean {
val method = event.location()?.method()
// TODO check property type
return method != null && method.name() in getMethodsName()
}
private fun getMethodsName(): List<String> {
val fieldName = getFieldName()
return listOf(JvmAbi.getterName(fieldName), JvmAbi.setterName(fieldName))
}
override fun getEventMessage(event: LocatableEvent): String {
val location = event.location()!!
val locationQName = location.declaringType().name() + "." + location.method().name()
val locationFileName = try {
location.sourceName()
} catch (e: AbsentInformationException) {
fileName
} catch (e: InternalError) {
fileName
}
val locationLine = location.lineNumber()
when (event) {
is ModificationWatchpointEvent -> {
val field = event.field()
return JavaDebuggerBundle.message(
"status.static.field.watchpoint.reached.access",
field.declaringType().name(),
field.name(),
locationQName,
locationFileName,
locationLine
)
}
is AccessWatchpointEvent -> {
val field = event.field()
return JavaDebuggerBundle.message(
"status.static.field.watchpoint.reached.access",
field.declaringType().name(),
field.name(),
locationQName,
locationFileName,
locationLine
)
}
is MethodEntryEvent -> {
val method = event.method()
return JavaDebuggerBundle.message(
"status.method.entry.breakpoint.reached",
method.declaringType().name() + "." + method.name() + "()",
locationQName,
locationFileName,
locationLine
)
}
is MethodExitEvent -> {
val method = event.method()
return JavaDebuggerBundle.message(
"status.method.exit.breakpoint.reached",
method.declaringType().name() + "." + method.name() + "()",
locationQName,
locationFileName,
locationLine
)
}
}
return JavaDebuggerBundle.message(
"status.line.breakpoint.reached",
locationQName,
locationFileName,
locationLine
)
}
fun setFieldName(fieldName: String) {
properties.myFieldName = fieldName
}
@TestOnly
fun setWatchAccess(value: Boolean) {
properties.watchAccess = value
}
@TestOnly
fun setWatchModification(value: Boolean) {
properties.watchModification = value
}
@TestOnly
fun setWatchInitialization(value: Boolean) {
properties.watchInitialization = value
}
override fun getDisabledIcon(isMuted: Boolean): Icon {
val master = DebuggerManagerEx.getInstanceEx(myProject).breakpointManager.findMasterBreakpoint(this)
return when {
isMuted && master == null -> AllIcons.Debugger.Db_muted_disabled_field_breakpoint
isMuted && master != null -> AllIcons.Debugger.Db_muted_dep_field_breakpoint
master != null -> AllIcons.Debugger.Db_dep_field_breakpoint
else -> AllIcons.Debugger.Db_disabled_field_breakpoint
}
}
override fun getSetIcon(isMuted: Boolean): Icon {
return when {
isMuted -> AllIcons.Debugger.Db_muted_field_breakpoint
else -> AllIcons.Debugger.Db_field_breakpoint
}
}
override fun getVerifiedIcon(isMuted: Boolean): Icon {
return when {
isMuted -> AllIcons.Debugger.Db_muted_field_breakpoint
else -> AllIcons.Debugger.Db_verified_field_breakpoint
}
}
override fun getVerifiedWarningsIcon(isMuted: Boolean): Icon = AllIcons.Debugger.Db_exception_breakpoint
override fun getCategory() = CATEGORY
override fun getDisplayName(): String {
if (!isValid) {
return JavaDebuggerBundle.message("status.breakpoint.invalid")
}
val className = className
@Suppress("HardCodedStringLiteral")
return if (!className.isNullOrEmpty()) className + "." + getFieldName() else getFieldName()
}
private fun getFieldName(): String {
return runReadAction {
evaluationElement?.name ?: "unknown"
}
}
override fun getEvaluationElement(): KtCallableDeclaration? {
return when (val callable = PositionUtil.getPsiElementAt(project, KtValVarKeywordOwner::class.java, sourcePosition)) {
is KtProperty -> callable
is KtParameter -> callable
else -> null
}
}
}
| apache-2.0 | f31ff2212af3d4e996fd9fbdc479a23f | 38.942529 | 138 | 0.596475 | 5.645816 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/kpm/KotlinKPMGradleProjectResolver.kt | 1 | 11930 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.gradleJava.configuration.kpm
import com.intellij.build.events.MessageEvent
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.project.*
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.externalSystem.util.ExternalSystemConstants
import com.intellij.openapi.externalSystem.util.Order
import com.intellij.openapi.roots.DependencyScope
import com.intellij.util.PlatformUtils
import org.gradle.tooling.model.idea.IdeaModule
import org.jetbrains.kotlin.gradle.kpm.idea.*
import org.jetbrains.kotlin.base.util.KotlinPlatformUtils
import org.jetbrains.kotlin.idea.configuration.multiplatform.KotlinMultiplatformNativeDebugSuggester
import org.jetbrains.kotlin.idea.gradle.configuration.ResolveModulesPerSourceSetInMppBuildIssue
import org.jetbrains.kotlin.idea.gradle.configuration.buildClasspathData
import org.jetbrains.kotlin.idea.gradle.configuration.findChildModuleById
import org.jetbrains.kotlin.idea.gradle.configuration.kpm.ContentRootsCreator
import org.jetbrains.kotlin.idea.gradle.configuration.kpm.ModuleDataInitializer
import org.jetbrains.kotlin.idea.gradle.ui.notifyLegacyIsResolveModulePerSourceSetSettingIfNeeded
import org.jetbrains.kotlin.idea.gradleTooling.*
import org.jetbrains.kotlin.idea.roots.findAll
import org.jetbrains.plugins.gradle.model.ProjectImportModelProvider
import org.jetbrains.plugins.gradle.model.data.BuildScriptClasspathData
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
import org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension
import org.jetbrains.plugins.gradle.service.project.ProjectResolverContext
import org.jetbrains.plugins.gradle.util.GradleConstants
import java.io.File
@Order(ExternalSystemConstants.UNORDERED + 1)
open class KotlinKPMGradleProjectResolver : AbstractProjectResolverExtension() {
override fun getExtraProjectModelClasses(): Set<Class<out Any>> =
throw UnsupportedOperationException("Use getModelProvider() instead!")
override fun getModelProvider(): ProjectImportModelProvider? = IdeaKotlinProjectModelProvider
override fun getToolingExtensionsClasses(): Set<Class<out Any>> = setOf(
IdeaKotlinProjectModel::class.java, Unit::class.java
)
override fun populateModuleExtraModels(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) {
if (ExternalSystemApiUtil.find(ideModule, BuildScriptClasspathData.KEY) == null) {
val buildScriptClasspathData = buildClasspathData(gradleModule, resolverCtx)
ideModule.createChild(BuildScriptClasspathData.KEY, buildScriptClasspathData)
}
super.populateModuleExtraModels(gradleModule, ideModule)
}
override fun createModule(gradleModule: IdeaModule, projectDataNode: DataNode<ProjectData>): DataNode<ModuleData>? {
return super.createModule(gradleModule, projectDataNode)?.also { mainModuleNode ->
val initializerContext = ModuleDataInitializer.Context.EMPTY
ModuleDataInitializer.EP_NAME.extensions.forEach { moduleDataInitializer ->
moduleDataInitializer.initialize(gradleModule, mainModuleNode, projectDataNode, resolverCtx, initializerContext)
}
suggestNativeDebug(gradleModule, resolverCtx)
}
}
override fun populateModuleContentRoots(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) {
if (!modelExists(gradleModule)) {
return super.populateModuleContentRoots(gradleModule, ideModule)
}
ContentRootsCreator.EP_NAME.extensions.forEach { contentRootsCreator ->
contentRootsCreator.populateContentRoots(gradleModule, ideModule, resolverCtx)
}
}
override fun populateModuleDependencies(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>, ideProject: DataNode<ProjectData>) {
if (!modelExists(gradleModule)) {
return super.populateModuleDependencies(gradleModule, ideModule, ideProject)
}
populateDependenciesByFragmentData(gradleModule, ideModule, ideProject, resolverCtx)
}
private fun modelExists(gradleModule: IdeaModule): Boolean = resolverCtx.getIdeaKotlinProjectModel(gradleModule) != null
companion object {
private val nativeDebugSuggester = object : KotlinMultiplatformNativeDebugSuggester<IdeaKotlinProjectModel>() {
override fun hasKotlinNativeHome(model: IdeaKotlinProjectModel?): Boolean = model?.kotlinNativeHome?.exists() ?: false
}
internal fun ProjectResolverContext.getIdeaKotlinProjectModel(gradleModule: IdeaModule): IdeaKotlinProjectModel? {
return this.getExtraProject(gradleModule, IdeaKotlinProjectModel::class.java)
}
private fun suggestNativeDebug(gradleModule: IdeaModule, resolverCtx: ProjectResolverContext) {
nativeDebugSuggester.suggestNativeDebug(resolverCtx.getIdeaKotlinProjectModel(gradleModule), resolverCtx)
if (!resolverCtx.isResolveModulePerSourceSet && !KotlinPlatformUtils.isAndroidStudio && !PlatformUtils.isMobileIde() &&
!PlatformUtils.isAppCode()
) {
notifyLegacyIsResolveModulePerSourceSetSettingIfNeeded(resolverCtx.projectPath)
resolverCtx.report(MessageEvent.Kind.WARNING, ResolveModulesPerSourceSetInMppBuildIssue())
}
}
//TODO check this
internal fun extractPackagePrefix(fragment: IdeaKotlinFragment): String? = null
internal fun extractContentRootSources(model: IdeaKotlinProjectModel): Collection<IdeaKotlinFragment> =
model.modules.flatMap { it.fragments }
//TODO replace with proper implementation, like with KotlinTaskProperties
internal fun extractPureKotlinSourceFolders(fragment: IdeaKotlinFragment): Collection<File> = fragment.sourceDirs
//TODO Unite with KotlinGradleProjectResolverExtension.getSourceSetName
internal val IdeaKotlinProjectModel.pureKotlinSourceFolders: Collection<String>
get() = extractContentRootSources(this).flatMap { extractPureKotlinSourceFolders(it) }.map { it.absolutePath }
internal val DataNode<out ModuleData>.sourceSetName
get() = (data as? GradleSourceSetData)?.id?.substringAfterLast(':')
//TODO Unite with KotlinGradleProjectResolverExtension.addDependency
internal fun addModuleDependency(
dependentModule: DataNode<out ModuleData>,
dependencyModule: DataNode<out ModuleData>,
) {
val moduleDependencyData = ModuleDependencyData(dependentModule.data, dependencyModule.data)
//TODO Replace with proper scope from dependency
moduleDependencyData.scope = DependencyScope.COMPILE
moduleDependencyData.isExported = false
moduleDependencyData.isProductionOnTestDependency = dependencyModule.sourceSetName == "test"
dependentModule.createChild(ProjectKeys.MODULE_DEPENDENCY, moduleDependencyData)
}
private fun populateDependenciesByFragmentData(
gradleModule: IdeaModule,
ideModule: DataNode<ModuleData>,
ideProject: DataNode<ProjectData>,
resolverCtx: ProjectResolverContext
) {
val allGradleModules = gradleModule.project.modules
val allModuleDataNodes = ExternalSystemApiUtil.findAll(ideProject, ProjectKeys.MODULE)
val allFragmentModulesById = allModuleDataNodes.flatMap { ExternalSystemApiUtil.findAll(it, GradleSourceSetData.KEY) }
.associateBy { it.data.id }
val sourceSetDataWithFragmentData = ExternalSystemApiUtil.findAll(ideModule, GradleSourceSetData.KEY)
.mapNotNull { ExternalSystemApiUtil.find(it, KotlinFragmentData.KEY)?.data?.let { fragmentData -> it to fragmentData } }
.sortedBy { it.second.refinesFragmentIds.size }
for ((fragmentSourceSetNode, kpmFragmentData) in sourceSetDataWithFragmentData) {
val refinesFragmentNodes = kpmFragmentData.refinesFragmentIds.mapNotNull { ideModule.findChildModuleById(it) }
refinesFragmentNodes.forEach {
addModuleDependency(fragmentSourceSetNode, it)
}
val sourceDependencyIds = kpmFragmentData.fragmentDependencies
.filterIsInstance<IdeaKotlinFragmentDependency>()
.mapNotNull { fragmentDependency ->
val foundGradleModule = allGradleModules.singleOrNull { dependencyGradleModule ->
dependencyGradleModule.name == fragmentDependency.coordinates.module.projectName
} ?: return@mapNotNull null // Probably it's worth to log
fragmentDependency to foundGradleModule
}
.map { (dependency, module) -> calculateKotlinFragmentModuleId(module, dependency.coordinates, resolverCtx) }
val dependencyModuleNodes = sourceDependencyIds.mapNotNull { allFragmentModulesById[it] }
dependencyModuleNodes.forEach { addModuleDependency(fragmentSourceSetNode, it) }
val groupedBinaryDependencies = kpmFragmentData.fragmentDependencies
.filterIsInstance<IdeaKotlinResolvedBinaryDependency>()
.groupBy { it.coordinates.toString() }
.map { (coordinates, binariesWithType) ->
GroupedLibraryDependency(coordinates, binariesWithType.map { it.binaryFile to it.binaryType.toBinaryType() })
}
groupedBinaryDependencies.forEach {
populateLibraryDependency(fragmentSourceSetNode, ideProject, it)
}
}
}
private fun String.toBinaryType(): LibraryPathType = when (this) {
IdeaKotlinDependency.CLASSPATH_BINARY_TYPE -> LibraryPathType.BINARY
IdeaKotlinDependency.SOURCES_BINARY_TYPE -> LibraryPathType.SOURCE
IdeaKotlinDependency.DOCUMENTATION_BINARY_TYPE -> LibraryPathType.DOC
else -> LibraryPathType.EXCLUDED
}
private data class GroupedLibraryDependency(
val coordinates: String?,
val binariesWithType: Collection<Pair<File, LibraryPathType>>
)
private fun populateLibraryDependency(
dependentModule: DataNode<out ModuleData>,
projectDataNode: DataNode<out ProjectData>,
binaryDependency: GroupedLibraryDependency
) {
val coordinates = binaryDependency.coordinates ?: return
val existingLibraryNodeWithData = projectDataNode.findAll(ProjectKeys.LIBRARY).find {
it.data.owner == GradleConstants.SYSTEM_ID && it.data.externalName == coordinates
}
val libraryData: LibraryData
if (existingLibraryNodeWithData != null) {
libraryData = existingLibraryNodeWithData.data
} else {
libraryData = LibraryData(GradleConstants.SYSTEM_ID, coordinates).apply {
binaryDependency.binariesWithType.forEach { (binaryFile, pathType) ->
addPath(pathType, binaryFile.absolutePath)
}
}
projectDataNode.createChild(ProjectKeys.LIBRARY, libraryData)
}
val libraryDependencyData = LibraryDependencyData(dependentModule.data, libraryData, LibraryLevel.PROJECT)
dependentModule.createChild(ProjectKeys.LIBRARY_DEPENDENCY, libraryDependencyData)
}
}
}
| apache-2.0 | 3e4fbf86277247fa076552f060a2be8d | 54.747664 | 139 | 0.722297 | 5.932372 | false | false | false | false |
jwren/intellij-community | plugins/ide-features-trainer/src/training/ui/MessageFactory.kt | 3 | 4757 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package training.ui
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.text.Strings
import org.intellij.lang.annotations.Language
import org.jdom.Element
import org.jdom.Text
import org.jdom.output.XMLOutputter
import training.dsl.LessonUtil
import training.util.KeymapUtil
import training.util.openLinkInBrowser
import java.util.regex.Pattern
import javax.swing.KeyStroke
internal object MessageFactory {
private val LOG = Logger.getInstance(MessageFactory::class.java)
fun setLinksHandlers(messageParts: List<MessagePart>) {
for (message in messageParts) {
if (message.type == MessagePart.MessageType.LINK && message.runnable == null) {
val link = message.link
if (link.isNullOrEmpty()) {
LOG.error("No link specified for ${message.text}")
}
else {
message.runnable = Runnable {
try {
openLinkInBrowser(link)
}
catch (e: Exception) {
LOG.warn(e)
}
}
}
}
}
}
fun convert(@Language("HTML") text: String): List<MessagePart> {
return text
.splitToSequence("\n")
.map { paragraph ->
val wrappedText = "<root><text>$paragraph</text></root>"
val textAsElement = JDOMUtil.load(wrappedText.byteInputStream()).getChild("text")
?: throw IllegalStateException("Can't parse as XML:\n$paragraph")
convert(textAsElement)
}
.reduce { acc, item -> acc + MessagePart("\n", MessagePart.MessageType.LINE_BREAK) + item }
}
private fun convert(element: Element?): List<MessagePart> {
if (element == null) {
return emptyList()
}
val list = mutableListOf<MessagePart>()
for (content in element.content) {
if (content is Text) {
var text = content.getValue()
if (Pattern.matches(" *\\p{IsPunctuation}.*", text)) {
val indexOfFirst = text.indexOfFirst { it != ' ' }
text = "\u00A0".repeat(indexOfFirst) + text.substring(indexOfFirst)
}
list.add(MessagePart(text, MessagePart.MessageType.TEXT_REGULAR))
}
else if (content is Element) {
val outputter = XMLOutputter()
var type = MessagePart.MessageType.TEXT_REGULAR
val text: String = Strings.unescapeXmlEntities(outputter.outputString(content.content))
var textAndSplitFn: (() -> Pair<String, List<IntRange>?>)? = null
var link: String? = null
var runnable: Runnable? = null
when (content.name) {
"icon" -> error("Need to return reflection-based icon processing")
"illustration" -> type = MessagePart.MessageType.ILLUSTRATION
"icon_idx" -> type = MessagePart.MessageType.ICON_IDX
"code" -> type = MessagePart.MessageType.CODE
"shortcut" -> type = MessagePart.MessageType.SHORTCUT
"strong" -> type = MessagePart.MessageType.TEXT_BOLD
"callback" -> {
type = MessagePart.MessageType.LINK
val id = content.getAttributeValue("id")
if (id != null) {
val callback = LearningUiManager.getAndClearCallback(id.toInt())
if (callback != null) {
runnable = Runnable { callback() }
}
else {
LOG.error("Unknown callback with id $id and text $text")
}
}
}
"a" -> {
type = MessagePart.MessageType.LINK
link = content.getAttributeValue("href")
}
"action" -> {
type = MessagePart.MessageType.SHORTCUT
link = text
textAndSplitFn = {
val shortcutByActionId = KeymapUtil.getShortcutByActionId(text)
if (shortcutByActionId != null) {
KeymapUtil.getKeyStrokeData(shortcutByActionId)
}
else {
KeymapUtil.getGotoActionData(text)
}
}
}
"raw_shortcut" -> {
type = MessagePart.MessageType.SHORTCUT
textAndSplitFn = {
KeymapUtil.getKeyStrokeData(KeyStroke.getKeyStroke(text))
}
}
"ide" -> {
type = MessagePart.MessageType.TEXT_REGULAR
textAndSplitFn = { LessonUtil.productName to null }
}
}
val message = MessagePart(type, textAndSplitFn ?: { text to null })
message.link = link
message.runnable = runnable
list.add(message)
}
}
return list
}
} | apache-2.0 | 1368846243392120894ee632fcfb32d1 | 35.045455 | 120 | 0.590919 | 4.672888 | false | false | false | false |
JetBrains/kotlin-native | runtime/src/main/kotlin/kotlin/native/concurrent/MutableData.kt | 1 | 4411 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package kotlin.native.concurrent
import kotlin.native.internal.*
import kotlinx.cinterop.*
@SymbolName("Kotlin_Any_share")
external private fun Any.share()
@SymbolName("Kotlin_CPointer_CopyMemory")
external private fun CopyMemory(to: COpaquePointer?, from: COpaquePointer?, count: Int)
@SymbolName("ReadHeapRefNoLock")
internal external fun readHeapRefNoLock(where: Any, index: Int): Any?
/**
* Mutable concurrently accessible data buffer. Could be accessed from several workers simulteniously.
*/
@Frozen
@NoReorderFields
public class MutableData constructor(capacity: Int = 16) {
init {
if (capacity <= 0) throw IllegalArgumentException()
// Instance of MutableData is shared.
share()
}
private var buffer_ = ByteArray(capacity).apply { share() }
private var buffer: ByteArray
get() =
when (kotlin.native.Platform.memoryModel) {
kotlin.native.MemoryModel.EXPERIMENTAL -> buffer_
else -> readHeapRefNoLock(this, 0) as ByteArray
}
set(value) { buffer_ = value}
private var size_ = 0
private val lock = Lock()
private fun resizeDataLocked(newSize: Int): Int {
assert(newSize >= size)
if (newSize > buffer.size) {
val actualSize = maxOf(buffer.size * 3 / 2 + 1, newSize)
val newBuffer = ByteArray(actualSize)
buffer.copyInto(newBuffer, startIndex = 0, endIndex = size)
newBuffer.share()
buffer = newBuffer
}
val position = size
size_ = newSize
return position
}
/**
* Current data size, may concurrently change later on.
*/
public val size: Int
get() = size_
/**
* Reset the data buffer, makings its size 0.
*/
public fun reset() = locked(lock) {
size_ = 0
}
/**
* Appends data to the buffer.
*/
public fun append(data: MutableData) = locked(lock) {
val toCopy = data.size
val where = resizeDataLocked(size + toCopy)
data.copyInto(buffer, 0, toCopy, where)
}
/**
* Appends byte array to the buffer.
*/
public fun append(data: ByteArray, fromIndex: Int = 0, toIndex: Int = data.size): Unit = locked(lock) {
if (fromIndex > toIndex)
throw IndexOutOfBoundsException("$fromIndex is bigger than $toIndex")
if (fromIndex == toIndex) return
val where = resizeDataLocked(this.size + (toIndex - fromIndex))
data.copyInto(buffer, where, fromIndex, toIndex)
}
/**
* Appends C data to the buffer, if `data` is null or `count` is non-positive - return.
*/
public fun append(data: COpaquePointer?, count: Int): Unit = locked(lock) {
if (data == null || count <= 0) return
val where = resizeDataLocked(this.size + count)
buffer.usePinned {
it -> CopyMemory(it.addressOf(where), data, count)
}
}
/**
* Copies range of mutable data to the byte array.
*/
public fun copyInto(output: ByteArray, destinationIndex: Int, startIndex: Int, endIndex: Int): Unit = locked(lock) {
buffer.copyInto(output, destinationIndex, startIndex, endIndex)
}
/**
* Get a byte from the mutable data.
*
* @Throws IndexOutOfBoundsException if index is beyond range.
*/
public operator fun get(index: Int): Byte = locked(lock) {
// index < 0 is checked below by array access.
if (index >= size)
throw IndexOutOfBoundsException("$index is not below $size")
buffer[index]
}
/**
* Executes provided block under lock with raw pointer to the data stored in the buffer.
* Block is executed under the spinlock, and must be short.
*/
public fun <R> withPointerLocked(block: (COpaquePointer, dataSize: Int) -> R) = locked(lock) {
buffer.usePinned {
it -> block(it.addressOf(0), size)
}
}
/**
* Executes provided block under lock with the raw data buffer.
* Block is executed under the spinlock, and must be short.
*/
public fun <R> withBufferLocked(block: (array: ByteArray, dataSize: Int) -> R) = locked(lock) {
block(buffer, size)
}
}
| apache-2.0 | e5decded1e1479cc8772fdf590839359 | 31.19708 | 120 | 0.619587 | 4.208969 | false | false | false | false |
jwren/intellij-community | platform/lang-impl/src/com/intellij/openapi/roots/ui/distribution/DistributionComboBox.kt | 1 | 8799 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.roots.ui.distribution
import com.intellij.openapi.application.ex.ClipboardUtil
import com.intellij.openapi.fileChooser.FileChooserFactory
import com.intellij.openapi.observable.properties.AtomicProperty
import com.intellij.openapi.observable.properties.ObservableMutableProperty
import com.intellij.openapi.observable.util.*
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectBundle
import com.intellij.openapi.roots.ui.distribution.DistributionComboBox.Item
import com.intellij.openapi.ui.*
import com.intellij.ui.*
import com.intellij.ui.components.fields.ExtendableTextField
import com.intellij.util.ui.JBInsets
import java.awt.event.ActionEvent
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean
import javax.swing.AbstractAction
import javax.swing.JList
import javax.swing.JTextField
import javax.swing.ListCellRenderer
import javax.swing.plaf.basic.BasicComboBoxEditor
import javax.swing.text.DefaultEditorKit
import javax.swing.text.JTextComponent
class DistributionComboBox(
private val project: Project?,
private val info: FileChooserInfo
) : ComboBox<Item>(CollectionComboBoxModel()) {
var sdkListLoadingText: String = ProjectBundle.message("sdk.loading.item")
var noDistributionText: String = ProjectBundle.message("sdk.missing.item")
var specifyLocationActionName: String = ProjectBundle.message("sdk.specify.location")
var defaultDistributionLocation: String? = null
private val collectionModel: CollectionComboBoxModel<Item>
get() = model as CollectionComboBoxModel
var selectedDistribution: DistributionInfo?
get() = (selectedItem as? Item.Distribution)?.info
set(distribution) {
selectedItem = distribution
}
override fun setSelectedItem(anObject: Any?) {
if (anObject is Item.SpecifyDistributionAction) {
showBrowseDistributionDialog()
return
}
val item = when (anObject) {
is Item.ListLoading -> Item.ListLoading
is Item.NoDistribution, null -> Item.NoDistribution
is Item.Distribution -> addDistributionIfNotExists(anObject.info)
is DistributionInfo -> addDistributionIfNotExists(anObject)
else -> throw IllegalArgumentException("Unsupported combobox item: ${anObject.javaClass.name}")
}
super.setSelectedItem(item)
}
fun addLoadingItem() {
if (!collectionModel.contains(Item.ListLoading)) {
val index = collectionModel.getElementIndex(Item.SpecifyDistributionAction)
collectionModel.add(index, Item.ListLoading)
}
}
fun removeLoadingItem() {
collectionModel.remove(Item.ListLoading)
}
fun addDistributionIfNotExists(info: DistributionInfo): Item {
val item = Item.Distribution(info)
val foundItem = collectionModel.items.find { it == item }
if (foundItem == null) {
if (info is LocalDistributionInfo) {
collectionModel.add(item)
}
else {
val index = collectionModel.getElementIndex(Item.SpecifyDistributionAction)
collectionModel.add(index, item)
if (collectionModel.contains(Item.NoDistribution)) {
collectionModel.remove(Item.NoDistribution)
super.setSelectedItem(item)
}
}
}
return foundItem ?: item
}
private fun getSelectedDistributionUiPath(): String {
val path =
(selectedDistribution as? LocalDistributionInfo)?.path
?: defaultDistributionLocation
?: collectionModel.items.asSequence()
.mapNotNull { (it as? Item.Distribution)?.info }
.mapNotNull { (it as? LocalDistributionInfo)?.path }
.firstOrNull()
?: System.getProperty("user.home", "")
return getPresentablePath(path)
}
private fun setSelectedDistributionUiPath(uiPath: String) {
when (val distribution = selectedDistribution) {
is LocalDistributionInfo -> {
distribution.uiPath = uiPath
popup?.list?.repaint()
selectedItemChanged()
}
else -> {
selectedDistribution = LocalDistributionInfo(uiPath)
}
}
}
fun bindSelectedDistribution(property: ObservableMutableProperty<DistributionInfo?>) {
bind(property.transform(
{ it?.let(Item::Distribution) ?: Item.NoDistribution },
{ (it as? Item.Distribution)?.info }
))
}
private fun bindSelectedDistributionPath(property: ObservableMutableProperty<String>) {
val mutex = AtomicBoolean()
property.afterChange { text ->
mutex.lockOrSkip {
setSelectedDistributionUiPath(text)
}
}
whenItemSelected {
mutex.lockOrSkip {
property.set(getSelectedDistributionUiPath())
}
}
}
private fun showBrowseDistributionDialog() {
val fileBrowserAccessor = object : TextComponentAccessor<DistributionComboBox> {
override fun getText(component: DistributionComboBox) = getSelectedDistributionUiPath()
override fun setText(component: DistributionComboBox, text: String) = setSelectedDistributionUiPath(text)
}
val selectFolderAction = BrowseFolderRunnable<DistributionComboBox>(
info.fileChooserTitle,
info.fileChooserDescription,
project,
info.fileChooserDescriptor,
this,
fileBrowserAccessor
)
selectFolderAction.run()
}
private fun createEditor(): Editor {
val property = AtomicProperty("")
val editor = object : Editor() {
override fun setItem(anObject: Any?) {}
override fun getItem(): Any? = selectedItem
}
editor.textField.bind(property)
bindSelectedDistributionPath(property)
return editor
}
init {
renderer = Optional.ofNullable(popup)
.map { it.list }
.map { ExpandableItemsHandlerFactory.install<Int>(it) }
.map<ListCellRenderer<Item>> { ExpandedItemListCellRendererWrapper(Renderer(), it) }
.orElseGet { Renderer() }
}
init {
collectionModel.add(Item.NoDistribution)
collectionModel.add(Item.SpecifyDistributionAction)
selectedItem = Item.NoDistribution
}
init {
val editor = createEditor()
setEditor(editor)
whenItemSelected {
setEditable(it is Item.Distribution && it.info is LocalDistributionInfo)
}
editor.textField.addBrowseExtension(::showBrowseDistributionDialog, null)
FileChooserFactory.getInstance()
.installFileCompletion(editor.textField, info.fileChooserDescriptor, true, null)
}
init {
val editorComponent = editor?.editorComponent
if (editorComponent is JTextComponent) {
val editorInputMap = editorComponent.inputMap
for (keyStroke in editorInputMap.allKeys()) {
if (DefaultEditorKit.pasteAction == editorInputMap[keyStroke]) {
inputMap.put(keyStroke, DefaultEditorKit.pasteAction)
}
}
actionMap.put(DefaultEditorKit.pasteAction, object : AbstractAction() {
override fun actionPerformed(e: ActionEvent) {
val comboBox = e.source as? DistributionComboBox ?: return
val clipboardText = ClipboardUtil.getTextInClipboard() ?: return
val distribution = comboBox.selectedDistribution
if (distribution is LocalDistributionInfo) {
distribution.uiPath = clipboardText
}
else {
comboBox.selectedDistribution = LocalDistributionInfo(clipboardText)
}
}
})
}
}
private inner class Renderer : ColoredListCellRenderer<Item>() {
override fun customizeCellRenderer(
list: JList<out Item>,
value: Item?,
index: Int,
selected: Boolean,
hasFocus: Boolean
) {
ipad = JBInsets.emptyInsets()
myBorder = null
when (value) {
is Item.ListLoading -> append(sdkListLoadingText)
is Item.NoDistribution -> append(noDistributionText, SimpleTextAttributes.ERROR_ATTRIBUTES)
is Item.SpecifyDistributionAction -> append(specifyLocationActionName)
is Item.Distribution -> {
val name = value.info.name
val description = value.info.description
append(name)
if (description != null) {
append(" ")
append(description, SimpleTextAttributes.GRAYED_ATTRIBUTES)
}
}
}
}
}
private abstract class Editor : BasicComboBoxEditor() {
val textField get() = editor as ExtendableTextField
override fun createEditorComponent(): JTextField {
val textField = ExtendableTextField()
textField.border = null
return textField
}
}
sealed class Item {
object ListLoading : Item()
object NoDistribution : Item()
object SpecifyDistributionAction : Item()
data class Distribution(val info: DistributionInfo) : Item()
}
} | apache-2.0 | 19e004e77601405c2b46ca41d987f012 | 32.846154 | 120 | 0.70758 | 5.01082 | false | false | false | false |
GunoH/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/intentions/PackageSearchUnresolvedReferenceQuickFix.kt | 2 | 2677 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.jetbrains.packagesearch.intellij.plugin.intentions
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.dependencytoolwindow.DependencyToolWindowFactory
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Iconable
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiReference
import com.jetbrains.packagesearch.PackageSearchIcons
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.PackagesListPanelProvider
import com.jetbrains.packagesearch.intellij.plugin.util.pkgsUiStateModifier
class PackageSearchUnresolvedReferenceQuickFix(private val ref: PsiReference) : IntentionAction, LowPriorityAction, Iconable {
private val classnamePattern =
Regex("(\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*\\.)*\\p{Lu}\\p{javaJavaIdentifierPart}+")
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
DependencyToolWindowFactory.activateToolWindow(project, PackagesListPanelProvider) {
project.pkgsUiStateModifier.setSearchQuery(ref.canonicalText)
}
}
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?) = ref.element.run {
isValid && classnamePattern.matches(text)
}
override fun getText() = PackageSearchBundle.message("packagesearch.quickfix.packagesearch.action")
@Suppress("DialogTitleCapitalization") // It's the Package Search plugin name...
override fun getFamilyName() = PackageSearchBundle.message("packagesearch.quickfix.packagesearch.family")
override fun getIcon(flags: Int) = PackageSearchIcons.Package
override fun startInWriteAction() = false
}
| apache-2.0 | 6298eb0e10497532a24698f3b2e8c0c8 | 46.803571 | 126 | 0.742622 | 5.041431 | false | false | false | false |
smmribeiro/intellij-community | plugins/markdown/test/src/org/intellij/plugins/markdown/editor/tables/MarkdownTableEnterTest.kt | 6 | 2976 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.editor.tables
import com.intellij.testFramework.LightPlatformCodeInsightTestCase
import org.intellij.plugins.markdown.editor.tables.TableTestUtils.runWithChangedSettings
class MarkdownTableEnterTest: LightPlatformCodeInsightTestCase() {
fun `test single enter inside cell`() {
// language=Markdown
val before = """
| none | none |
|------|------|
| some<caret> | some |
""".trimIndent()
// language=Markdown
val after = """
| none | none |
|------|------|
| some<br/><caret> | some |
""".trimIndent()
doTest(before, after)
}
fun `test double enter inside cell`() {
// language=Markdown
val before = """
| none | none |
|------|------|
| some<caret> | some |
""".trimIndent()
// language=Markdown
val after = """
| none | none |
|------|------|
| some
<caret>| some |
""".trimIndent()
doTest(before, after, count = 2)
}
fun `test single enter at the row end`() {
// language=Markdown
val before = """
| none | none |
|------|------|
| some | some |<caret>
""".trimIndent()
// language=Markdown
val after = """
| none | none |
|------|------|
| some | some |
""".trimIndent()
doTest(before, after)
}
fun `test shift enter at the row end`() {
// language=Markdown
val before = """
| none | none |
|------|------|
| some | some |<caret>
""".trimIndent()
// language=Markdown
val after = """
| none | none |
|------|------|
| some | some |
| | |<caret>
""".trimIndent()
doTest(before, after, shift = true)
}
fun `test shift enter at the separator row end`() {
// language=Markdown
val before = """
| none | none |
|------|------|<caret>
| some | some |
""".trimIndent()
// language=Markdown
val after = """
| none | none |
|------|------|
| | |<caret>
| some | some |
""".trimIndent()
doTest(before, after, shift = true)
}
fun `test shift enter at the header row end`() {
// language=Markdown
val before = """
| none | none |<caret>
|------|------|
| some | some |
""".trimIndent()
// language=Markdown
val after = """
| none | none |
<caret>
|------|------|
| some | some |
""".trimIndent()
doTest(before, after, shift = true)
}
private fun doTest(content: String, expected: String, count: Int = 1, shift: Boolean = false) {
runWithChangedSettings(project) {
configureFromFileText("some.md", content)
repeat(count) {
when {
shift -> executeAction("EditorStartNewLine")
else -> type("\n")
}
}
checkResultByText(expected)
}
}
}
| apache-2.0 | 22714505f5a5ba218c547f128d587071 | 23.595041 | 158 | 0.526882 | 4.294372 | false | true | false | false |
kmikusek/light-sensor | app/src/main/java/pl/pw/mgr/lightsensor/calibrations/CalibrationsAdapter.kt | 1 | 2830 | package pl.pw.mgr.lightsensor.calibrations
import android.content.Context
import android.support.v4.content.ContextCompat
import android.support.v7.widget.AppCompatCheckBox
import android.support.v7.widget.AppCompatTextView
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import kotlinx.android.synthetic.main.item_calibration.view.*
import pl.pw.mgr.lightsensor.R
import pl.pw.mgr.lightsensor.common.C
import pl.pw.mgr.lightsensor.data.model.Calibration
internal class CalibrationsAdapter(
private val context: Context
) : RecyclerView.Adapter<CalibrationsAdapter.ViewHolder>() {
//TODO to powinno byc sortowane po wart punktu?
private val items = mutableListOf<Calibration>()
private var selectedPosition = C.INVALID_INT
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = items[position]
holder.number.text = position.toString()
holder.label.text = item.name
holder.checkbox.isChecked = position == selectedPosition
holder.root.setOnClickListener {
if (holder.checkbox.isChecked) {
holder.checkbox.isChecked = false
selectedPosition = C.INVALID_INT
} else {
holder.checkbox.isChecked = true
val lastPosition = selectedPosition
selectedPosition = position
if (lastPosition != C.INVALID_INT) {
notifyItemChanged(lastPosition)
}
}
}
}
override fun onCreateViewHolder(parent: ViewGroup?, position: Int) =
ViewHolder(LayoutInflater.from(context).inflate(R.layout.item_calibration, parent, false))
override fun getItemCount() = items.size
fun setItems(items: List<Calibration>) {
this.items.clear()
this.items.addAll(items)
notifyDataSetChanged()
}
fun addItem(calibration: Calibration) {
items.add(calibration)
notifyItemInserted(itemCount - 1)
}
fun removeItem(calibration: Calibration) {
val position = items.indexOf(calibration)
items.remove(calibration)
if (position != C.INVALID_INT) {
selectedPosition = C.INVALID_INT
notifyItemRemoved(position)
notifyItemRangeChanged(position, itemCount)
}
}
fun getSelectedCalibration() = items.getOrNull(selectedPosition)
internal class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val root: RelativeLayout = view.item_calibration_root
val number: AppCompatTextView = view.number
val label: AppCompatTextView = view.label
val checkbox: AppCompatCheckBox = view.checkbox
}
} | mit | 9b8360a306bdb00af92b7d50a04a4e99 | 33.950617 | 102 | 0.683746 | 4.829352 | false | false | false | false |
monarezio/PathFinder | app/src/main/java/net/zdendukmonarezio/pathfinder/domain/common/extensions/List.kt | 1 | 539 | package net.zdendukmonarezio.pathfinder.domain.common.extensions
import net.zdendukmonarezio.pathfinder.domain.game.model.utils.Coordinate
/**
* Created by monarezio on 23/04/2017.
*/
fun<E> List<E>.set(index: Int, value: E): List<E> {
return mapIndexed { i, e ->
if(i == index) value
else e
}
}
fun<E> List<List<E>>.isInBounds(x: Int, y: Int): Boolean = x >= 0 && x < size && y >= 0 && y < get(x).size
fun<E> List<List<E>>.isInBounds(coordinate: Coordinate): Boolean = isInBounds(coordinate.x, coordinate.y) | apache-2.0 | 27518df610465a95f9fe490679b9d3e4 | 29 | 106 | 0.660482 | 2.994444 | false | false | false | false |
glorantq/KalanyosiRamszesz | src/glorantq/ramszesz/commands/AvatarCommand.kt | 1 | 1481 | package glorantq.ramszesz.commands
import glorantq.ramszesz.utils.BotUtils
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent
import sx.blah.discord.handle.obj.IUser
import sx.blah.discord.util.EmbedBuilder
/**
* Created by glora on 2017. 07. 23..
*/
class AvatarCommand : ICommand {
override val commandName: String
get() = "avatar"
override val description: String
get() = "Get the avatar of a user"
override val permission: Permission
get() = Permission.USER
override val extendedHelp: String
get() = "Get the avatar of a user. Tag a person to get their avatar"
override val aliases: List<String>
get() = listOf("profilepic", "ppic")
override val usage: String
get() = "[@Mention]"
override fun execute(event: MessageReceivedEvent, args: List<String>) {
val mentions: List<IUser> = event.message.mentions
val username: String
val avatarUrl: String
if(mentions.isEmpty()) {
avatarUrl = event.author.avatarURL
username = event.author.name
} else {
avatarUrl = mentions[0].avatarURL
username = mentions[0].name
}
val builder: EmbedBuilder = BotUtils.embed("Avatar", event.author)
builder.withDescription("Here's $username's avatar:")
builder.withImage("$avatarUrl?size=2048")
BotUtils.sendMessage(builder.build(), event.channel)
}
} | gpl-3.0 | 1c0efe02b55c4f027cb93f3dcc401dae | 33.465116 | 84 | 0.659014 | 4.407738 | false | false | false | false |
chiken88/passnotes | app/src/main/kotlin/com/ivanovsky/passnotes/presentation/core/adapter/ViewModelsAdapter.kt | 1 | 3194 | package com.ivanovsky.passnotes.presentation.core.adapter
import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.ivanovsky.passnotes.BR
import com.ivanovsky.passnotes.presentation.core.BaseCellViewModel
import com.ivanovsky.passnotes.presentation.core.ViewModelTypes
class ViewModelsAdapter(
private val lifecycleOwner: LifecycleOwner,
private val viewTypes: ViewModelTypes
) : RecyclerView.Adapter<ViewModelsAdapter.ViewHolder>() {
private val differ = AsyncListDiffer<BaseCellViewModel>(this, ViewModelsDiffCallback())
fun updateItems(newItems: List<BaseCellViewModel>) {
differ.submitList(newItems)
}
override fun getItemCount(): Int {
return differ.currentList.size
}
override fun getItemViewType(position: Int): Int {
val type = differ.currentList[position]::class
return viewTypes.getViewType(type)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val inflater = LayoutInflater.from(parent.context)
val layoutId = viewTypes.getLayoutResId(viewType)
val binding: ViewDataBinding = DataBindingUtil.inflate(inflater, layoutId, parent, false)
binding.lifecycleOwner = lifecycleOwner
return ViewHolder(binding)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val viewModel = differ.currentList[position]
if (holder.viewModel != null && holder.viewModel == viewModel) {
return
}
if (holder.viewModel != null) {
holder.binding.unbind()
}
holder.viewModel = viewModel
holder.binding.setVariable(BR.viewModel, viewModel)
holder.binding.executePendingBindings()
}
override fun onViewAttachedToWindow(holder: ViewHolder) {
super.onViewAttachedToWindow(holder)
holder.viewModel?.onAttach()
}
override fun onViewDetachedFromWindow(holder: ViewHolder) {
super.onViewDetachedFromWindow(holder)
holder.viewModel?.onDetach()
}
class ViewHolder(
val binding: ViewDataBinding,
var viewModel: BaseCellViewModel? = null
) : RecyclerView.ViewHolder(binding.root)
class ViewModelsDiffCallback : DiffUtil.ItemCallback<BaseCellViewModel>() {
override fun areItemsTheSame(
oldItem: BaseCellViewModel,
newItem: BaseCellViewModel
): Boolean =
if (oldItem.model.id != null && newItem.model.id != null) {
oldItem.model.id == newItem.model.id
} else {
oldItem.model == newItem.model
}
@SuppressLint("DiffUtilEquals")
override fun areContentsTheSame(
oldItem: BaseCellViewModel,
newItem: BaseCellViewModel
): Boolean =
(oldItem.model == newItem.model)
}
} | gpl-2.0 | ed5aa0f1d4e3ac78de38935a5333e9b8 | 33.354839 | 97 | 0.700063 | 5.253289 | false | false | false | false |
ZoranPandovski/al-go-rithms | sort/merge_sort/kotlin/merge_sort.kt | 1 | 1626 | fun mergeSortIA(array: IntArray) : IntArray {
val arrayCopy = array.copyOf()
val arrayCopy2 = array.copyOf()
sortSectionIA(arrayCopy, arrayCopy2, 0, arrayCopy.size)
return arrayCopy2
}
/**
* Sorts the specified section of the array.
*
* @param workA Should contain identical values as workB in the specified range.
* The final values in the specified range are destroyed (actually they are made
* of two adjacent sorted ranged).
* @param workB Should contain identical values as workA in the specified range.
* The final values in the specified range are the sorted values in that range.
*/
internal inline fun mergeHalvesIA(workA: IntArray,
workB: IntArray,
start: Int,
mid: Int,
exclusiveEnd: Int) {
var p1 = start
var p2 = mid
for (i in start until exclusiveEnd) {
if (p1 < mid && (p2 == exclusiveEnd || workA[p1] <= workA[p2])) {
workB[i] = workA[p1]
p1++
} else {
workB[i] = workA[p2]
p2++
}
}
}
internal fun sortSectionIA(input: IntArray,
output: IntArray,
start: Int,
exclusiveEnd: Int) : Unit {
if (exclusiveEnd - start <= 1)
return
val mid = (start + exclusiveEnd) / 2
sortSectionIA(output, input, start, mid)
sortSectionIA(output, input, mid, exclusiveEnd)
mergeHalvesIA(input, output, start, mid, exclusiveEnd)
}
| cc0-1.0 | 95d8d1f1dbf4af8560426e95ad807bf9 | 32.875 | 93 | 0.553506 | 4.169231 | false | false | false | false |
bixlabs/bkotlin | bkotlin/src/main/java/com/bixlabs/bkotlin/Span.kt | 1 | 7781 | package com.bixlabs.bkotlin
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.MaskFilter
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.net.Uri
import android.text.*
import android.text.style.*
import android.view.View
import java.util.*
/**
* Kotlin wrapper around SpannableStringBuilder
* Inspired by JakeWharton's Truss and Kotlin's kotlinx.html
*
* Example:
* ```
* val span = span {
* text("Regular text\n")
* +"Or with plus operator.\n\n"
*
* +"Spans "
*
* bold {
* +"are "
* strikethrough { +"hard?\n" }
* }
*
* // Nested spans
* italic {
* backgroundColor(Color.Black) {
* foregroundColor(Color.BLUE) {
* +"Nested spans "
* }
* }
* boldItalic {
* +"are so cool!\n"
* }
* }
*
* // Click example
* quote(Color.RED) {
* url("https://google.com", { println(it.url); /*redirect?*/ true }) {
* monospace {
* +"Google"
* }
* }
* }
* }
*
* textView.text = span.build()
* ```
*
* @see <a href="https://gist.github.com/JakeWharton/11274467">Truss</a>
* @see <a href="https://github.com/Kotlin/kotlinx.html">kotlinx.html</a>
*/
@Suppress("unused")
open class Span {
private val spans = ArrayList<Span>()
open fun build(builder: SpannableStringBuilder = SpannableStringBuilder()): Spannable {
spans.forEach { span -> span.build(builder) }
return builder
}
fun span(what: Any, init: Node.() -> Unit): Span {
val child = Node(what)
child.init()
spans.add(child)
return this
}
fun text(content: String): Span {
spans.add(Leaf(content))
return this
}
operator fun String.unaryPlus() = text(this)
fun style(style: Int, span: StyleSpan = StyleSpan(style), init: Span.() -> Unit): Span = span(span, init)
fun normal(span: StyleSpan = StyleSpan(Typeface.NORMAL), init: Span.() -> Unit): Span = span(span, init)
fun bold(span: StyleSpan = StyleSpan(Typeface.BOLD), init: Span.() -> Unit): Span = span(span, init)
fun italic(span: StyleSpan = StyleSpan(Typeface.ITALIC), init: Span.() -> Unit): Span = span(span, init)
fun boldItalic(span: StyleSpan = StyleSpan(Typeface.BOLD_ITALIC), init: Span.() -> Unit): Span = span(span, init)
fun underline(span: UnderlineSpan = UnderlineSpan(), init: Span.() -> Unit): Span = span(span, init)
fun typeface(family: String, span: TypefaceSpan = TypefaceSpan(family), init: Span.() -> Unit): Span = span(span, init)
fun sansSerif(span: TypefaceSpan = TypefaceSpan("sans-serif"), init: Span.() -> Unit): Span = span(span, init)
fun serif(span: TypefaceSpan = TypefaceSpan("serif"), init: Span.() -> Unit): Span = span(span, init)
fun monospace(span: TypefaceSpan = TypefaceSpan("monospace"), init: Span.() -> Unit): Span = span(span, init)
fun appearance(context: Context, appearance: Int, span: TextAppearanceSpan = TextAppearanceSpan(context, appearance), init: Span.() -> Unit): Span = span(span, init)
fun superscript(span: SuperscriptSpan = SuperscriptSpan(), init: Span.() -> Unit): Span = span(span, init)
fun subscript(span: SubscriptSpan = SubscriptSpan(), init: Span.() -> Unit): Span = span(span, init)
fun strikethrough(span: StrikethroughSpan = StrikethroughSpan(), init: Span.() -> Unit): Span = span(span, init)
fun scaleX(proportion: Float, span: ScaleXSpan = ScaleXSpan(proportion), init: Span.() -> Unit): Span = span(span, init)
fun relativeSize(proportion: Float, span: RelativeSizeSpan = RelativeSizeSpan(proportion), init: Span.() -> Unit): Span = span(span, init)
fun absoluteSize(size: Int, dip: Boolean = false, span: AbsoluteSizeSpan = AbsoluteSizeSpan(size, dip), init: Span.() -> Unit): Span = span(span, init)
fun quote(color: Int = Color.BLACK, span: QuoteSpan = QuoteSpan(color), init: Span.() -> Unit): Span = span(span, init)
fun mask(filter: MaskFilter, span: MaskFilterSpan = MaskFilterSpan(filter), init: Span.() -> Unit): Span = span(span, init)
fun leadingMargin(every: Int = 0, span: LeadingMarginSpan = LeadingMarginSpan.Standard(every), init: Span.() -> Unit): Span = span(span, init)
fun leadingMargin(first: Int = 0, rest: Int = 0, span: LeadingMarginSpan = LeadingMarginSpan.Standard(first, rest), init: Span.() -> Unit): Span = span(span, init)
fun foregroundColor(color: Int = Color.BLACK, span: ForegroundColorSpan = ForegroundColorSpan(color), init: Span.() -> Unit): Span = span(span, init)
fun backgroundColor(color: Int = Color.BLACK, span: BackgroundColorSpan = BackgroundColorSpan(color), init: Span.() -> Unit): Span = span(span, init)
fun bullet(gapWidth: Int = 0, color: Int = Color.BLACK, span: BulletSpan = BulletSpan(gapWidth, color), init: Span.() -> Unit): Span = span(span, init)
fun align(align: Layout.Alignment = Layout.Alignment.ALIGN_NORMAL, span: AlignmentSpan.Standard = AlignmentSpan.Standard(align), init: Span.() -> Unit): Span = span(span, init)
fun drawableMargin(drawable: Drawable, padding: Int = 0, span: DrawableMarginSpan = DrawableMarginSpan(drawable, padding), init: Span.() -> Unit): Span = span(span, init)
fun iconMargin(bitmap: Bitmap, padding: Int = 0, span: IconMarginSpan = IconMarginSpan(bitmap, padding), init: Span.() -> Unit): Span = span(span, init)
fun image(context: Context, bitmap: Bitmap, verticalAlignment: Int = DynamicDrawableSpan.ALIGN_BOTTOM, span: ImageSpan = ImageSpan(context, bitmap, verticalAlignment), init: Span.() -> Unit): Span = span(span, init)
fun image(drawable: Drawable, verticalAlignment: Int = DynamicDrawableSpan.ALIGN_BOTTOM, span: ImageSpan = ImageSpan(drawable, verticalAlignment), init: Span.() -> Unit): Span = span(span, init)
fun image(context: Context, uri: Uri, verticalAlignment: Int = DynamicDrawableSpan.ALIGN_BOTTOM, span: ImageSpan = ImageSpan(context, uri, verticalAlignment), init: Span.() -> Unit): Span = span(span, init)
fun image(context: Context, resourceId: Int, verticalAlignment: Int = DynamicDrawableSpan.ALIGN_BOTTOM, span: ImageSpan = ImageSpan(context, resourceId, verticalAlignment), init: Span.() -> Unit): Span = span(span, init)
fun clickable(onClick: (ClickableSpan) -> Unit, style: ((ds: TextPaint?) -> Unit)? = null, span: ClickableSpan = object : ClickableSpan() {
override fun onClick(view: View?) {
onClick(this)
}
override fun updateDrawState(ds: TextPaint?) {
if (style != null) style.invoke(ds) else super.updateDrawState(ds)
}
}, init: Span.() -> Unit): Span = span(span, init)
fun url(url: String, onClick: (URLSpan) -> Boolean, span: URLSpan = object : URLSpan(url) {
override fun onClick(widget: View?) {
if (onClick(this)) {
super.onClick(widget)
}
}
}, init: Span.() -> Unit): Span = span(span, init)
class Node(val span: Any) : Span() {
override fun build(builder: SpannableStringBuilder): Spannable {
val start = builder.length
super.build(builder)
builder.setSpan(span, start, builder.length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
return builder
}
}
class Leaf(val content: Any) : Span() {
override fun build(builder: SpannableStringBuilder): Spannable {
builder.append(content.toString())
return builder
}
}
}
fun span(init: Span.() -> Unit): Span {
val spanWithChildren = Span()
spanWithChildren.init()
return spanWithChildren
} | apache-2.0 | a0726ef83536d8b3d4c4d4c76d3eb169 | 45.047337 | 224 | 0.645547 | 3.900251 | false | false | false | false |
deltadak/plep | src/main/kotlin/nl/deltadak/plep/ui/settingspane/spinners/NumberOfMovingDaysSpinner.kt | 1 | 994 | package nl.deltadak.plep.ui.settingspane.spinners
import nl.deltadak.plep.database.settingsdefaults.SettingsDefaults
import nl.deltadak.plep.ui.settingspane.SPINNER_WIDTH
import javafx.scene.control.Spinner
import javafx.scene.control.SpinnerValueFactory
import javafx.scene.layout.GridPane
import nl.deltadak.plep.database.tables.Settings
/**
* This spinner allows the user to select the number of days that the forward/backward buttons should skip.
*/
class NumberOfMovingDaysSpinner {
/**
* Construct a new spinner.
*/
fun getNew(): Spinner<Int> {
val spinner = Spinner<Int>()
val initialNumberOfMovingDays = Settings.get(SettingsDefaults.NUMBER_OF_MOVING_DAYS).toInt()
spinner.valueFactory = SpinnerValueFactory.IntegerSpinnerValueFactory(1, 14, initialNumberOfMovingDays)
spinner.id = "numberOfMovingDaysSpinner"
spinner.prefWidth = SPINNER_WIDTH
GridPane.setColumnIndex(spinner, 2)
return spinner
}
} | mit | c20371cf559558d82482359df96d00ce | 30.09375 | 111 | 0.750503 | 4.194093 | false | false | false | false |
timakden/advent-of-code | src/main/kotlin/ru/timakden/aoc/year2016/day05/Puzzle.kt | 1 | 1336 | package ru.timakden.aoc.year2016.day05
import ru.timakden.aoc.util.md5Hex
import ru.timakden.aoc.util.measure
import kotlin.time.ExperimentalTime
@ExperimentalTime
fun main() {
measure {
println("Part One: ${solvePartOne(input)}")
println("Part Two: ${solvePartTwo(input)}")
}
}
fun solvePartOne(input: String): String {
var count = 0L
var encoded: String
var password = ""
repeat(8) {
while (true) {
encoded = md5Hex(input + count.toString())
count++
if (encoded.startsWith("00000")) {
password += encoded[5]
break
}
}
}
return password
}
fun solvePartTwo(input: String): String {
var count = 0L
var encoded: String
var password = "________"
var position: Int
repeat(8) {
while (true) {
encoded = md5Hex(input + count.toString())
count++
if (encoded.startsWith("00000") && encoded[5].isDigit()) {
position = encoded[5].toString().toInt()
if (position in 0..7 && password[position] == '_') {
password = password.replaceRange(position, position + 1, encoded[6].toString())
break
}
}
}
}
return password
}
| apache-2.0 | cf7edb54f008229bf9b42dc46bc95fbf | 23.290909 | 99 | 0.530689 | 4.282051 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/search/impact/impactinfocollection/GeneImpact.kt | 1 | 2316 | package org.evomaster.core.search.impact.impactinfocollection
import org.evomaster.core.search.gene.Gene
/**
* TO enable gene impact with inner impacts
* 1. override [clone] and [copy], such methods could be used iteratively for inner impacts.
* eg [org.evomaster.core.search.impact.impactinfocollection.value.ObjectGeneImpact.clone]
* 2. override [validate] to check if the gene type is correct
* 3. override [countImpactWithMutatedGeneWithContext], this method could also be used iteratively for inner impacts
*/
open class GeneImpact (sharedImpactInfo: SharedImpactInfo, specificImpactInfo: SpecificImpactInfo) : Impact(sharedImpactInfo, specificImpactInfo){
constructor(
id : String
) : this(SharedImpactInfo(id), SpecificImpactInfo())
open fun validate(gene : Gene) : Boolean = true
fun check(previous: Gene?, current: Gene){
if (previous != null && !validate(previous))
throw IllegalArgumentException("mismatched gene impact for previous ${previous::class.java}")
if (!validate(current))
throw IllegalArgumentException("mismatched gene impact for previous ${current::class.java}")
}
fun check(gc: MutatedGeneWithContext){
check(gc.previous, gc.current)
}
open fun countImpactWithMutatedGeneWithContext(gc: MutatedGeneWithContext, noImpactTargets: Set<Int>, impactTargets: Set<Int>, improvedTargets: Set<Int>, onlyManipulation: Boolean){
countImpactAndPerformance(noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation, num = gc.numOfMutatedGene)
}
/**
* during search, Gene might be changed due to
* e.g., taint analysis, additional info from SUT
* thus, we need to sync impact based on current gene
*/
open fun syncImpact(previous: Gene?, current: Gene){
check(previous, current)
}
open fun innerImpacts() = listOf<Impact>()
open fun flatViewInnerImpact(): Map<String, Impact> = mutableMapOf()
override fun copy(): GeneImpact {
return GeneImpact(
shared.copy(), specific.copy()
)
}
override fun clone() : GeneImpact{
return GeneImpact(
shared.clone(), specific.clone()
)
}
} | lgpl-3.0 | 53bf6c86758809773a2da781e3cb5224 | 38.271186 | 198 | 0.699482 | 4.814969 | false | false | false | false |
OpenConference/OpenConference-android | app/src/main/java/com/openconference/util/lce/LceAnimatable.kt | 1 | 2573 | package com.openconference.util.lce
import android.support.annotation.StringRes
import android.view.View
import android.widget.TextView
/**
* Default animation implementation
*
* @author Hannes Dorfmann
*/
interface LceAnimatable<M> {
var content_view: View
var errorView: TextView
var loadingView: View
var emptyView: View
fun isRestoringViewState(): Boolean
fun getViewState(): LceViewState<M>?
/**
* show the loading indicator
*/
fun showLoading() {
if (!isRestoringViewState() && loadingView.visibility != View.VISIBLE) {
loadingView.alpha = 0f
loadingView.animate().alpha(
1f).withStartAction { loadingView.visibility = View.VISIBLE }.start()
content_view.animate().alpha(0f).withEndAction { content_view.visibility = View.GONE }.start()
} else {
loadingView.visibility = View.VISIBLE
content_view.visibility = View.GONE
}
errorView.visibility = View.GONE
if (!isRestoringViewState()) {
getViewState()!!.showLoading()
}
}
/**
* Show the error indicator
*/
fun showError(@StringRes errorMsgRes: Int) {
if (!isRestoringViewState() && errorView.visibility != View.VISIBLE) {
errorView.alpha = 0f
errorView.animate().alpha(1f).withStartAction { errorView.visibility = View.VISIBLE }.start()
loadingView.animate().alpha(0f).withEndAction { loadingView.visibility = View.GONE }.start()
} else {
errorView.visibility = View.VISIBLE
loadingView.visibility = View.GONE
}
errorView.setText(errorMsgRes)
content_view.visibility = View.GONE
if (!isRestoringViewState()) {
getViewState()!!.showError(errorMsgRes)
}
}
/**
* Show the content with the given data
*/
fun showContent(data: M) {
emptyView.visibility = if (isDataEmpty(data)) {
View.VISIBLE
} else {
View.GONE
}
if (!isRestoringViewState() && content_view.visibility != View.VISIBLE) {
content_view.alpha = 0f
content_view.animate().alpha(
1f).withStartAction { content_view.visibility = View.VISIBLE }.start()
loadingView.animate().alpha(0f).withEndAction { loadingView.visibility = View.GONE }.start()
} else {
content_view.visibility = View.VISIBLE
loadingView.visibility = View.GONE
}
errorView.visibility = View.GONE
if (!isRestoringViewState()) {
getViewState()!!.showContent(data)
}
}
/**
* Used to determine if the data is empty so that the emty view should be displyed
*/
fun isDataEmpty(data: M): Boolean
} | apache-2.0 | d8c509cd9e32282f2ea2e8f881d7e0b6 | 26.094737 | 100 | 0.667703 | 4.266998 | false | false | false | false |
kmruiz/sonata | frontend/src/main/kotlin/io/sonatalang/snc/frontend/domain/token/OperatorToken.kt | 1 | 675 | package io.sonatalang.snc.frontend.domain.token
class OperatorToken(val value: String, nextToken: Boolean = true) : BasicToken(nextToken) {
override fun with(character: Char) = when {
isSuitable(character) -> OperatorToken(value + character)
else -> OperatorToken(value, nextToken = false)
}
override fun toString() = value
companion object : TokenFactory<OperatorToken> {
private val OPERATORS = arrayOf('+', '-', '/', '*', '|', '&', '=', '!', '>', '<', '%')
override fun isSuitable(character: Char) = OPERATORS.contains(character)
override fun create(character: Char) = OperatorToken(character.toString())
}
} | gpl-2.0 | f3714562bf9ee123f0ab81bf88a02eb5 | 38.764706 | 94 | 0.645926 | 4.5 | false | false | false | false |
cretz/asmble | compiler/src/main/kotlin/asmble/cli/Command.kt | 1 | 6740 | package asmble.cli
import asmble.util.Logger
abstract class Command<T> {
// Can't have this delegate
// Ug: http://stackoverflow.com/questions/33966186/how-to-delegate-implementation-to-a-property-in-kotlin
lateinit var logger: Logger
abstract val name: String
abstract val desc: String
abstract fun args(bld: ArgsBuilder): T
abstract fun run(args: T)
fun runWithArgs(bld: ArgsBuilder) = run(args(bld))
interface ArgsBuilder {
fun arg(
name: String,
desc: String,
opt: String? = null,
default: String? = null,
lowPriority: Boolean = false
): String
fun args(
name: String,
desc: String,
opt: String? = null,
default: List<String>? = null,
lowPriority: Boolean = false
): List<String>
fun flag(opt: String, desc: String, lowPriority: Boolean = false): Boolean
fun done()
class ActualArgBuilder(var args: List<String>) : ArgsBuilder {
fun getArg(opt: String?) =
if (opt != null) args.indexOf("-$opt").takeIf { it != -1 }?.let { index ->
args.getOrNull(index + 1)?.also {
args = args.subList(0, index) + args.subList(index + 2, args.size)
}
} else args.indexOfFirst { !it.startsWith("-") || it == "--" }.takeIf { it != -1 }?.let { index ->
args[index].also { args = args.subList(0, index) + args.subList(index + 1, args.size) }
}
override fun arg(name: String, desc: String, opt: String?, default: String?, lowPriority: Boolean) =
getArg(opt) ?: default ?: error("Arg '$name' not found")
override fun args(
name: String,
desc: String,
opt: String?,
default: List<String>?,
lowPriority: Boolean
): List<String> {
var ret = emptyList<String>()
while (true) { ret += getArg(opt) ?: break }
return if (ret.isNotEmpty()) ret else default ?: error("Arg '$name' not found")
}
override fun flag(opt: String, desc: String, lowPriority: Boolean) =
args.indexOf("-$opt").takeIf { it != -1 }?.also {
args = args.subList(0, it) + args.subList(it + 1, args.size)
} != null
override fun done() =
require(args.isEmpty()) { "Unknown args: $args" }
}
class ArgDefBuilder : ArgsBuilder {
var argDefs = emptyList<ArgDef>(); private set
override fun arg(name: String, desc: String, opt: String?, default: String?, lowPriority: Boolean): String {
argDefs += ArgDef.WithValue(
name = name,
opt = opt,
desc = desc,
defaultDesc = default,
multi = false,
lowPriority = lowPriority
)
return default ?: ""
}
override fun args(
name: String,
desc: String,
opt: String?,
default: List<String>?,
lowPriority: Boolean
): List<String> {
argDefs += ArgDef.WithValue(
name = name,
opt = opt,
desc = desc,
defaultDesc = default?.let {
if (it.isEmpty()) "<empty>" else if (it.size == 1) it.first() else it.toString()
},
multi = true,
lowPriority = lowPriority
)
return default ?: emptyList()
}
override fun flag(opt: String, desc: String, lowPriority: Boolean): Boolean {
argDefs += ArgDef.Flag(
opt = opt,
desc = desc,
multi = false,
lowPriority = lowPriority
)
return false
}
override fun done() { }
}
sealed class ArgDef : Comparable<ArgDef> {
abstract val name: String
// True means it won't appear in the single-line desc
abstract val lowPriority: Boolean
abstract fun argString(bld: StringBuilder): StringBuilder
abstract fun descString(bld: StringBuilder): StringBuilder
override fun compareTo(other: ArgDef) = name.compareTo(other.name)
data class WithValue(
override val name: String,
// No opt means trailing
val opt: String?,
val desc: String,
val defaultDesc: String?,
val multi: Boolean,
override val lowPriority: Boolean
) : ArgDef() {
override fun argString(bld: StringBuilder): StringBuilder {
if (defaultDesc != null) bld.append('[')
if (opt != null) bld.append("-$opt ")
bld.append("<$name>")
if (defaultDesc != null) bld.append(']')
if (multi) bld.append("...")
return bld
}
override fun descString(bld: StringBuilder): StringBuilder {
if (opt != null) bld.append("-$opt ")
bld.append("<$name>")
bld.append(" - $desc ")
if (multi) bld.append("Multiple allowed. ")
if (defaultDesc != null) bld.append("Optional, default: $defaultDesc")
else bld.append("Required.")
return bld
}
}
// fun flag(opt: String, desc: String, lowPriority: Boolean = false): Boolean
data class Flag(
val opt: String,
val desc: String,
val multi: Boolean,
override val lowPriority: Boolean
) : ArgDef() {
override val name get() = opt
override fun argString(bld: StringBuilder): StringBuilder {
bld.append("[-$opt]")
if (multi) bld.append("...")
return bld
}
override fun descString(bld: StringBuilder): StringBuilder {
bld.append("-$opt - $desc Optional. ")
if (multi) bld.append("Multiple allowed. ")
return bld
}
}
}
}
} | mit | ed26b11c565abb6108f716113183ab8d | 35.437838 | 120 | 0.467953 | 4.955882 | false | false | false | false |
vjache/klips | src/test/java/org/klips/dsl/GameScenarioTest.kt | 1 | 4346 | package org.klips.dsl
import org.junit.Test
import org.klips.RuleGroupNotTriggeredException
import org.klips.engine.*
import org.klips.engine.rete.ReteInput
import kotlin.test.assertFailsWith
class GameScenarioTest {
val pid1 = PlayerId(1)
val pid2 = PlayerId(2)
@Test
fun main() {
val input = GameRules().input
with(input) {
var aims: Pair<ActorId, ActorId>? = null
flush("Adj-Symmetry") {
createSpace()
aims = placeAims()
}
val (aim1, aim2) = aims!!
println(aims)
// Create Communication agent by AIM 1
flush("CreateAgent")
{ +CreateAgentCommand(aim1, cid(10, 11).value, ActorKind.Comm) }
val comm1 = ActorId.last!!
println("COMM: $comm1")
// Create Communication agent by AIM 2
flush("CreateAgent")
{ +CreateAgentCommand(aim2, cid(90, 91).value, ActorKind.Comm) }
// Move Communication agent to cell (10,13)
for (i in 12..13)
flush("Move")
{ +MoveCommand(comm1.facet, cid(10, i)) }
// Deploy Communication agent
flush("Deploy")
{ +DeployCommand(comm1.facet) }
// Create Guard agent by AIM 1
flush("CreateAgent")
{ +CreateAgentCommand(aim1, cid(10, 11).value, ActorKind.Guard) }
val guard1 = ActorId.last!!
// Move Guard agent to cell (10,12)
flush("Move")
{ +MoveCommand(guard1.facet, cid(10, 12)) }
// Move Guard agent to cell (11,12)
flush("Move")
{ +MoveCommand(guard1.facet, cid(11, 12)) }
// Try move Guard agent to cell (12,12) => must fail due to out of comm field
assertFailsWith<RuleGroupNotTriggeredException> {
flush("Move")
{ +MoveCommand(guard1.facet, cid(12, 12)) }
}
// Try move Guard agent to cell (12,12) => must fail due to out of comm field
assertFailsWith<RuleGroupNotTriggeredException> {
flush("Move")
{ +MoveCommand(guard1.facet, cid(11, 11)) }
}
// Move Guard agent to (11,13)
flush("Move")
{ +MoveCommand(guard1.facet, cid(11, 13)) }
// Move Guard agent to (12,13)
flush("Move")
{ +MoveCommand(guard1.facet, cid(12, 13)) }
// Try move Guard agent to cell (13,13) => must fail due to out of comm field
assertFailsWith<RuleGroupNotTriggeredException> {
flush("Move")
{ +MoveCommand(guard1.facet, cid(13, 13)) }
}
// Try move Guard agent to cell (13,14) => must fail due to out of comm field
assertFailsWith<RuleGroupNotTriggeredException> {
flush("Move")
{ +MoveCommand(guard1.facet, cid(13, 14)) }
}
// Deploy Guard agent
flush("Deploy")
{ +DeployCommand(guard1.facet) }
}
}
fun ReteInput.createSpace() {
for (i in 1..100) {
for (j in 1..100) {
val cid1 = cid(i, j)
+Adjacent(cid1, cid(i, j + 1))
+Adjacent(cid1, cid(i + 1, j))
}
}
}
fun ReteInput.placeAims(): Pair<ActorId, ActorId> {
val aim1 = ActorId()
val aim2 = ActorId()
+Actor(aim1, pid1, ActorKind.Aim, State.Deployed)
+Actor(aim2, pid2, ActorKind.Aim, State.Deployed)
+At(aim1.facet, cid(10, 10))
+At(aim2.facet, cid(90, 90))
return Pair(aim1, aim2)
}
val cidPool = mutableMapOf<Int, Facet.ConstFacet<CellId>>()
fun cid(i: Int, j: Int): Facet.ConstFacet<CellId> {
val n = i * 1000 + j
return cidPool.getOrPut(n) {
CellId(n).facet as Facet.ConstFacet<CellId>
}
}
val aidPool = mutableMapOf<Int, Facet<ActorId>>()
fun aid(i: Int): Facet<ActorId> {
return aidPool.getOrPut(i) {
ActorId(i).facet
}
}
}
fun main(args: Array<String>) {
System.out.print(">>")
System.`in`.read()
GameScenarioTest().main()
System.out.print(">>>")
System.`in`.read()
} | apache-2.0 | cccb4fcf0606d3044fd3861cec8b09ac | 28.371622 | 89 | 0.52462 | 3.925926 | false | false | false | false |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/history/HistoryItemViewHolder.kt | 1 | 6099 | package com.battlelancer.seriesguide.history
import android.graphics.drawable.Drawable
import android.text.format.DateUtils
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.collection.SparseArrayCompat
import androidx.core.view.isGone
import androidx.core.view.isInvisible
import androidx.recyclerview.widget.RecyclerView
import com.battlelancer.seriesguide.databinding.ItemHistoryBinding
import com.battlelancer.seriesguide.history.TraktEpisodeHistoryLoader.HistoryItem
import com.battlelancer.seriesguide.settings.DisplaySettings
import com.battlelancer.seriesguide.util.ImageTools
import com.battlelancer.seriesguide.util.LanguageTools
import com.battlelancer.seriesguide.util.TextTools
import com.battlelancer.seriesguide.util.TimeTools
import com.uwetrottmann.trakt5.entities.HistoryEntry
import java.util.Date
class HistoryItemViewHolder(
val binding: ItemHistoryBinding,
itemClickListener: BaseHistoryAdapter.OnItemClickListener
) : RecyclerView.ViewHolder(binding.root) {
private var historyEntry: HistoryEntry? = null
init {
binding.imageViewHistoryAvatar.isGone = true
binding.constaintLayoutHistory.setOnClickListener { view ->
historyEntry?.let { itemClickListener.onItemClick(view, it) }
}
}
fun bindCommon(
item: HistoryItem,
previousItem: HistoryItem?,
drawableWatched: Drawable,
drawableCheckIn: Drawable,
isMultiColumn: Boolean
) {
this.historyEntry = item.historyEntry
// optional header
val isShowingHeader = previousItem == null || previousItem.headerTime != item.headerTime
if (isMultiColumn) {
// In a multi-column layout it looks nicer if all items are inset by header height.
binding.textViewHistoryHeader.isInvisible = !isShowingHeader
} else {
binding.textViewHistoryHeader.isGone = !isShowingHeader
}
binding.textViewHistoryHeader.text = if (isShowingHeader) {
// display headers like "Mon in 3 days", also "today" when applicable
val context = binding.root.context.applicationContext
TimeTools.formatToLocalDayAndRelativeTime(context, Date(item.headerTime))
} else {
null
}
// action type indicator
if ("watch" == item.historyEntry.action) {
// marked watched
binding.imageViewHistoryType.setImageDrawable(drawableWatched)
} else {
// check-in, scrobble
binding.imageViewHistoryType.setImageDrawable(drawableCheckIn)
}
// Set disabled for darker icon (non-interactive).
binding.imageViewHistoryType.isEnabled = false
// timestamp
val watchedAt = item.historyEntry.watched_at
if (watchedAt != null) {
val timestamp =
DateUtils.getRelativeTimeSpanString(
watchedAt.toInstant().toEpochMilli(),
System.currentTimeMillis(),
DateUtils.MINUTE_IN_MILLIS,
DateUtils.FORMAT_ABBREV_ALL
)
binding.textViewHistoryInfo.text = timestamp
} else {
binding.textViewHistoryInfo.text = null
}
}
fun bindToEpisode(item: HistoryEntry, localShowPosters: SparseArrayCompat<String>?) {
val context = binding.root.context.applicationContext
// show title
binding.textViewHistoryShow.text = item.show?.title
// show poster, use a TMDB one
val showTmdbId = item.show?.ids?.tmdb
val posterUrl = if (localShowPosters != null && showTmdbId != null) {
// prefer poster of already added show, fall back to first uploaded poster
ImageTools.posterUrlOrResolve(
localShowPosters.get(showTmdbId),
showTmdbId,
LanguageTools.LANGUAGE_EN,
context
)
} else {
null
}
ImageTools.loadShowPosterUrlResizeSmallCrop(
context,
binding.imageViewHistoryPoster,
posterUrl
)
// episode
val episode = item.episode
val number = episode?.number
val season = episode?.season
if (episode != null && season != null && number != null) {
binding.textViewHistoryEpisode.text =
TextTools.getNextEpisodeString(context, season, number, episode.title)
} else {
binding.textViewHistoryEpisode.text = null
}
}
fun bindToMovie(item: HistoryEntry) {
// movie title
binding.textViewHistoryShow.text = item.movie?.title
val movieTmdbId = item.movie?.ids?.tmdb
val posterUrl = if (movieTmdbId != null) {
// TMDb poster (resolved on demand as trakt does not have them)
"movietmdb://$movieTmdbId"
} else {
null // no poster
}
val context = binding.root.context.applicationContext
ImageTools.loadShowPosterUrlResizeSmallCrop(
context,
binding.imageViewHistoryPoster,
posterUrl
)
}
companion object {
fun inflate(
parent: ViewGroup,
itemClickListener: BaseHistoryAdapter.OnItemClickListener
): HistoryItemViewHolder {
return HistoryItemViewHolder(
ItemHistoryBinding.inflate(
LayoutInflater.from(parent.context), parent, false
),
itemClickListener
)
}
fun areContentsTheSame(oldItem: HistoryItem, newItem: HistoryItem): Boolean {
val old = oldItem.historyEntry
val new = newItem.historyEntry
return old.watched_at == new.watched_at
&& old.action == new.action
&& old.show?.title == new.show?.title
&& old.episode?.title == new.episode?.title
&& old.movie?.title == new.movie?.title
}
}
} | apache-2.0 | 80380d300a11bf98f308da281cab5d69 | 35.746988 | 96 | 0.632235 | 5.257759 | false | false | false | false |
QReport/q-report | src/main/kotlin/ru/redenergy/report/client/ui/TicketsListShow.kt | 2 | 6978 | package ru.redenergy.report.client.ui
import com.rabbit.gui.background.DefaultBackground
import com.rabbit.gui.component.control.Button
import com.rabbit.gui.component.control.MultiTextbox
import com.rabbit.gui.component.control.TextBox
import com.rabbit.gui.component.display.TextLabel
import com.rabbit.gui.component.list.DisplayList
import com.rabbit.gui.component.list.ScrollableDisplayList
import com.rabbit.gui.component.list.entries.ListEntry
import com.rabbit.gui.render.TextRenderer
import com.rabbit.gui.show.Show
import net.minecraft.client.Minecraft
import net.minecraft.client.resources.I18n
import net.minecraft.util.EnumChatFormatting
import ru.redenergy.report.client.QReportClient
import ru.redenergy.report.common.entity.Ticket
import ru.redenergy.report.common.network.NetworkHandler
import ru.redenergy.report.common.network.packet.AddMessagePacket
import ru.redenergy.report.common.network.packet.requests.RequestSyncPacket
import java.text.SimpleDateFormat
import java.util.*
open class TicketsListShow : Show() {
init{
background = DefaultBackground()
}
val timeFormatter = SimpleDateFormat("dd.M HH:mm:ss")
var selectedTicketIndex: Int = -1
var selectedTicket: Ticket? = null
get() = if(selectedTicketIndex >= 0 && selectedTicketIndex < QReportClient.syncedTickets.size)
QReportClient.syncedTickets[selectedTicketIndex]
else
null
override fun onInit(){
super.onInit()
NetworkHandler.sendToServer(RequestSyncPacket())
}
override fun setup(){
super.setup()
registerComponents()
updateInformation()
}
open fun registerComponents(){
registerComponent(TextLabel(this.width / 5, this.height / 5 - 15, this.width / 6, I18n.format("show.tickets.list.title")))
registerComponent(ScrollableDisplayList(this.width / 5, this.height / 5, this.width / 6 , this.height / 5 * 3, 45,
getTicketsListContent()))
registerComponent(TextLabel(this.width / 5 + this.width / 6 + 15, this.height / 5 - 15, this.width / 6, I18n.format("show.tickets.box.title")))
registerComponent(MultiTextbox(this.width / 5 + this.width / 6 + 15, this.height / 5, this.width / 3 - 15, this.height / 4 * 2 - 23, I18n.format("show.tickets.select"))
.setBackgroundVisibility(false)
.setMaxLenght(Int.MAX_VALUE)
.setIsEnabled(false)
.setId("information_field"))
registerComponent(TextLabel(this.width / 5 + this.width / 6 + 15, this.height / 5 + this.height / 4 * 2 - 15, this.width / 3, I18n.format("show.tickets.label.title"))
.setIsVisible(false)
.setId("add_message_label"))
registerComponent(MultiTextbox(this.width / 5 + this.width / 6 + 15, this.height / 5 + this.height / 4 * 2, this.width / 3, this.height / 10)
.setId("new_message_field")
.setIsVisible(false)
.setIsEnabled(false))
registerComponent(Button(this.width / 5 + this.width / 6 + 15, this.height / 5 + this.height / 4 * 2 + this.height / 10 + 5, this.width / 3, 20, I18n.format("show.tickets.send"))
.setIsVisible(false)
.setIsEnabled(false)
.setId("send_message_button")
.setClickListener({ addMessage() }))
registerComponent(Button(this.width / 5 + this.width / 6 + 15, this.height / 5 + this.height / 4 * 2 + this.height / 10 + 5 + 22, this.width / 3, 20, I18n.format("show.report.close"))
.setClickListener { this.getStage().displayPrevious() })
}
open fun getTicketsListContent(): List<TicketEntry> =
QReportClient.syncedTickets
.sortedBy { it.messages.get(0).timestamp }
.reversed()
.filter { it.sender.equals(Minecraft.getMinecraft().thePlayer.commandSenderName, true) }
.map { TicketEntry(it, {select(it)}) }
protected fun select(selected: Ticket){
this.selectedTicketIndex = QReportClient.syncedTickets.indexOf(selected)
updateInformation()
}
open fun updateInformation() {
val ticket = this.selectedTicket ?: return
var informationLabel = findComponentById<MultiTextbox>("information_field") as MultiTextbox
informationLabel.setText(generateInformation(ticket))
var hasAccess = QReportClient.adminAccess || ticket.sender.equals(Minecraft.getMinecraft().thePlayer.commandSenderName, true)
setMessageSectionStatus(hasAccess)
}
private fun generateInformation(ticket: Ticket): String{
var builder = StringBuilder()
ticket.messages.forEach {
with(builder) {
append("${EnumChatFormatting.BOLD}${it.sender}")
append("\n")
append(timeFormatter.format(Date(it.timestamp)))
append("\n")
append(it.text)
append("\n\n")
}
}
return builder.toString()
}
private fun setMessageSectionStatus(status: Boolean){
var label = findComponentById<TextLabel>("add_message_label") as TextLabel
label.setIsVisible(status)
var messageField = findComponentById<TextBox>("new_message_field") as TextBox
messageField.setIsEnabled(status).setIsVisible(status)
var sendMessageButton = findComponentById<Button>("send_message_button") as Button
sendMessageButton.setIsVisible(status).setIsEnabled(status)
}
private fun addMessage(){
var message = (findComponentById<MultiTextbox>("new_message_field") as MultiTextbox).text
if(this.selectedTicket == null || message.trim().equals("")) return
NetworkHandler.sendToServer(AddMessagePacket(this.selectedTicket!!.uid, message))
NetworkHandler.sendToServer(RequestSyncPacket())
}
class TicketEntry(val ticket: Ticket, val action: () -> Unit) : ListEntry{
override fun onClick(list: DisplayList?, mouseX: Int, mouseY: Int) {
super.onClick(list, mouseX, mouseY)
action.invoke()
}
override fun onDraw(list: DisplayList?, posX: Int, posY: Int, width: Int, height: Int, mouseX: Int, mouseY: Int) {
TextRenderer.renderString(posX + 5, posY + 5, ticket.sender)
TextRenderer.renderString(posX + 5, posY + 15, "#" + ticket.shortUid)
TextRenderer.renderString(posX + 5, posY + 25, I18n.format("show.tickets.reason") + " " + I18n.format(ticket.reason.translateKey))
TextRenderer.renderString(posX + 5, posY + 35,
"${EnumChatFormatting.WHITE}${I18n.format("show.tickets.status")} ${EnumChatFormatting.RESET}" + I18n.format(ticket.status.translateKey), ticket.status.color)
}
}
} | mit | 2b19c72b46cab36c4247463a5a866089 | 45.482993 | 191 | 0.64732 | 4.148633 | false | false | false | false |
a642500/Ybook | app/src/main/kotlin/com/ybook/app/ui/home/IdentityFragment.kt | 1 | 6043 | /*
Copyright 2015 Carlos
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.ybook.app.ui.home
import android.support.v4.app.Fragment
import android.widget.AbsListView
import android.widget.ListAdapter
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.View
import android.widget.AdapterView
import android.app.Activity
import android.widget.TextView
import com.ybook.app.dummy.DummyContent
import android.widget.ArrayAdapter
import com.ybook.app
import android.widget.AdapterView.OnItemClickListener
import com.github.ksoichiro.android.observablescrollview.ObservableListView
import com.github.ksoichiro.android.observablescrollview.ObservableScrollViewCallbacks
import com.github.ksoichiro.android.observablescrollview.ObservableGridView
import com.github.ksoichiro.android.observablescrollview.Scrollable
import com.ybook.app.ui.main.MainActivity
import com.ybook.app.ui.main.OnHeadViewHideOrShowListener
import android.widget.ListView
import com.ybook.app.R
import android.support.v7.widget.RecyclerView
import com.github.ksoichiro.android.observablescrollview.ObservableRecyclerView
import java.util.ArrayList
import com.ybook.app.ui.home.IdentityRecyclerAdapter.IdentityCardData
import com.ybook.app.util.AccountHelper
import me.toxz.kotlin.after
import android.support.v7.widget.LinearLayoutManager
/**
* A fragment representing a list of Items.
* <p/>
* Large screen devices (such as tablets) are supported by replacing the ListView
* with a GridView.
* <p/>
* Activities containing this fragment MUST implement the {@link OnFragmentInteractionListener}
* interface.
*/
public class IdentityFragment : Fragment(), OnItemClickListener {
private var mInteractionListener: OnFragmentInteractionListener? = null
private var mRecyclerView: ObservableRecyclerView? = null
private var mAdapter: IdentityRecyclerAdapter? = null
private val mItems = ArrayList<IdentityCardData>()
private var mEmptyData: IdentityCardData? = IdentityCardData(IdentityRecyclerAdapter.ViewType.Login)
override fun onCreate(savedInstanceState: Bundle?) {
super<Fragment>.onCreate(savedInstanceState)
// TODO: Change Adapter to display your content
}
override fun onResume() {
super<Fragment>.onResume()
testLogin()
}
private fun testLogin() {
if (mItems.contains(mEmptyData) && AccountHelper.hasAccount(getActivity())) {
mItems.remove(mEmptyData)
mAdapter!!.notifyDataSetChanged()
} else if (!mItems.contains(mEmptyData) && !AccountHelper.hasAccount(getActivity())) {
mItems.add(mEmptyData)
mAdapter!!.notifyDataSetChanged()
}
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
val view = inflater!!.inflate(app.R.layout.fragment_identity_list, container, false)
mAdapter = IdentityRecyclerAdapter(inflater, mItems)
mRecyclerView = (view.findViewById(android.R.id.list) as ObservableRecyclerView) after {
it setHasFixedSize true
it setLayoutManager LinearLayoutManager(inflater.getContext())
it setAdapter mAdapter
if (!this.isDetached()) it setScrollViewCallbacks mCallback
}
return view
}
private var mCallback: ObservableScrollViewCallbacks? = null
override fun onAttach(activity: Activity?) {
super<Fragment>.onAttach(activity)
try {
mInteractionListener = activity as OnFragmentInteractionListener
} catch (e: ClassCastException) {
throw ClassCastException(activity!!.toString() + " must implement OnFragmentInteractionListener")
}
try {
mCallback = activity as ObservableScrollViewCallbacks
if (mRecyclerView != null) {
(mRecyclerView as Scrollable).setScrollViewCallbacks(mCallback)
}
} catch(e: ClassCastException) {
throw ClassCastException(activity!!.toString() + " must implement ObservableScrollViewCallbacks")
}
}
override fun onDetach() {
super<Fragment>.onDetach()
mInteractionListener = null
mRecyclerView!!.setScrollViewCallbacks(null)
}
override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
if (null != mInteractionListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mInteractionListener!!.onFragmentInteraction(DummyContent.ITEMS.get(position).id)
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public trait OnFragmentInteractionListener {
// TODO: Update argument type and name
public fun onFragmentInteraction(id: String)
}
class object {
// TODO: Rename and change types of parameters
public fun newInstance(): IdentityFragment {
return IdentityFragment()
}
}
} | apache-2.0 | c8941fb29a63ae846b329a3b8890207c | 37.253165 | 116 | 0.722654 | 4.885206 | false | false | false | false |
MaibornWolff/codecharta | analysis/import/GitLogParser/src/test/kotlin/de/maibornwolff/codecharta/importer/gitlogparser/converter/AttributeTypesFactoryTest.kt | 1 | 2150 | package de.maibornwolff.codecharta.importer.gitlogparser.converter
import de.maibornwolff.codecharta.importer.gitlogparser.input.metrics.MetricsFactory
import de.maibornwolff.codecharta.model.AttributeType
import org.assertj.core.api.Assertions
import org.junit.jupiter.api.Test
class AttributeTypesFactoryTest {
@Test
fun `gets type for node attributes is correct`() {
val metrics = MetricsFactory(listOf("added_lines", "age_in_weeks")).createMetrics()
val attributeTypes = AttributeTypesFactory.createNodeAttributeTypes(metrics)
Assertions.assertThat(attributeTypes.type).isEqualTo("nodes")
}
@Test
fun `gets attributeTypes for specified metrics`() {
val metrics = MetricsFactory(listOf("added_lines", "age_in_weeks")).createMetrics()
val attributeTypes = AttributeTypesFactory.createNodeAttributeTypes(metrics)
Assertions.assertThat(attributeTypes.attributeTypes).containsKeys("added_lines", "age_in_weeks")
Assertions.assertThat(attributeTypes.attributeTypes)
.isEqualTo(mapOf("added_lines" to AttributeType.absolute, "age_in_weeks" to AttributeType.relative))
}
@Test
fun `gets type for edge attributes is correct`() {
val metrics = MetricsFactory().createMetrics()
val attributeTypes = AttributeTypesFactory.createEdgeAttributeTypes(metrics)
Assertions.assertThat(attributeTypes.type).isEqualTo("edges")
}
@Test
fun `gets attributeTypes for edge metrics`() {
val metrics = MetricsFactory(listOf("highly_coupled_files")).createMetrics()
val attributeTypes = AttributeTypesFactory.createEdgeAttributeTypes(metrics)
Assertions.assertThat(attributeTypes.attributeTypes)
.isEqualTo(mapOf("temporal_coupling" to AttributeType.absolute))
}
@Test
fun `handles null values for edge attributeTypes correctly`() {
val metrics = MetricsFactory(listOf("added_lines")).createMetrics()
val attributeTypes = AttributeTypesFactory.createEdgeAttributeTypes(metrics)
Assertions.assertThat(attributeTypes.attributeTypes).isEmpty()
}
}
| bsd-3-clause | 2bdeadebb6af7fdcfd16be64e8fba2de | 36.719298 | 112 | 0.736744 | 4.735683 | false | true | false | false |
ericberman/MyFlightbookAndroid | app/src/main/java/com/myflightbook/android/webservices/CreateUserSvc.kt | 1 | 2240 | /*
MyFlightbook for Android - provides native access to MyFlightbook
pilot's logbook
Copyright (C) 2017-2022 MyFlightbook, LLC
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.myflightbook.android.webservices
import org.ksoap2.serialization.SoapObject
import android.content.Context
import java.lang.Exception
class CreateUserSvc : MFBSoap() {
fun fCreateUser(
szEmail: String?, szPass: String?, szFirst: String?, szLast: String?,
szQ: String?, szA: String?, c: Context?
): Boolean {
var fResult = false
val request = setMethod("CreateUser")
request.addProperty("szAppToken", AuthToken.APPTOKEN)
request.addProperty("szEmail", szEmail)
request.addProperty("szPass", szPass)
request.addProperty("szFirst", szFirst)
request.addProperty("szLast", szLast)
request.addProperty("szQuestion", szQ)
request.addProperty("szAnswer", szA)
val result = invoke(c) as SoapObject?
if (result == null) lastError = "Error creating account - $lastError" else {
try {
// if we get here, we have success.
AuthToken.m_szAuthToken = result.getProperty("szAuthToken").toString()
AuthToken.m_szEmail = szEmail!!
AuthToken.m_szPass = szPass!!
fResult = true
// Clear the aircraft cache because we need to reload it
val ac = AircraftSvc()
ac.flushCache()
} catch (e: Exception) {
lastError += e.message
}
}
return fResult
}
} | gpl-3.0 | f798264a5e09409edac179ff9dcaf72d | 38.315789 | 86 | 0.647768 | 4.507042 | false | false | false | false |
shyiko/ktlint | ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/ArgumentListWrappingRule.kt | 1 | 12647 | package com.pinterest.ktlint.ruleset.experimental
import com.pinterest.ktlint.core.KtLint
import com.pinterest.ktlint.core.Rule
import com.pinterest.ktlint.core.ast.ElementType
import com.pinterest.ktlint.core.ast.ElementType.DOT_QUALIFIED_EXPRESSION
import com.pinterest.ktlint.core.ast.ElementType.ELSE
import com.pinterest.ktlint.core.ast.ElementType.TYPE_ARGUMENT_LIST
import com.pinterest.ktlint.core.ast.children
import com.pinterest.ktlint.core.ast.column
import com.pinterest.ktlint.core.ast.isPartOf
import com.pinterest.ktlint.core.ast.isPartOfComment
import com.pinterest.ktlint.core.ast.isRoot
import com.pinterest.ktlint.core.ast.isWhiteSpace
import com.pinterest.ktlint.core.ast.isWhiteSpaceWithNewline
import com.pinterest.ktlint.core.ast.lineIndent
import com.pinterest.ktlint.core.ast.prevLeaf
import com.pinterest.ktlint.core.ast.visit
import kotlin.math.max
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafElement
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.PsiWhiteSpaceImpl
import org.jetbrains.kotlin.psi.KtContainerNode
import org.jetbrains.kotlin.psi.KtDoWhileExpression
import org.jetbrains.kotlin.psi.KtIfExpression
import org.jetbrains.kotlin.psi.KtWhileExpression
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
/**
* https://kotlinlang.org/docs/reference/coding-conventions.html#method-call-formatting
*
* The rule is more aggressive in inserting newlines after arguments than mentioned in the styleguide:
* Each argument should be on a separate line if
* - at least one of the arguments is
* - maxLineLength exceeded (and separating arguments with \n would actually help)
* in addition, "(" and ")" must be on separates line if any of the arguments are (otherwise on the same)
*/
class ArgumentListWrappingRule : Rule("argument-list-wrapping") {
private var indentSize = -1
private var maxLineLength = -1
override fun visit(
node: ASTNode,
autoCorrect: Boolean,
emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit
) {
if (node.isRoot()) {
val editorConfig = node.getUserData(KtLint.EDITOR_CONFIG_USER_DATA_KEY)!!
indentSize = editorConfig.indentSize
maxLineLength = editorConfig.maxLineLength
return
}
if (indentSize <= 0) {
return
}
if (node.elementType == ElementType.VALUE_ARGUMENT_LIST &&
// skip when there are no arguments
node.firstChildNode?.treeNext?.elementType != ElementType.RPAR &&
// skip lambda arguments
node.treeParent?.elementType != ElementType.FUNCTION_LITERAL &&
// skip if number of arguments is big (we assume it with a magic number of 8)
node.children().count { it.elementType == ElementType.VALUE_ARGUMENT } <= 8
) {
// each argument should be on a separate line if
// - at least one of the arguments is
// - maxLineLength exceeded (and separating arguments with \n would actually help)
// in addition, "(" and ")" must be on separates line if any of the arguments are (otherwise on the same)
val putArgumentsOnSeparateLines =
node.textContainsIgnoringLambda('\n') ||
// max_line_length exceeded
maxLineLength > -1 && (node.column - 1 + node.textLength) > maxLineLength && !node.textContains('\n')
if (putArgumentsOnSeparateLines) {
val prevWhitespaceWithNewline = node.prevLeaf { it.isWhiteSpaceWithNewline() }
val adjustedIndent = when {
// IDEA quirk:
// generic<
// T,
// R>(
// 1,
// 2
// )
// instead of
// generic<
// T,
// R>(
// 1,
// 2
// )
prevWhitespaceWithNewline?.isPartOf(TYPE_ARGUMENT_LIST) == true -> indentSize
// IDEA quirk:
// foo
// .bar(
// 1,
// 2
// )
// instead of
// foo
// .bar(
// 1,
// 2
// )
prevWhitespaceWithNewline?.isPartOf(DOT_QUALIFIED_EXPRESSION) == true -> indentSize
else -> 0
}
// aiming for
// ... LPAR
// <line indent + indentSize> VALUE_ARGUMENT...
// <line indent> RPAR
val lineIndent = node.lineIndent()
val indent = ("\n" + lineIndent.substring(0, (lineIndent.length - adjustedIndent).coerceAtLeast(0)))
.let { if (node.isOnSameLineAsControlFlowKeyword()) it + " ".repeat(indentSize) else it }
val paramIndent = indent + " ".repeat(indentSize)
nextChild@ for (child in node.children()) {
when (child.elementType) {
ElementType.LPAR -> {
val prevLeaf = child.prevLeaf()
if (prevLeaf is PsiWhiteSpace && prevLeaf.textContains('\n')) {
emit(child.startOffset, errorMessage(child), true)
if (autoCorrect) {
prevLeaf.delete()
}
}
}
ElementType.VALUE_ARGUMENT,
ElementType.RPAR -> {
var argumentInnerIndentAdjustment = 0
val prevLeaf = child.prevWhiteSpaceWithNewLine() ?: child.prevLeaf()
val intendedIndent = if (child.elementType == ElementType.VALUE_ARGUMENT) {
paramIndent
} else {
indent
}
if (prevLeaf is PsiWhiteSpace) {
val spacing = prevLeaf.getText()
val cut = spacing.lastIndexOf("\n")
if (cut > -1) {
val childIndent = spacing.substring(cut)
if (childIndent == intendedIndent) {
continue@nextChild
}
emit(
child.startOffset,
"Unexpected indentation" +
" (expected ${intendedIndent.length - 1}, actual ${childIndent.length - 1})",
true
)
} else {
emit(child.startOffset, errorMessage(child), true)
}
if (autoCorrect) {
val adjustedIndent =
(if (cut > -1) spacing.substring(0, cut) else "") + intendedIndent
argumentInnerIndentAdjustment = adjustedIndent.length - prevLeaf.getTextLength()
(prevLeaf as LeafPsiElement).rawReplaceWithText(adjustedIndent)
}
} else {
emit(child.startOffset, errorMessage(child), true)
if (autoCorrect) {
argumentInnerIndentAdjustment = intendedIndent.length - child.column
node.addChild(PsiWhiteSpaceImpl(intendedIndent), child)
}
}
if (argumentInnerIndentAdjustment != 0 && child.elementType == ElementType.VALUE_ARGUMENT) {
child.visit { n ->
if (n.elementType == ElementType.WHITE_SPACE && n.textContains('\n')) {
val isInCollectionOrFunctionLiteral =
n.treeParent?.elementType == ElementType.COLLECTION_LITERAL_EXPRESSION || n.treeParent?.elementType == ElementType.FUNCTION_LITERAL
// If we're inside a collection literal, let's recalculate the adjustment
// because the items inside the collection should not be subject to the same
// indentation as the brackets.
val adjustment = if (isInCollectionOrFunctionLiteral) {
val expectedPosition = intendedIndent.length + indentSize
expectedPosition - child.column
} else {
argumentInnerIndentAdjustment
}
val split = n.text.split("\n")
(n as LeafElement).rawReplaceWithText(
split.joinToString("\n") {
when {
it.isEmpty() -> it
adjustment > 0 -> it + " ".repeat(adjustment)
else -> it.substring(0, max(it.length + adjustment, 0))
}
}
)
}
}
}
}
}
}
}
}
}
private fun errorMessage(node: ASTNode) =
when (node.elementType) {
ElementType.LPAR -> """Unnecessary newline before "(""""
ElementType.VALUE_ARGUMENT ->
"Argument should be on a separate line (unless all arguments can fit a single line)"
ElementType.RPAR -> """Missing newline before ")""""
else -> throw UnsupportedOperationException()
}
private fun ASTNode.textContainsIgnoringLambda(char: Char): Boolean {
return children().any { child ->
val elementType = child.elementType
elementType == ElementType.WHITE_SPACE && child.textContains(char) ||
elementType == ElementType.COLLECTION_LITERAL_EXPRESSION && child.textContains(char) ||
elementType == ElementType.VALUE_ARGUMENT && child.children().any { it.textContainsIgnoringLambda(char) }
}
}
private fun ASTNode.prevWhiteSpaceWithNewLine(): ASTNode? {
var prev = prevLeaf()
while (prev != null && (prev.isWhiteSpace() || prev.isPartOfComment())) {
if (prev.isWhiteSpaceWithNewline()) {
return prev
}
prev = prev.prevLeaf()
}
return null
}
private fun ASTNode.isOnSameLineAsControlFlowKeyword(): Boolean {
val containerNode = psi.getStrictParentOfType<KtContainerNode>() ?: return false
if (containerNode.node.elementType == ELSE) return false
val controlFlowKeyword = when (val parent = containerNode.parent) {
is KtIfExpression -> parent.ifKeyword.node
is KtWhileExpression -> parent.firstChild.node
is KtDoWhileExpression -> parent.whileKeyword?.node
else -> null
} ?: return false
var prevLeaf = prevLeaf() ?: return false
while (prevLeaf != controlFlowKeyword) {
if (prevLeaf.isWhiteSpaceWithNewline()) return false
prevLeaf = prevLeaf.prevLeaf() ?: return false
}
return true
}
}
| mit | ad05dbafe279841d3d63cf04e6836086 | 49.588 | 175 | 0.498142 | 5.874129 | false | false | false | false |
vanniktech/Emoji | emoji/src/androidMain/kotlin/com/vanniktech/emoji/EmojiManagers.kt | 1 | 1929 | /*
* Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("EmojiManagers")
package com.vanniktech.emoji
import android.content.Context
import android.text.Spannable
import android.text.SpannableStringBuilder
import com.vanniktech.emoji.internal.EmojiSpan
fun EmojiManager.replaceWithImages(
context: Context,
text: Spannable?,
emojiSize: Float,
) {
val emojiReplacer = emojiProvider() as? EmojiReplacer ?: defaultEmojiReplacer
emojiReplacer.replaceWithImages(
context = context,
text = text ?: SpannableStringBuilder(""),
emojiSize = emojiSize,
fallback = defaultEmojiReplacer,
)
}
internal val defaultEmojiReplacer = EmojiReplacer { context, text, emojiSize, _ ->
val existingSpans = text.getSpans(0, text.length, EmojiSpan::class.java)
val existingSpanPositions: MutableList<Int> = ArrayList(existingSpans.size)
val size = existingSpans.size
for (i in 0 until size) {
existingSpanPositions.add(text.getSpanStart(existingSpans[i]))
}
val findAllEmojis = EmojiManager.findAllEmojis(text)
for (i in findAllEmojis.indices) {
val (emoji, range) = findAllEmojis[i]
if (!existingSpanPositions.contains(range.first)) {
text.setSpan(
EmojiSpan(context, emoji, emojiSize),
range.first, range.last, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE,
)
}
}
}
| apache-2.0 | 5bf4ac32bd44d766e60ee9fef6867958 | 32.807018 | 82 | 0.738454 | 4.108742 | false | false | false | false |
alessio-b-zak/myRivers | android/app/src/main/java/com/epimorphics/android/myrivers/models/InputStreamToWIMSPoint.kt | 1 | 2567 | package com.epimorphics.android.myrivers.models
import android.util.JsonReader
import com.epimorphics.android.myrivers.data.WIMSPoint
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.util.*
/**
* Consumes an InputStream and converts it to a List of WIMSPoints
*
* @see WIMSPoint
*/
class InputStreamToWIMSPoint {
/**
* Converts InputStream to JsonReader and consumes it.
*
* @param inputStream InputStream to be consumed
*
* @throws IOException
*/
@Throws(IOException::class)
fun readJsonStream(inputStream: InputStream): List<WIMSPoint> {
val reader = JsonReader(InputStreamReader(inputStream, "UTF-8"))
reader.use {
return readMessagesArray(reader)
}
}
/**
* Focuses on the array of objects that are to be converted to WIMSPoints and parses
* them one by one.
*
* @param reader JsonReader to be consumed
* @return List<WIMSPoint> result
*
* @throws IOException
*/
@Throws(IOException::class)
fun readMessagesArray(reader: JsonReader): List<WIMSPoint> {
val messages = ArrayList<WIMSPoint>()
reader.beginArray()
while (reader.hasNext()) {
messages.add(readMessage(reader))
}
reader.endArray()
return messages
}
/**
* Converts single JsonObject to WIMSPoint and returns it.
*
* @param reader JsonReader to be consumed
* @param withDistance a Boolean flag set to true when a distance to the user's location is
* needed(in MyArea) and false otherwise
*
* @throws IOException
*/
@Throws(IOException::class)
fun readMessage(reader: JsonReader, withDistance: Boolean = false): WIMSPoint {
var id: String = ""
var latitude = 0.0
var longitude = 0.0
var distance = 0.0
reader.beginObject()
while (reader.hasNext()) {
val name = reader.nextName()
when (name) {
"id" -> id = reader.nextString()
"latitude" -> latitude = reader.nextDouble()
"longitude" -> longitude = reader.nextDouble()
"distance" -> distance = reader.nextDouble()
else -> reader.skipValue()
}
}
reader.endObject()
if (withDistance) {
return WIMSPoint(id, latitude, longitude, distance)
} else {
return WIMSPoint(id, latitude, longitude)
}
}
} | mit | c67947b676bea29c2dd81b52e8741096 | 27.533333 | 95 | 0.603818 | 4.667273 | false | false | false | false |
siempredelao/Distance-From-Me-Android | app/src/main/java/gc/david/dfm/address/data/AddressRemoteDataSource.kt | 1 | 2858 | /*
* Copyright (c) 2019 David Aguiar Gonzalez
*
* 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 gc.david.dfm.address.data
import android.content.Context
import com.google.android.gms.maps.model.LatLng
import com.google.gson.Gson
import gc.david.dfm.R
import gc.david.dfm.address.data.model.AddressCollectionEntity
import gc.david.dfm.logger.DFMLogger
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.IOException
/**
* Created by david on 12.01.17.
*/
class AddressRemoteDataSource(context: Context) : AddressRepository {
private val client = OkHttpClient()
private val gson = Gson()
private val geocodeApiKey = context.resources.getString(R.string.maps_geocode_api_key)
override fun getNameByCoordinates(coordinates: LatLng, callback: AddressRepository.Callback) {
executeRequest(getNameByCoordinatesUrl(coordinates), callback)
}
override fun getCoordinatesByName(name: String, callback: AddressRepository.Callback) {
executeRequest(getCoordinatesByNameUrl(name), callback)
}
private fun executeRequest(url: String, callback: AddressRepository.Callback) {
val request = Request.Builder().url(url).header("content-type", "application/json").build()
try {
val response = client.newCall(request).execute()
val addressCollectionEntity =
gson.fromJson(response.body()!!.charStream(), AddressCollectionEntity::class.java)
callback.onSuccess(addressCollectionEntity)
} catch (exception: IOException) {
callback.onError(exception.message ?: "AddressRemoteDataSource error")
}
}
private fun getNameByCoordinatesUrl(coordinates: LatLng): String {
val parameter = "latlng=${coordinates.latitude},${coordinates.longitude}"
DFMLogger.logMessage("AddressRemoteDataSource", parameter)
return getUrl(parameter)
}
private fun getCoordinatesByNameUrl(name: String): String {
val parameterValue = name.replace(" ", "+")
val parameter = "address=$parameterValue"
DFMLogger.logMessage("AddressRemoteDataSource", parameter)
return getUrl(parameter)
}
private fun getUrl(parameter: String): String {
return "https://maps.googleapis.com/maps/api/geocode/json?$parameter&key=$geocodeApiKey"
}
}
| apache-2.0 | 230cd0ee3b0f0be567e082ef8e07dba9 | 36.605263 | 102 | 0.721484 | 4.417311 | false | false | false | false |
iZettle/wrench | wrench-app/src/main/java/com/izettle/wrench/database/WrenchApplication.kt | 1 | 705 | package com.izettle.wrench.database
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import com.izettle.wrench.database.tables.ApplicationTable
@Entity(tableName = ApplicationTable.TABLE_NAME, indices = [Index(value = arrayOf(ApplicationTable.COL_PACK_NAME), unique = true)])
data class WrenchApplication constructor(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = ApplicationTable.COL_ID)
var id: Long,
@ColumnInfo(name = ApplicationTable.COL_PACK_NAME)
var packageName: String,
@ColumnInfo(name = ApplicationTable.COL_APP_LABEL)
var applicationLabel: String
)
| mit | 67dcd5678db00d21d4a700c11e04cc11 | 34.25 | 131 | 0.739007 | 4.246988 | false | false | false | false |
jdinkla/groovy-java-ray-tracer | src/main/kotlin/net/dinkla/raytracer/objects/utilities/PlyType.kt | 1 | 914 | package net.dinkla.raytracer.objects.utilities
import java.util.HashMap
enum class PlyType private constructor(internal val key: String, internal val clazz: Class<*>, internal val size: Int) {
CHAR("char", Short::class.java, 1),
UCHAR("uchar", Short::class.java, 1),
SHORT("short", Short::class.java, 2),
USHORT("ushort", Short::class.java, 2),
INT("int", Int::class.java, 4),
UINT("uint", Int::class.java, 4),
FLOAT("float", Int::class.java, 4),
DOUBLE("double", Int::class.java, 8);
companion object {
val map: MutableMap<String, PlyType>
init {
map = HashMap()
map["char"] = CHAR
map["uchar"] = UCHAR
map["short"] = SHORT
map["ushort"] = USHORT
map["int"] = INT
map["uint"] = UINT
map["float"] = FLOAT
map["double"] = DOUBLE
}
}
}
| apache-2.0 | f66a62c936dcbf7bfdfb93a27c9b2451 | 25.882353 | 120 | 0.54814 | 3.700405 | false | false | false | false |
EyeBody/EyeBody | EyeBody2/app/src/main/java/com/example/android/eyebody/gallery/ImageEditFragment.kt | 1 | 4362 | package com.example.android.eyebody.gallery
import android.app.Fragment
import android.os.Bundle
import android.util.Log
import android.view.*
import com.example.android.eyebody.R
import kotlinx.android.synthetic.main.fragment_image_edit.*
class ImageEditFragment : Fragment() {
lateinit var collage: CollageActivity
lateinit var selected: ArrayList<Photo>
var imgViewWidth: Int = 0
var imgViewHeight: Int = 0
var currentIndex: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
collage = activity as CollageActivity
selected = collage.selectedPhotoList
selected.clear()
for(s in collage.selectedIndexList){
selected.add(collage.photoList[s].copyToCacheDir(activity)) //임시 폴더로 복사
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
return inflater.inflate(R.layout.fragment_image_edit, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//selectedImageView 가로 세로 크기
selectedImage_edit.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
imgViewWidth = selectedImage_edit.measuredWidth
imgViewHeight = selectedImage_edit.measuredHeight
setImage(currentIndex) //다른거(크롭, 스티커)하다가 다시 돌아왔을 때 해당 이미지 바로 보여주기, 초기값 0
leftButton_edit.setOnClickListener {
setImage(currentIndex - 1)
}
rightButton_edit.setOnClickListener {
setImage(currentIndex + 1)
}
cropButton.setOnClickListener {
//ImageCropFragment로 교체
var imageCropFragment = ImageCropFragment()
var bundle = Bundle()
bundle.putInt("idx", currentIndex)
imageCropFragment.arguments = bundle
fragmentManager
.beginTransaction()
.replace(R.id.fragment_container, imageCropFragment)
.addToBackStack(null)
.commit()
}
rotationButton.setOnClickListener {
selected[currentIndex].rotationImage(90f)
selectedImage_edit.setImageBitmap(selected[currentIndex].getBitmap(imgViewWidth, imgViewHeight))
}
stickerButton.setOnClickListener {
//스티커 붙이기
//https://github.com/niravkalola/Android-StickerView
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.menu_image_edit, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_image_collage -> {
//회전 저장
//ImageCollageFragment로 교체
var imageCollageFragment = ImageSaveFragment()
fragmentManager
.beginTransaction()
.replace(R.id.fragment_container, imageCollageFragment)
.addToBackStack(null)
.commit()
}
}
return super.onOptionsItemSelected(item)
}
fun setImage(pos: Int){
try {
//좌우 넘기기 버튼
leftButton_edit.visibility = View.VISIBLE
rightButton_edit.visibility = View.VISIBLE
if (pos == 0) { //이전 사진이 없는 경우
leftButton_edit.visibility = View.INVISIBLE
}
if (pos == selected.size - 1) { //이후 사진이 없는 경우
rightButton_edit.visibility = View.INVISIBLE
}
//이미지와 현재 인덱스 변경
selectedImage_edit.setImageBitmap(selected[pos].getBitmap(imgViewWidth, imgViewHeight))
imageIndexTextView.text = (pos + 1).toString() + "/" + selected.size
currentIndex = pos
} catch (e: Exception){
Log.e("ImageEditFragment", "out of index") //버튼 빠르게 누르면 OutOfIndex 에러 발생
}
}
} | mit | 1a690b083ea00b0eda5da09c9e48404b | 32.427419 | 115 | 0.615106 | 4.470334 | false | false | false | false |
xfournet/intellij-community | python/src/com/jetbrains/python/codeInsight/completion/PyCompletionUtils.kt | 1 | 2940 | /*
* 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.codeInsight.completion
import com.intellij.codeInsight.TailType
import com.intellij.codeInsight.completion.AutoCompletionContext
import com.intellij.codeInsight.completion.AutoCompletionDecision
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.codeInsight.lookup.TailTypeDecorator
import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil
import com.jetbrains.python.psi.AccessDirection
import com.jetbrains.python.psi.PyClass
import com.jetbrains.python.psi.PyFunction
import com.jetbrains.python.psi.PyTypedElement
import com.jetbrains.python.psi.resolve.PyResolveContext
import com.jetbrains.python.psi.types.PyType
import com.jetbrains.python.psi.types.TypeEvalContext
import icons.PythonIcons
/**
* Various utils for custom completions
*/
/**
* Implementation of CompletionContributor#handleAutoCompletionPossibility
*
* auto-insert the obvious only case; else show other cases.
*/
fun autoInsertSingleItem(context: AutoCompletionContext) =
if (context.items.size == 1) {
AutoCompletionDecision.insertItem(context.items.first())!!
}
else {
AutoCompletionDecision.SHOW_LOOKUP!!
}
fun CompletionParameters.getPyClass() = (ScopeUtil.getScopeOwner(position) as? PyFunction)?.containingClass
fun CompletionParameters.getFile() = (ScopeUtil.getScopeOwner(position) as? PyFunction)?.containingFile
fun CompletionParameters.getTypeEvalContext() = TypeEvalContext.codeCompletion(originalFile.project, originalFile)
/**
* Add method completion to to result.
* @param result destination
* @param element if provided will check if method does not exist already
* @param builderPostprocessor function to be used to tune lookup builder
*/
fun addMethodToResult(result: CompletionResultSet,
element: PyTypedElement?,
typeEvalContext: TypeEvalContext,
methodName: String,
methodParentheses: String = "(self)",
builderPostprocessor: ((LookupElementBuilder) -> LookupElementBuilder)? = null) {
val type = if (element != null) typeEvalContext.getType(element) else null
if (type != null) {
val resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(typeEvalContext)
if (type.resolveMember(methodName, null, AccessDirection.READ, resolveContext)?.firstOrNull()?.element != null) {
return
}
}
val item = LookupElementBuilder.create(methodName + methodParentheses)
.withIcon(PythonIcons.Python.Nodes.Cyan_dot)
result.addElement(TailTypeDecorator.withTail(builderPostprocessor?.invoke(item) ?: item, TailType.CASE_COLON))
} | apache-2.0 | 90c0889cdcfb0c3030f41d10f79b88c0 | 39.847222 | 140 | 0.77381 | 4.711538 | false | false | false | false |
JavaEden/OrchidCore | plugins/OrchidPresentations/src/main/kotlin/com/eden/orchid/presentations/model/Slide.kt | 1 | 776 | package com.eden.orchid.presentations.model
import com.eden.orchid.api.resources.resource.OrchidResource
class Slide(val slideContent: OrchidResource, order: Int) {
private val slideOrderRegex = "(\\d+)-(.*)"
val order: Int
val id: String
init {
val resourcePath = slideContent.reference.path
val regex = slideOrderRegex.toRegex().matchEntire(resourcePath)
if(regex != null) {
this.order = Integer.parseInt(regex.groups[1]!!.value)
this.id = regex.groups[2]!!.value
}
else {
this.order = order
this.id = slideContent.reference.originalFileName
}
}
val content: String
get() {
return slideContent.compileContent(null)
}
}
| mit | c1ca9274473e9801e9f57e2aecfa7027 | 24.866667 | 71 | 0.610825 | 4.311111 | false | false | false | false |
eugeis/ee-schkola | ee-schkola_des/src/main/kotlin/ee/schkola/SchkolaModel.kt | 1 | 6906 | package ee.schkola
import ee.design.*
import ee.lang.*
object Schkola : Comp({ artifact("ee-schkola").namespace("ee.schkola") }) {
object Person : Module() {
object PersonName : Basic() {
val first = propS()
val last = propS()
}
object Profile : Entity() {
val gender = prop(Gender)
val name = prop(PersonName)
val birthName = propS()
val birthday = propDT()
val address = prop(Address)
val contact = prop(Contact)
val photoData = prop(n.Blob)
val photo = propS()
val family = prop(Family)
val church = prop(ChurchInfo)
val education = prop(Education)
//val findByName = findBy(name)
val findByEmail = findBy(contact.sub { email })
val findByPhone = findBy(contact.sub { phone })
}
object Church : Entity() {
val name = propS()
val address = prop(Address)
val pastor = prop(PersonName)
val contact = prop(Contact)
val association = propS()
}
object Education : Basic() {
val graduation = prop(Graduation)
val other = propS()
val profession = propS()
}
object ChurchInfo : Basic() {
val church = propS()
val member = propB()
val services = prop(n.String)
}
object Family : Basic() {
val maritalState = prop(MaritalState)
val childrenCount = propI()
val partner = prop(PersonName)
}
object Address : Basic() {
val street = propS()
val suite = propS()
val city = propS()
val code = propS()
val country = propS()
}
object Contact : Basic() {
val phone = propS()
val email = propS()
val cellphone = propS()
}
object Gender : EnumType() {
val Unknown = lit()
val Male = lit()
val Female = lit()
}
object MaritalState : EnumType() {
val Unknown = lit()
val Single = lit()
val Married = lit()
val Separated = lit()
val Divorced = lit()
val Widowed = lit()
}
object GraduationLevel : EnumType() {
val Unknown = lit()
val MiddleSchool = lit { doc("Hauptschule") }
val SecondarySchool = lit { doc("Realschule") }
val HighSchool = lit { doc("Abitur") }
val TechnicalCollege = lit { doc("Fachschule") }
val College = lit { doc("Hochschule") }
}
object Graduation : Entity() {
val name = propS()
val level = prop(GraduationLevel)
}
}
object Finance : Module() {
object Expense : Entity() {
val purpose = prop(ExpensePurpose)
val amount = propF()
val profile = prop(Person.Profile)
val date = propDT()
}
object ExpensePurpose : Entity() {
val name = propS()
val description = propS()
}
object Fee : Entity() {
val student = prop(Person.Profile)
val amount = propF { doc("Negative values are charge a fee and positive values are paying of it.") }
val kind = prop(FeeKind)
val date = propDT { doc("Deadline of a fee or paying date of it.") }
}
object FeeKind : Entity() {
val name = propS()
val amount = propF()
val description = propS()
}
}
object Student : Module() {
object SchoolApplication : Entity() {
val profile = prop(Person.Profile)
val churchContactPerson = prop(Person.PersonName)
val churchContact = prop(Person.Contact)
val churchCommitment = propB { doc("Do the responsible parties agree?") }
val schoolYear = prop(SchoolYear)
val group = propS()
}
object SchoolYear : Entity() {
val name = propS()
val start = propDT()
val end = propDT()
val dates = prop(n.List.GT(n.Date))
}
object Course : Entity() {
val name = propS()
val begin = propDT()
val end = propDT()
val teacher = prop(Person.PersonName)
val schoolYear = prop(SchoolYear)
val fee = propF()
val description = prop(n.Text)
}
object GroupCategory : EnumType() {
val CourseGroup = lit()
val YearGroup = lit()
}
object AttendanceState : EnumType() {
val Registered = lit()
val Confirmed = lit()
val Canceled = lit()
val Present = lit()
}
object Group : Entity() {
val name = propS { nullable(false) }
val category = prop(GroupCategory)
val schoolYear = prop(SchoolYear)
val representative = prop(Person.Profile)
val students = prop(n.List.GT(Person.Profile))
val courses = prop(n.List.GT(Course))
}
object Grade : Entity() {
val student = prop { type(Person.Profile).nullable(false) }
val course = prop { type(Course).nullable(false) }
val grade = propF()
val comment = propS()
}
object Attendance : Entity() {
val student = prop { type(Person.Profile).nullable(false) }
val date = propDT { nullable(false) }
val course = prop { type(Course).nullable(false) }
val hours = propI()
val state = prop(AttendanceState)
val token = propS()
val register = createBy(student, course, p(state, { value(AttendanceState.Registered) }))
val confirm = updateBy(p(state, { value(AttendanceState.Confirmed) }))
val cancel = updateBy(p(state, { value(AttendanceState.Canceled) }))
}
}
object Library : Module() {
object Location : Basic() {
val shelf = propS()
val fold = propS()
}
object Book : Entity() {
val title = propS { nullable(false) }
val description = prop(n.Text)
val language = propS()
val releaseDate = propDT()
val edition = propS()
val category = propS()
val author = prop(Person.PersonName)
val location = prop(Location)
val findByTitle = findBy(title)
//val findByAuthor = findBy(author)
val findByPattern = findBy(p("pattern"))
//val changeLocation = updateBy(location)
}
}
}
| apache-2.0 | 24b33aedd946284a360d6b0a95638fac | 29.693333 | 112 | 0.50391 | 4.631791 | false | false | false | false |
elifarley/kotlin-examples | src/com/github/elifarley/kotlin/textfile/DailyTextImexKit.kt | 2 | 1942 | package com.orgecc.util.textfile
import com.orgecc.util.DateTimeKit
import com.orgecc.util.DateTimeKit.format
import com.orgecc.util.io.IOWithDigest.MDReader
import com.orgecc.util.io.IOWithDigest.MDWriter
import com.orgecc.util.logger
import com.orgecc.util.persistence.toConvertedArrayParams
import java.nio.file.Path
import java.time.LocalDate
import java.util.*
/**
* Created by elifarley on 25/11/16.
*/
fun String.addDateTimeSequence(date: Date, seq: Int) = this +
"${DateTimeKit.DATE_FORMATTER.format(date)}-$seq.txt"
open class DailyTextImexConfig(val reportName: String, val lineLength: Int) {
open val fixedLineCount: Int = 2
open val fixedLinesAreVirtual = false
}
abstract class DailyTextImporterConfig(
reportName: String,
lineLength: Int,
val useNewReader: (streamName: String, filePath: Path, block: (MDReader) -> Unit) -> Unit
): DailyTextImexConfig(reportName,lineLength)
abstract class DailyTextExporterConfig<in I: Any, out E: Any>(
reportName: String,
lineLength: Int,
val listQuery: String,
val useNewWriter: (streamName: String, filePath: Path, block: (MDWriter) -> Unit) -> Unit
): DailyTextImexConfig(reportName,lineLength) {
abstract fun toObject(rs: I): E
}
data class NextDailyImexParams(val nextSequence: Int, val startDate: LocalDate, val endDate: LocalDate) {
val queryParams: Array<Any?> = toConvertedArrayParams(listOf(startDate, endDate))
init {
if (startDate != endDate) {
val deltaInDays = (endDate.toEpochDay() - startDate.toEpochDay()).toInt()
val log = logger(this.javaClass)
when {
deltaInDays > 0 -> log.warn("[init] {} days in range [{}, {}] ", deltaInDays + 1, startDate, endDate)
deltaInDays < 0 -> log.error("[init] {} days in NEGATIVE range [{}, {}]", -deltaInDays + 1, startDate, endDate)
}
}
}
}
| mit | 7c63c683d6dbeb51bad1a6d183075054 | 32.482759 | 127 | 0.681771 | 3.727447 | false | true | false | false |
toastkidjp/Yobidashi_kt | app/src/main/java/jp/toastkid/yobidashi/libs/intent/SettingsIntentFactory.kt | 2 | 1080 | package jp.toastkid.yobidashi.libs.intent
import android.content.Intent
import android.provider.Settings
/**
* Settings intent factory.
* @author toastkidjp
*/
class SettingsIntentFactory {
/**
* Make launch settings intent.
* @return [Intent]
*/
fun makeLaunch() = Intent(Settings.ACTION_SETTINGS)
/**
* Make launch Wi-Fi settings intent.
* @return [Intent]
*/
fun wifi() = Intent(Settings.ACTION_WIFI_SETTINGS)
/**
* Make launch wireless settings intent.
* @return [Intent]
*/
fun wireless() = Intent(Settings.ACTION_WIRELESS_SETTINGS)
/**
* Make launch all apps settings intent.
* @return [Intent]
*/
fun allApps() = Intent(Settings.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS)
/**
* Make launch Date and Time settings intent.
* @return [Intent]
*/
fun dateAndTime() = Intent(Settings.ACTION_DATE_SETTINGS)
/**
* Make launch display settings intent.
* @return [Intent]
*/
fun display() = Intent(Settings.ACTION_DISPLAY_SETTINGS)
}
| epl-1.0 | beebc9a6e214710608e7f72c89b62229 | 21.5 | 76 | 0.633333 | 4.044944 | false | false | false | false |
mistraltechnologies/smogen | src/main/kotlin/com/mistraltech/smogen/plugin/MatcherGeneratorOptionsDialog.kt | 1 | 2321 | package com.mistraltech.smogen.plugin
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiClass
import com.mistraltech.smogen.codegenerator.matchergenerator.MatcherGeneratorProperties
import javax.swing.JComponent
class MatcherGeneratorOptionsDialog(
override val project: Project,
override val matchedClass: PsiClass,
override val candidateRoots: List<VirtualFile>,
private val generatorProperties: MatcherGeneratorProperties
) : DialogWrapper(project), MatcherGeneratorOptionsPanelDataSource {
override val recentsKey: String = "MatcherGeneratorOptionsDialog.RecentsKey"
private val matcherGeneratorOptionsPanel: MatcherGeneratorOptionsPanel
override fun doOKAction() {
super.doOKAction()
val sourceRoot = matcherGeneratorOptionsPanel.selectedSourceRoot
generatorProperties.setClassName(matcherGeneratorOptionsPanel.selectedClassName)
.setFactoryMethodPrefix(if (matcherGeneratorOptionsPanel.isAn) "an" else "a")
.setExtensible(matcherGeneratorOptionsPanel.isMakeExtensible)
.setMatcherSuperClassName(matcherGeneratorOptionsPanel.superClassName)
.setPackageName(matcherGeneratorOptionsPanel.selectedPackageName)
.setGenerateInterface(matcherGeneratorOptionsPanel.isGenerateInterface)
.setSourceRoot(sourceRoot)
}
override fun doValidate(): ValidationInfo? {
val validationInfo = matcherGeneratorOptionsPanel.doValidate()
return validationInfo ?: super.doValidate()
}
override fun createCenterPanel(): JComponent {
return matcherGeneratorOptionsPanel.root
}
override val packageName: String
get() = generatorProperties.packageName!!
override val defaultClassName: String
get() = generatorProperties.className!!
override val defaultRoot: VirtualFile
get() = generatorProperties.sourceRoot!!
override val defaultIsExtensible: Boolean
get() = generatorProperties.isExtensible
init {
isModal = true
title = "Generate Matcher"
matcherGeneratorOptionsPanel = MatcherGeneratorOptionsPanel(this)
init()
}
}
| bsd-3-clause | 9fb165e771a1e7e717e4f0875158fc41 | 37.683333 | 89 | 0.76131 | 5.52619 | false | false | false | false |
outadoc/Twistoast-android | twistoast/src/main/kotlin/fr/outadev/twistoast/FragmentWebView.kt | 1 | 6773 | /*
* Twistoast - FragmentWebView.kt
* Copyright (C) 2013-2016 Baptiste Candellier
*
* Twistoast 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.
*
* Twistoast 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 fr.outadev.twistoast
import android.app.Fragment
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.view.*
import android.webkit.WebView
import android.webkit.WebViewClient
/**
* A fragment that contains a webview and its controls.
* Will automatically inject some JS in the pages to make their title disappear, for cosmetic reasons.
*/
class FragmentWebView : Fragment() {
private var webView: WebView? = null
private var itemRefresh: MenuItem? = null
private var itemCancel: MenuItem? = null
private var urlToOpen: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
if (webView == null) {
webView = TwistoastWebView(activity)
if (arguments.containsKey("url")) {
// Load a classic URL
loadUrl(arguments.getString("url"))
} else if (arguments.containsKey("twitter_username")) {
// Load a Twitter profile
loadTwitterTimeline(arguments.getString("twitter_username"))
}
}
/*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(true);
}*/
return webView
}
private fun loadTwitterTimeline(username: String) {
// Load a twitter profile page by injecting the username into some HTML that will be loaded
// by the webview
urlToOpen = "https://twitter.com/$username"
val twitterHtmlWrapper = """<html><body><a class="twitter-timeline" href="https://twitter.com/$username">""" +
"""Tweets by TwistoCaen</a> """ +
"""<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script></body></html>"""
webView?.loadData(twitterHtmlWrapper, "text/html", "utf-8")
}
private fun loadUrl(url: String) {
webView?.loadUrl(url)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.webview, menu)
itemRefresh = menu.findItem(R.id.action_refresh_page)
itemCancel = menu.findItem(R.id.action_cancel_refresh)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle presses on the action bar items
when (item.itemId) {
R.id.action_refresh_page -> {
webView?.reload()
return true
}
R.id.action_cancel_refresh -> {
webView?.stopLoading()
return true
}
R.id.action_open_website -> {
if (urlToOpen == null)
return true
val i = Intent(Intent.ACTION_VIEW)
i.data = Uri.parse(urlToOpen)
startActivity(i)
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
val canGoBack: Boolean
get() = webView!!.canGoBack()
fun goBack() {
webView?.goBack()
}
/**
* A custom webview with event listeners and custom settings.
*/
private inner class TwistoastWebView
constructor(context: Context) : WebView(context) {
val headers = mapOf(Pair("X-Requested-With", "com.actigraph.twisto.tabbarapp"))
init {
setWebViewClient(object : WebViewClient() {
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
// Hide refresh button while refreshing
itemRefresh?.isVisible = false
itemCancel?.isVisible = true
}
override fun onPageFinished(view: WebView, url: String) {
super.onPageFinished(view, url)
// Hide cancel button when done refreshing
itemRefresh?.isVisible = true
itemCancel?.isVisible = false
// Load some javascript that will hide the stuff we don't want on the page
view.loadUrl("""javascript: var a = document.getElementsByClassName("title-div");""")
view.loadUrl("""javascript: var b = document.getElementsByClassName("contenu");""")
view.loadUrl("javascript:" + Uri.encode("for(var i = a.length-1; i >= 0; i--) { " +
"(b[0] != null) ? b[0].removeChild(a[i]) : document.body.removeChild(a[i]); }"))
}
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
if (Regex("^https?:").find(url) != null) {
urlToOpen = url
}
// Intercept page load so that we can inject our own X-Requested-With header
// because the Twisto website checks to see if it's coming from their own app
// (and as you can see it's useless as hell)
view.loadUrl(url, headers)
return true
}
})
settings.builtInZoomControls = true
settings.displayZoomControls = false
settings.javaScriptEnabled = true
}
override fun loadUrl(url: String) {
super.loadUrl(url, headers)
// If this is a http or https URL, remember it
// so that we can open it in a browser later on if needed
if (Regex("^https?:").find(url) != null) {
urlToOpen = url
}
}
}
}
| gpl-3.0 | bdc383068c8aed2c788a40eed4bd7e6b | 34.835979 | 121 | 0.591318 | 4.796742 | false | false | false | false |
vitoling/HiWeather | src/main/kotlin/com/vito/work/weather/dto/ForecastWeather.kt | 1 | 1112 | package com.vito.work.weather.dto
import java.sql.Date
import java.sql.Timestamp
import java.time.LocalDateTime
import javax.persistence.*
/**
* Created by lingzhiyuan.
* Date : 16/4/10.
* Time : 下午9:30.
* Description:
*
*/
@Entity
@Table(name = "weather_forecast")
data class ForecastWeather(
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
var id: Long = 0L,
var district: Long = 0L,
var date: Date = Date(0),
var max: Int = 0,
var min: Int = 0,
@Column(length = 10)
var weather_day: String = "",
@Column(length = 10)
var weather_night: String = "",
var wind_direction_day: Int = 0,
var wind_direction_night: Int = 0,
@Column(length = 10)
var wind_force_day: String = "",
@Column(length = 10)
var wind_force_night: String = "",
@Column(length = 10)
var sunrise: String = "",
@Column(length = 10)
var sunset: String = "",
var update_time: Timestamp = Timestamp.valueOf(LocalDateTime.now())
) | gpl-3.0 | a35e15c58e33fbc8be069b01a0828e83 | 25.404762 | 75 | 0.564982 | 3.705686 | false | false | false | false |
aewhite/intellij-eclipse-collections-plugin | src/net/andrewewhite/eclipse/collections/intellij/plugin/inspections/PreferIsNotEmptyInspection.kt | 1 | 2959 | package net.andrewewhite.eclipse.collections.intellij.plugin.inspections
import com.intellij.codeInspection.*
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.*
import com.intellij.psi.JavaTokenType.EXCL
import com.intellij.psi.codeStyle.CodeStyleManager
import com.intellij.psi.codeStyle.JavaCodeStyleManager
/**
* Created by awhite on 1/6/17.
*/
class PreferIsNotEmptyInspection: BaseJavaBatchLocalInspectionTool() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
if (!isEclipseCollectionsBeingUsed(holder)) { return PsiElementVisitor.EMPTY_VISITOR }
return PreferIsNotEmptyInspection.Visitor(holder, isOnTheFly)
}
class Visitor(val holder: ProblemsHolder, val onTheFly: Boolean) : JavaElementVisitor() {
override fun visitPrefixExpression(expression: PsiPrefixExpression) {
super.visitPrefixExpression(expression)
//TODO Add support for detecting cases like list.size() != 0 and list.size() > 0
if (isNegationExpression(expression)) { return }
val methodCall = expression.operand as? PsiMethodCallExpression ?: return
val methodExpression = methodCall.methodExpression
val sourceElement = methodExpression.firstChild ?: return
if (methodExpression.referenceName != "isEmpty") { return }
if (!classSupportsNotEmpty(methodCall)) return
holder.registerProblem(
expression,
"Should use asLazy to avoid intermediate collections",
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
TextRange.create(0, expression.textRange.length),
IsNotEmptyQuickFix(sourceElement))
}
private fun classSupportsNotEmpty(methodCall: PsiMethodCallExpression): Boolean {
val resolvedMethodCall = methodCall.resolveMethod() ?: return true
val containingClass = resolvedMethodCall.containingClass ?: return true
if (containingClass.findMethodsByName("notEmpty", true).isEmpty()) {
return false
}
return true
}
private fun isNegationExpression(expression: PsiPrefixExpression) = expression.operationTokenType != EXCL
}
}
class IsNotEmptyQuickFix(val sourceElement: PsiElement) : LocalQuickFix {
override fun getFamilyName(): String = "Use notEmpty"
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.getPsiElement()
val elementFactory = JavaPsiFacade.getElementFactory(element.getProject())
element.replace(elementFactory.createExpressionFromText(sourceElement.text + ".notEmpty()", element))
CodeStyleManager.getInstance(project).reformat(JavaCodeStyleManager.getInstance(project).shortenClassReferences(element))
}
}
| mit | 591ff160154ea312a9ed15936a629aa3 | 43.164179 | 129 | 0.710375 | 5.614801 | false | false | false | false |
rcgroot/adb-awake | studio/app/src/main/java/nl/renedegroot/android/adbawake/businessmodel/Service.kt | 1 | 2996 | /*------------------------------------------------------------------------------
** Author: René de Groot
** Copyright: (c) 2017 René de Groot All Rights Reserved.
**------------------------------------------------------------------------------
** No part of this file may be reproduced
** or transmitted in any form or by any
** means, electronic or mechanical, for the
** purpose, without the express written
** permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of "Stay-awake on adb".
*
* "Stay-awake on adb" 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.
*
* "Stay-awake on adb" 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 "Stay-awake on adb". If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.renedegroot.android.adbawake.businessmodel
import android.service.notification.NotificationListenerService
import android.service.notification.StatusBarNotification
import nl.renedegroot.android.adbawake.Application
import nl.renedegroot.android.adbawake.providers.SystemTextProvider
import javax.inject.Inject
class Service : NotificationListenerService() {
@Inject
lateinit var lockControl: LockControl
@Inject
lateinit var preferences: Preferences
@Inject
lateinit var systemTextProvider: SystemTextProvider
override fun onCreate() {
super.onCreate()
Application.appComponent.inject(this)
}
override fun onDestroy() {
super.onDestroy()
lockControl.enableWakelock(this, false)
}
override fun onNotificationPosted(sbn: StatusBarNotification?) {
handleNotification(sbn, true)
}
override fun onNotificationRemoved(sbn: StatusBarNotification?) {
handleNotification(sbn, false)
}
private fun handleNotification(sbn: StatusBarNotification?, isAdded: Boolean) {
if (sbn == null) {
return
}
val enabled = preferences.isServiceEnabled(this)
val match = matchesADBNotification(sbn)
if (enabled && match) {
lockControl.enableWakelock(this, isAdded)
}
}
private fun matchesADBNotification(sbn: StatusBarNotification): Boolean {
val systemText = systemTextProvider.getSystemText("adb_active_notification_title")
return when (sbn.notification.tickerText) {
systemText, "USB debugging connected", "USB-foutopsporing verbonden" -> true
else -> false
}
}
}
| gpl-3.0 | 5f79b3a822d4f29e2bcc93f8535a267b | 34.642857 | 90 | 0.645959 | 4.892157 | false | false | false | false |
prfarlow1/nytc-meet | app/src/main/kotlin/org/needhamtrack/nytc/screens/event/editmark/EditMarkPresenter.kt | 1 | 2686 | package org.needhamtrack.nytc.screens.event.editmark
import org.needhamtrack.nytc.base.BasePresenter
import org.needhamtrack.nytc.base.PresenterConfiguration
import org.needhamtrack.nytc.models.AttemptResult
import org.needhamtrack.nytc.models.Fraction
import org.needhamtrack.nytc.models.Mark
class EditMarkPresenter(view: EditMarkContract.View, configuration: PresenterConfiguration) : BasePresenter<EditMarkContract.View>(view, configuration), EditMarkContract.Presenter {
private var fraction = Fraction.ZERO
private var feet = -1
private var inches = -1
private var attemptResult: AttemptResult = AttemptResult.ValidMark(null)
override fun onFractionSelected(position: Int) {
when (position) {
0 -> fraction = Fraction.ZERO
1 -> fraction = Fraction.ONE_QUARTER
2 -> fraction = Fraction.HALF
3 -> fraction = Fraction.THREE_QUARTERS
}
}
override fun onValidClick() {
view?.setInputsEnabled(true)
attemptResult = AttemptResult.ValidMark(null)
}
override fun onFoulClick() {
view?.setInputsEnabled(false)
attemptResult = AttemptResult.Foul
}
override fun onNoMarkClick() {
view?.setInputsEnabled(false)
attemptResult = AttemptResult.NoMark
}
override fun onSaveClick(rawFeet: String, rawInches: String) {
when (attemptResult) {
is AttemptResult.ValidMark -> {
feet = try {
rawFeet.toInt()
} catch (nfe: NumberFormatException) {
-1
}
inches = try {
rawInches.toInt()
} catch (nfe: NumberFormatException) {
-1
}
if (feet < 0 && inches < 0) {
if (fraction == Fraction.ZERO) {
view?.displayNoMarkError()
} else {
view?.displayInvalidFeetAndInchesError()
}
} else if (feet < 0 && inches >= 0) {
view?.displayInvalidFeetError()
} else if (feet >= 0 && inches < 0) {
view?.displayInvalidInchesError()
} else {
attemptResult = AttemptResult.ValidMark(Mark(feet, inches, fraction))
view?.saveAndClose(attemptResult)
}
}
is AttemptResult.Foul -> {
view?.saveAndClose(attemptResult)
}
is AttemptResult.NoMark -> {
view?.saveAndClose(attemptResult)
}
}
}
} | mit | aff41eea7d2dd1069e8eb73183ea039f | 33.896104 | 181 | 0.559568 | 4.91042 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.