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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ccampo133/NBodyJS | src/main/kotlin/me/ccampo/nbody/model/SimulationContext.kt | 1 | 1971 | package me.ccampo.nbody.model
import me.ccampo.nbody.util.gravityAcceleration
import me.ccampo.nbody.util.isWayOutOfBounds
import me.ccampo.nbody.util.verlet
/**
* Runs an n-body gravity simulation using Verlet integration.
*
* @param dt The timestep
* @param initBodies The set of initial bodies
* @param width The simulation area width
* @param height The simulation area height
* @param nPos The number of historical positions to track, per body
* @param nOld The number of old bodies to track after they've been removed (collided, escaped, etc)
*/
class SimulationContext(
val dt: Double,
val initBodies: Set<Body> = emptySet<Body>(),
val width: Int = 100,
val height: Int = 100,
val nPos: Int = 0,
val nOld: Int = 0) {
var bodies = initBodies
private set
var removedBodies: List<Body> = listOf()
private set
/**
* Move the simulation forward one timestep.
*/
fun run() {
// Remove bodies that collide or are WAY out of bounds (to preserve resources)
val bodiesToRemove = bodies.filter { b ->
isWayOutOfBounds(b.x.x, b.x.y, width, height) || (bodies - b).any { b.isCollision(it) }
}
bodies -= bodiesToRemove
// Keep only the last "nOld" removed bodies
removedBodies = (removedBodies + bodiesToRemove).takeLast(nOld)
// Update the positions of all bodies using the "Velocity Verlet" algorithm
// and exclude the current body from the acceleration calculation.
bodies = bodies.map {
val (x, v) = verlet(it.x, it.v, dt, { pos -> gravityAcceleration(pos, bodies - it) })
Body(it.m, it.r, x, v, (it.positions + x).takeLast(nPos))
}.toSet()
}
fun clear() {
removedBodies = listOf()
bodies = emptySet()
}
fun reset() {
removedBodies = listOf()
bodies = initBodies
}
fun clearPositionHistory() {
bodies = bodies.map { it.copy(positions = emptyList()) }.toSet()
}
fun addBody(body: Body) {
bodies += body
}
}
| mit | 1a4b2eff42636c9880cdf2721e9d76c3 | 27.157143 | 100 | 0.666159 | 3.670391 | false | false | false | false |
d9n/intellij-rust | src/main/kotlin/org/rust/ide/inspections/RsMissingElseInspection.kt | 1 | 2015 | package org.rust.ide.inspections
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import org.rust.ide.inspections.fixes.SubstituteTextFix
import org.rust.lang.core.psi.RsExprStmt
import org.rust.lang.core.psi.RsIfExpr
import org.rust.lang.core.psi.RsVisitor
import org.rust.lang.core.rightSiblings
/**
* Checks for potentially missing `else`s.
* A partial analogue of Clippy's suspicious_else_formatting.
* QuickFix: Change to `else if`
*/
class RsMissingElseInspection : RsLocalInspectionTool() {
override fun getDisplayName() = "Missing else"
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) =
object : RsVisitor() {
override fun visitExprStmt(expr: RsExprStmt) {
val firstIf = expr.extractIf() ?: return
val nextIf = expr.rightSiblings
.dropWhile { (it is PsiWhiteSpace || it is PsiComment) && '\n' !in it.text }
.firstOrNull()
.extractIf() ?: return
val condition = nextIf.condition ?: return
val rangeStart = expr.startOffsetInParent + firstIf.textLength
val rangeLen = condition.expr.textRange.startOffset - firstIf.textRange.startOffset - firstIf.textLength
val fixRange = TextRange(nextIf.textRange.startOffset, nextIf.textRange.startOffset)
holder.registerProblem(
expr.parent,
TextRange(rangeStart, rangeStart + rangeLen),
"Suspicious if. Did you mean `else if`?",
SubstituteTextFix(expr.containingFile, fixRange, "else ", "Change to `else if`"))
}
}
private fun PsiElement?.extractIf(): RsIfExpr? = when (this) {
is RsIfExpr -> this
is RsExprStmt -> firstChild.extractIf()
else -> null
}
}
| mit | 85fe298aae735e1ca91894146fe68422 | 41.87234 | 120 | 0.653598 | 4.579545 | false | false | false | false |
sinnerschrader/account-tool | src/main/kotlin/com/sinnerschrader/s2b/accounttool/presentation/interceptor/LdapConnectionInterceptor.kt | 1 | 2012 | package com.sinnerschrader.s2b.accounttool.presentation.interceptor
import com.sinnerschrader.s2b.accounttool.config.WebConstants
import com.sinnerschrader.s2b.accounttool.config.ldap.LdapConfiguration
import com.sinnerschrader.s2b.accounttool.presentation.RequestUtils.currentUserDetails
import com.sinnerschrader.s2b.accounttool.presentation.RequestUtils.getLdapConnection
import com.sinnerschrader.s2b.accounttool.presentation.RequestUtils.setLdapConnection
import com.unboundid.ldap.sdk.LDAPConnection
import com.unboundid.ldap.sdk.LDAPException
import com.unboundid.ldap.sdk.ResultCode.SUCCESS
import org.springframework.web.servlet.ModelAndView
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
class LdapConnectionInterceptor(private val ldapConfiguration: LdapConfiguration) : HandlerInterceptorAdapter() {
@Throws(Exception::class)
override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
currentUserDetails?.apply {
var connection: LDAPConnection? = null
try {
connection = ldapConfiguration.createConnection()
with(connection.bind(dn, password)) {
if (resultCode === SUCCESS) setLdapConnection(request, connection)
}
} catch (le: LDAPException) {
connection?.close()
request.session.invalidate()
return false
}
}
return true
}
@Throws(Exception::class)
override fun postHandle(request: HttpServletRequest, response: HttpServletResponse,
handler: Any, modelAndView: ModelAndView?) {
getLdapConnection(request)?.close()
request.removeAttribute(WebConstants.ATTR_CONNECTION)
currentUserDetails?.let {
modelAndView?.addObject("currentUser", it)
}
}
}
| mit | c074e1960eebb17b2c9ef5e9399673b4 | 42.73913 | 113 | 0.723161 | 4.943489 | false | true | false | false |
tag-them/metoothanks | app/src/main/java/org/itiswednesday/metoothanks/CanvasView.kt | 1 | 6177 | package org.itiswednesday.metoothanks
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.os.SystemClock
import android.support.v7.widget.Toolbar
import android.util.AttributeSet
import android.view.MenuItem
import android.view.MotionEvent
import android.view.View
import org.itiswednesday.metoothanks.activities.Edit
import org.itiswednesday.metoothanks.items.Image
import org.itiswednesday.metoothanks.items.Item
import org.itiswednesday.metoothanks.items.Text
import java.io.Serializable
import android.graphics.DashPathEffect
const val CORNER_RADIUS = 25f
const val EDGE_WIDTH = 10f
class CanvasView : View, Serializable {
private var selectedItem: Item? = null
private val items = ArrayList<Item>()
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
private val framePaint = Paint().apply {
style = Paint.Style.STROKE
strokeWidth = EDGE_WIDTH
color = fetchColor(context, R.attr.colorPrimary)
pathEffect = DashPathEffect(floatArrayOf(50f, 50f), 0f)
}
override fun onDraw(canvas: Canvas) {
items.forEach {
it.draw(canvas)
}
if (selectedItem != null)
canvas.drawRoundRect(selectedItem!!.bounds, CORNER_RADIUS, CORNER_RADIUS, framePaint)
}
fun addImage(bitmap: Bitmap, center: Boolean = false) =
// fitBitmap – resizing the image in case it's bigger than the screen
Image(fitBitmap(bitmap, width, height), hostView = this).apply {
if (center)
move([email protected] / 2 - this.width / 2,
[email protected] / 2 - this.height / 2)
}.addToItems()
fun addText(text: String) = Text(text, width, hostView = this).addToItems()
// if a touch is registered less than 101 milliseconds
// since the last touch, it will be treated as a drag/slide
private val MAX_ELAPSED_TIME_TO_DRAG = 100
// last time the canvas was touched with one pointer
private var prevMoveTouchTime = SystemClock.elapsedRealtime()
// last time the canvas was touched with two pointers
private var prevResizeTouchTime = SystemClock.elapsedRealtime()
// the distance between the X coordinate of the pointer and the item's left edge (used for dragging)
private var gripDistanceFromLeftEdge = 0
// the distance between the Y coordinate of the pointer and the item's top edge (used for dragging)
private var gripDistanceFromTopEdge = 0
// pointers' coordinates at the beginning of a resize
private var pointersGrip = PointPair({ Point() })
// bounds value at the beginning of the resize
private var originalBounds = RectF()
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent?): Boolean {
if (event == null) return false
val pointerCount = event.pointerCount
when (pointerCount) {
1 -> {
val x = event.x.toInt()
val y = event.y.toInt()
// looking for a picture that got touched;
// since the first pictures in the array get drawn first,
// we iterate over the array from its end in order to get the
// furthest picture (picture in the front)
for (item in items.reversed()) {
if (SystemClock.elapsedRealtime() -
prevMoveTouchTime < MAX_ELAPSED_TIME_TO_DRAG && selectedItem != null)
selectedItem?.move(
x - gripDistanceFromLeftEdge, y - gripDistanceFromTopEdge)
else {
selectNone()
if (item.touched(x, y)) {
gripDistanceFromLeftEdge = x - item.left
gripDistanceFromTopEdge = y - item.top
item.select()
}
}
prevMoveTouchTime = SystemClock.elapsedRealtime()
}
}
2 -> {
if (SystemClock.elapsedRealtime() -
prevResizeTouchTime < MAX_ELAPSED_TIME_TO_DRAG) {
val pointers = PointPair(
init = { Point(event.getX(it).toInt(), event.getY(it).toInt()) })
selectedItem?.resize(pointers, pointersGrip, originalBounds)
} else {
pointersGrip = PointPair {
Point(event.getX(it).toInt(), event.getY(it).toInt())
}
selectedItem?.let { originalBounds = it.bounds }
}
prevResizeTouchTime = SystemClock.elapsedRealtime()
}
}
invalidate()
return true
}
private fun Item.select() {
selectedItem = this
val clickListener = { item: MenuItem ->
when (item.itemId) {
R.id.action_item_delete -> selectedItem!!.removeFromItems()
R.id.action_item_move_forward -> items.swapWithNextItem(selectedItem!!)
R.id.action_item_move_backward -> items.swapWithPrevItem(selectedItem!!)
else -> handleMenuItemClick(item)
}
true
}
with(itemToolbar) {
menu.clear()
inflateMenu(R.menu.item_menu)
inflateMenu(itemMenuID)
setOnMenuItemClickListener(clickListener)
visibility = Toolbar.VISIBLE
}
invalidate()
}
fun selectNone() {
selectedItem = null
itemToolbar.menu.clear()
}
private fun Item.addToItems() {
items.add(this)
this.select()
invalidate()
}
private fun Item.removeFromItems() {
items.remove(this)
selectNone()
invalidate()
}
private val itemToolbar
get() = (context as Edit).findViewById<Toolbar>(R.id.item_toolbar)
} | mpl-2.0 | ad77fac94fb89a604c23a339b2629332 | 32.565217 | 104 | 0.590445 | 4.80919 | false | false | false | false |
soywiz/korge | korge/src/jvmMain/kotlin/com/soywiz/korge/GLCanvasKorge.kt | 1 | 2320 | package com.soywiz.korge
import com.soywiz.korge.view.*
import com.soywiz.korgw.awt.*
import com.soywiz.korio.async.*
import kotlinx.coroutines.*
import java.io.*
class GLCanvasKorge private constructor(
val dummy: Boolean,
val canvas: GLCanvas,
val virtualWidth: Int?,
val virtualHeight: Int?
) : Closeable {
val gameWindow = GLCanvasGameWindow(canvas)
lateinit var stage: Stage
val views get() = stage.views
val injector get() = views.injector
private suspend fun init() {
//val deferred = CompletableDeferred<Stage>()
//val context = coroutineContext
//println("[a]")
println("GLCanvasKorge.init[a]: ${Thread.currentThread()}")
Thread {
println("GLCanvasKorge.init[b]: ${Thread.currentThread()}")
runBlocking {
println("GLCanvasKorge.init[c]: ${Thread.currentThread()}")
Korge(width = canvas.width, height = canvas.height, virtualWidth = virtualWidth ?: canvas.width, virtualHeight = virtualHeight ?: canvas.height, gameWindow = gameWindow) {
println("GLCanvasKorge.init[d]: ${Thread.currentThread()}")
//println("[A]")
[email protected] = this@Korge
//deferred.complete(this@Korge)
//println("[B]")
}
}
}.start()
println("GLCanvasKorge.init[e]: ${Thread.currentThread()}")
//println("[b]")
while (!::stage.isInitialized) delay(1L)
println("GLCanvasKorge.init[f]: ${Thread.currentThread()}")
//[email protected] = deferred.await()
//println("[c]")
}
suspend fun executeInContext(block: suspend Stage.() -> Unit) {
withContext(stage.coroutineContext) {
block(stage)
}
}
fun launchInContext(block: suspend Stage.() -> Unit) {
launchImmediately(stage.coroutineContext) {
block(stage)
}
}
override fun close() {
gameWindow.exit()
}
companion object {
suspend operator fun invoke(canvas: GLCanvas, virtualWidth: Int? = null, virtualHeight: Int? = null): GLCanvasKorge {
return GLCanvasKorge(true, canvas, virtualWidth, virtualHeight).apply { init() }
}
}
}
| apache-2.0 | a03b22fe27ab406732d53d638d9c9fae | 33.626866 | 187 | 0.596121 | 4.328358 | false | false | false | false |
Orchextra/orchextra-android-sdk | indoorpositioning/src/test/java/com/gigigo/orchextra/indoorpositioning/FakeIPDbDataSource.kt | 1 | 2280 | /*
* Created by Orchextra
*
* Copyright (C) 2017 Gigigo Mobile Services SL
*
* 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.gigigo.orchextra.indoorpositioning
import com.gigigo.orchextra.core.domain.entities.IndoorPositionConfig
import com.gigigo.orchextra.indoorpositioning.domain.datasource.IPDbDataSource
import com.gigigo.orchextra.indoorpositioning.domain.models.OxBeacon
import com.gigigo.orchextra.indoorpositioning.utils.extensions.getValue
import java.util.*
class FakeIPDbDataSource : IPDbDataSource {
private val beaconDb = mutableListOf<OxBeacon>()
private var positionConfig: List<IndoorPositionConfig> = emptyList()
init {
beaconDb.add(SAVED_BEACON)
beaconDb.add(SAVED_OLD_BEACON)
}
override fun saveConfig(config: List<IndoorPositionConfig>) {
positionConfig = config
}
override fun getConfig(): List<IndoorPositionConfig> {
return positionConfig
}
override fun getBeacon(id: String): OxBeacon? {
beaconDb.map { if (id == it.getValue()) return it }
return null
}
override fun getBeacons(): List<OxBeacon> = beaconDb
override fun saveOrUpdateBeacon(beacon: OxBeacon) {
beaconDb.add(beacon)
}
override fun removeBeacon(id: String) {
val beacon = getBeacon(id)
if (beacon != null) {
beaconDb.remove(beacon)
}
}
companion object {
val SAVED_BEACON = OxBeacon(
uuid = "test_uuid",
minor = 4,
major = 9,
lastDetection = Date()
)
val SAVED_OLD_BEACON = OxBeacon(
uuid = "test_uuid_old",
minor = 5,
major = 10,
lastDetection = Date(50 * 1000)
)
}
} | apache-2.0 | 4d677e68ea6bc30c7d9ffaf45c8f88bf | 28.24359 | 78 | 0.666667 | 4.160584 | false | true | false | false |
vondear/RxTools | RxUI/src/main/java/com/tamsiree/rxui/view/RxRotateTool.kt | 1 | 1461 | package com.tamsiree.rxui.view
import android.graphics.PointF
/**
* @author tamsiree
*/
object RxRotateTool {
const val CIRCLE_ANGLE = 2 * Math.PI
fun getRotateAngle(p1: PointF, p2: PointF, mPointCenter: PointF): Double {
val q1 = getQuadrant(p1, mPointCenter)
val q2 = getQuadrant(p2, mPointCenter)
val angle1 = getAngle(p1, mPointCenter)
val angle2 = getAngle(p2, mPointCenter)
return if (q1 == q2) {
angle1 - angle2
} else {
0.00
}
}
fun getAngle(p: PointF, mPointCenter: PointF): Double {
val x = p.x - mPointCenter.x
val y = mPointCenter.y - p.y
val angle = Math.atan(y / x.toDouble())
return getNormalizedAngle(angle)
}
fun getQuadrant(p: PointF, mPointCenter: PointF): Int {
val x = p.x
val y = p.y
if (x > mPointCenter.x) {
if (y > mPointCenter.y) {
return 4
} else if (y < mPointCenter.y) {
return 1
}
} else if (x < mPointCenter.x) {
if (y > mPointCenter.y) {
return 3
} else if (y < mPointCenter.y) {
return 2
}
}
return -1
}
fun getNormalizedAngle(angle: Double): Double {
var angle = angle
while (angle < 0) {
angle += CIRCLE_ANGLE
}
return angle % CIRCLE_ANGLE
}
} | apache-2.0 | 530955ccdf9d08d513bf9487d60a6524 | 25.581818 | 78 | 0.5154 | 3.784974 | false | false | false | false |
reimersjc/code-kata-02 | src/main/kotlin/com/dasreimers/codekata/IterativeChop.kt | 1 | 526 | package com.dasreimers.codekata
/**
* Traditional iterative binary search.
*/
class IterativeChop : Chop {
override fun chop(key: Int, array: IntArray): Int {
var low = 0
var high = array.size - 1
while (low <= high) {
val mid = (low + high) / 2
if (key < array[mid]) {
high = mid -1
} else if (key > array[mid]) {
low = mid + 1
} else {
return mid
}
}
return -1
}
} | apache-2.0 | edf8113e13076d1972060434fe4adb73 | 21.913043 | 55 | 0.444867 | 3.925373 | false | false | false | false |
yuzumone/Raid | app/src/main/kotlin/net/yuzumone/raid/PrefActivity.kt | 1 | 2852 | package net.yuzumone.raid
import android.content.Context
import android.content.Intent
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.app.AppCompatActivity
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import com.google.firebase.messaging.FirebaseMessaging
import net.yuzumone.raid.databinding.FragmentPrefBinding
import net.yuzumone.raid.util.PrefUtil
class PrefActivity : AppCompatActivity() {
companion object {
fun createIntent(context: Context) {
val intent = Intent(context, PrefActivity::class.java)
context.startActivity(intent)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
val fragment = PrefFragment()
supportFragmentManager.beginTransaction().add(android.R.id.content, fragment).commit()
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
android.R.id.home -> {
finish()
return true
}
}
return super.onOptionsItemSelected(item)
}
class PrefFragment : Fragment() {
lateinit private var binding: FragmentPrefBinding
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_pref, container, false)
val prefs = PrefUtil(activity)
binding.morioka.title.text = getString(R.string.morioka)
binding.morioka.checkbox.isChecked = prefs.isMoriokaNotification
binding.takizawa.title.text = getString(R.string.takizawa)
binding.takizawa.checkbox.isChecked = prefs.isTakizawaNotification
binding.buttonSave.setOnClickListener {
prefs.isMoriokaNotification = binding.morioka.checkbox.isChecked
prefs.isTakizawaNotification = binding.takizawa.checkbox.isChecked
if (binding.morioka.checkbox.isChecked) {
FirebaseMessaging.getInstance().subscribeToTopic("morioka")
} else {
FirebaseMessaging.getInstance().unsubscribeFromTopic("morioka")
}
if (binding.takizawa.checkbox.isChecked) {
FirebaseMessaging.getInstance().subscribeToTopic("takizawa")
} else {
FirebaseMessaging.getInstance().unsubscribeFromTopic("takizawa")
}
activity.finish()
}
return binding.root
}
}
} | apache-2.0 | ce20d1665a69c18a0e28cdb257b4cf1c | 38.082192 | 97 | 0.656732 | 4.986014 | false | false | false | false |
stripe/stripe-android | payments-ui-core/src/main/java/com/stripe/android/ui/core/elements/SaveForFutureUseElementUI.kt | 1 | 1127 | package com.stripe.android.ui.core.elements
import androidx.annotation.RestrictTo
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
const val SAVE_FOR_FUTURE_CHECKBOX_TEST_TAG = "SAVE_FOR_FUTURE_CHECKBOX_TEST_TAG"
@Composable
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun SaveForFutureUseElementUI(
enabled: Boolean,
element: SaveForFutureUseElement,
modifier: Modifier = Modifier,
) {
val controller = element.controller
val checked by controller.saveForFutureUse.collectAsState(true)
val label by controller.label.collectAsState(null)
val resources = LocalContext.current.resources
CheckboxElementUI(
automationTestTag = SAVE_FOR_FUTURE_CHECKBOX_TEST_TAG,
isChecked = checked,
label = label?.let { resources.getString(it, element.merchantName) },
isEnabled = enabled,
modifier = modifier,
onValueChange = {
controller.onValueChange(!checked)
},
)
}
| mit | 573d26792a55865b6a7de96159ef9161 | 32.147059 | 81 | 0.747116 | 4.368217 | false | true | false | false |
stripe/stripe-android | example/src/main/java/com/stripe/example/adapter/SourcesAdapter.kt | 1 | 2107 | package com.stripe.example.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.stripe.android.model.Source
import com.stripe.android.model.SourceTypeModel
import com.stripe.example.databinding.SourcesListItemBinding
internal class SourcesAdapter : RecyclerView.Adapter<SourcesAdapter.ViewHolder>() {
private val sources: MutableList<Source> = mutableListOf()
init {
setHasStableIds(true)
notifyDataSetChanged()
}
internal class ViewHolder(
private val viewBinding: SourcesListItemBinding
) : RecyclerView.ViewHolder(viewBinding.root) {
fun bind(source: Source) {
viewBinding.status.text = source.status?.toString()
viewBinding.redirectStatus.text = getRedirectStatus(source)
viewBinding.sourceId.text = source.id?.let { sourceId ->
sourceId.substring(sourceId.length - 6)
}
viewBinding.sourceType.text = if (Source.SourceType.THREE_D_SECURE == source.type) {
"3DS"
} else {
source.type
}
}
private fun getRedirectStatus(source: Source): String? {
return source.redirect?.status?.toString()
?: (source.sourceTypeModel as SourceTypeModel.Card).threeDSecureStatus.toString()
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
SourcesListItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(sources[position])
}
override fun getItemCount(): Int {
return sources.size
}
override fun getItemId(position: Int): Long {
return sources[position].id.orEmpty().hashCode().toLong()
}
fun addSource(source: Source) {
sources.add(0, source)
notifyItemInserted(0)
}
}
| mit | ab29347b87df03f882653a4b8898a816 | 30.924242 | 97 | 0.641671 | 4.946009 | false | false | false | false |
stripe/stripe-android | payments-ui-core/src/main/java/com/stripe/android/ui/core/FormUI.kt | 1 | 4775 | package com.stripe.android.ui.core
import androidx.annotation.RestrictTo
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import com.stripe.android.ui.core.elements.AffirmElementUI
import com.stripe.android.ui.core.elements.AffirmHeaderElement
import com.stripe.android.ui.core.elements.AfterpayClearpayElementUI
import com.stripe.android.ui.core.elements.AfterpayClearpayHeaderElement
import com.stripe.android.ui.core.elements.AuBecsDebitMandateElementUI
import com.stripe.android.ui.core.elements.AuBecsDebitMandateTextElement
import com.stripe.android.ui.core.elements.BsbElement
import com.stripe.android.ui.core.elements.BsbElementUI
import com.stripe.android.ui.core.elements.CardDetailsSectionElement
import com.stripe.android.ui.core.elements.CardDetailsSectionElementUI
import com.stripe.android.ui.core.elements.EmptyFormElement
import com.stripe.android.ui.core.elements.FormElement
import com.stripe.android.ui.core.elements.IdentifierSpec
import com.stripe.android.ui.core.elements.MandateTextElement
import com.stripe.android.ui.core.elements.MandateTextUI
import com.stripe.android.ui.core.elements.OTPElement
import com.stripe.android.ui.core.elements.OTPElementUI
import com.stripe.android.ui.core.elements.SaveForFutureUseElement
import com.stripe.android.ui.core.elements.SaveForFutureUseElementUI
import com.stripe.android.ui.core.elements.SectionElement
import com.stripe.android.ui.core.elements.SectionElementUI
import com.stripe.android.ui.core.elements.StaticTextElement
import com.stripe.android.ui.core.elements.StaticTextElementUI
import kotlinx.coroutines.flow.Flow
@Composable
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun FormUI(
hiddenIdentifiersFlow: Flow<Set<IdentifierSpec>>,
enabledFlow: Flow<Boolean>,
elementsFlow: Flow<List<FormElement>?>,
lastTextFieldIdentifierFlow: Flow<IdentifierSpec?>,
loadingComposable: @Composable ColumnScope.() -> Unit,
modifier: Modifier = Modifier
) {
val hiddenIdentifiers by hiddenIdentifiersFlow.collectAsState(emptySet())
val enabled by enabledFlow.collectAsState(true)
val elements by elementsFlow.collectAsState(null)
val lastTextFieldIdentifier by lastTextFieldIdentifierFlow.collectAsState(null)
FormUI(
hiddenIdentifiers = hiddenIdentifiers,
enabled = enabled,
elements = elements,
lastTextFieldIdentifier = lastTextFieldIdentifier,
loadingComposable = loadingComposable,
modifier = modifier
)
}
@Composable
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun FormUI(
hiddenIdentifiers: Set<IdentifierSpec>,
enabled: Boolean,
elements: List<FormElement>?,
lastTextFieldIdentifier: IdentifierSpec?,
loadingComposable: @Composable ColumnScope.() -> Unit,
modifier: Modifier = Modifier
) {
Column(
modifier = modifier.fillMaxWidth(1f)
) {
elements?.let {
it.forEachIndexed { _, element ->
if (!hiddenIdentifiers.contains(element.identifier)) {
when (element) {
is SectionElement -> SectionElementUI(
enabled,
element,
hiddenIdentifiers,
lastTextFieldIdentifier
)
is StaticTextElement -> StaticTextElementUI(element)
is SaveForFutureUseElement -> SaveForFutureUseElementUI(enabled, element)
is AfterpayClearpayHeaderElement -> AfterpayClearpayElementUI(
enabled,
element
)
is AuBecsDebitMandateTextElement -> AuBecsDebitMandateElementUI(element)
is AffirmHeaderElement -> AffirmElementUI()
is MandateTextElement -> MandateTextUI(element)
is CardDetailsSectionElement -> CardDetailsSectionElementUI(
enabled,
element.controller,
hiddenIdentifiers,
lastTextFieldIdentifier
)
is BsbElement -> BsbElementUI(enabled, element, lastTextFieldIdentifier)
is OTPElement -> OTPElementUI(enabled, element)
is EmptyFormElement -> {}
}
}
}
} ?: loadingComposable()
}
}
| mit | fd8d22bce98b89a8596c7da059cf88e3 | 43.626168 | 97 | 0.690681 | 4.842799 | false | false | false | false |
exponent/exponent | packages/expo-modules-core/android/src/main/java/expo/modules/kotlin/modules/ModuleDefinitionBuilder.kt | 2 | 12110 | /**
* We used a function from the experimental STD API - typeOf (see kotlinlang.org/api/latest/jvm/stdlib/kotlin.reflect/type-of.html).
* We shouldn't have any problem with that function, cause it's widely used in other libraries created by JetBrains like kotlinx-serializer.
* This function is super handy if we want to receive a collection type.
* For example, it's very hard to obtain the generic parameter type from the list class.
* In plain Java, it's almost impossible. There is a trick to getting such information using something called TypeToken.
* For instance, the Gson library uses this workaround. But there still will be a problem with nullability.
* We didn't find a good solution to distinguish between List<Any?> and List<Any>.
* Mainly because from the JVM perspective it's the same type.
* That's why we used typeOf. It solves all problems described above.
*/
@file:OptIn(ExperimentalStdlibApi::class)
package expo.modules.kotlin.modules
import android.app.Activity
import android.content.Intent
import expo.modules.kotlin.Promise
import expo.modules.kotlin.events.BasicEventListener
import expo.modules.kotlin.events.EventListener
import expo.modules.kotlin.events.EventListenerWithPayload
import expo.modules.kotlin.events.EventListenerWithSenderAndPayload
import expo.modules.kotlin.events.EventName
import expo.modules.kotlin.events.EventsDefinition
import expo.modules.kotlin.events.OnActivityResultPayload
import expo.modules.kotlin.methods.AnyMethod
import expo.modules.kotlin.methods.Method
import expo.modules.kotlin.methods.PromiseMethod
import expo.modules.kotlin.types.toAnyType
import expo.modules.kotlin.views.ViewManagerDefinition
import expo.modules.kotlin.views.ViewManagerDefinitionBuilder
import kotlin.reflect.typeOf
@DefinitionMarker
class ModuleDefinitionBuilder(private val module: Module? = null) {
private var name: String? = null
private var constantsProvider = { emptyMap<String, Any?>() }
private var eventsDefinition: EventsDefinition? = null
@PublishedApi
internal var methods = mutableMapOf<String, AnyMethod>()
@PublishedApi
internal var viewManagerDefinition: ViewManagerDefinition? = null
@PublishedApi
internal val eventListeners = mutableMapOf<EventName, EventListener>()
fun build(): ModuleDefinitionData {
val moduleName = name ?: module?.javaClass?.simpleName
return ModuleDefinitionData(
requireNotNull(moduleName),
constantsProvider,
methods,
viewManagerDefinition,
eventListeners,
eventsDefinition
)
}
/**
* Sets the name of the module that is exported to the JavaScript world.
*/
fun name(name: String) {
this.name = name
}
/**
* Definition function setting the module's constants to export.
*/
fun constants(constantsProvider: () -> Map<String, Any?>) {
this.constantsProvider = constantsProvider
}
/**
* Definition of the module's constants to export.
*/
fun constants(vararg constants: Pair<String, Any?>) {
constantsProvider = { constants.toMap() }
}
@JvmName("methodWithoutArgs")
inline fun function(
name: String,
crossinline body: () -> Any?
) {
methods[name] = Method(name, arrayOf()) { body() }
}
inline fun <reified R> function(
name: String,
crossinline body: () -> R
) {
methods[name] = Method(name, arrayOf()) { body() }
}
inline fun <reified R, reified P0> function(
name: String,
crossinline body: (p0: P0) -> R
) {
methods[name] = if (P0::class == Promise::class) {
PromiseMethod(name, arrayOf()) { _, promise -> body(promise as P0) }
} else {
Method(name, arrayOf(typeOf<P0>().toAnyType())) { body(it[0] as P0) }
}
}
inline fun <reified R, reified P0, reified P1> function(
name: String,
crossinline body: (p0: P0, p1: P1) -> R
) {
methods[name] = if (P1::class == Promise::class) {
PromiseMethod(name, arrayOf(typeOf<P0>().toAnyType())) { args, promise -> body(args[0] as P0, promise as P1) }
} else {
Method(name, arrayOf(typeOf<P0>().toAnyType(), typeOf<P1>().toAnyType())) { body(it[0] as P0, it[1] as P1) }
}
}
inline fun <reified R, reified P0, reified P1, reified P2> function(
name: String,
crossinline body: (p0: P0, p1: P1, p2: P2) -> R
) {
methods[name] = if (P2::class == Promise::class) {
PromiseMethod(name, arrayOf(typeOf<P0>().toAnyType(), typeOf<P1>().toAnyType())) { args, promise -> body(args[0] as P0, args[1] as P1, promise as P2) }
} else {
Method(name, arrayOf(typeOf<P0>().toAnyType(), typeOf<P1>().toAnyType(), typeOf<P2>().toAnyType())) { body(it[0] as P0, it[1] as P1, it[2] as P2) }
}
}
inline fun <reified R, reified P0, reified P1, reified P2, reified P3> function(
name: String,
crossinline body: (p0: P0, p1: P1, p2: P2, p3: P3) -> R
) {
methods[name] = if (P3::class == Promise::class) {
PromiseMethod(name, arrayOf(typeOf<P0>().toAnyType(), typeOf<P1>().toAnyType(), typeOf<P2>().toAnyType())) { args, promise -> body(args[0] as P0, args[1] as P1, args[2] as P2, promise as P3) }
} else {
Method(name, arrayOf(typeOf<P0>().toAnyType(), typeOf<P1>().toAnyType(), typeOf<P2>().toAnyType(), typeOf<P3>().toAnyType())) { body(it[0] as P0, it[1] as P1, it[2] as P2, it[3] as P3) }
}
}
inline fun <reified R, reified P0, reified P1, reified P2, reified P3, reified P4> function(
name: String,
crossinline body: (p0: P0, p1: P1, p2: P2, p3: P3, p4: P4) -> R
) {
methods[name] = if (P4::class == Promise::class) {
PromiseMethod(name, arrayOf(typeOf<P0>().toAnyType(), typeOf<P1>().toAnyType(), typeOf<P2>().toAnyType(), typeOf<P3>().toAnyType())) { args, promise -> body(args[0] as P0, args[1] as P1, args[2] as P2, args[3] as P3, promise as P4) }
} else {
Method(name, arrayOf(typeOf<P0>().toAnyType(), typeOf<P1>().toAnyType(), typeOf<P2>().toAnyType(), typeOf<P3>().toAnyType(), typeOf<P4>().toAnyType())) { body(it[0] as P0, it[1] as P1, it[2] as P2, it[3] as P3, it[4] as P4) }
}
}
inline fun <reified R, reified P0, reified P1, reified P2, reified P3, reified P4, reified P5> function(
name: String,
crossinline body: (p0: P0, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5) -> R
) {
methods[name] = if (P5::class == Promise::class) {
PromiseMethod(name, arrayOf(typeOf<P0>().toAnyType(), typeOf<P1>().toAnyType(), typeOf<P2>().toAnyType(), typeOf<P3>().toAnyType(), typeOf<P4>().toAnyType())) { args, promise -> body(args[0] as P0, args[1] as P1, args[2] as P2, args[3] as P3, args[4] as P4, promise as P5) }
} else {
Method(name, arrayOf(typeOf<P0>().toAnyType(), typeOf<P1>().toAnyType(), typeOf<P2>().toAnyType(), typeOf<P3>().toAnyType(), typeOf<P4>().toAnyType(), typeOf<P5>().toAnyType())) { body(it[0] as P0, it[1] as P1, it[2] as P2, it[3] as P3, it[4] as P4, it[5] as P5) }
}
}
inline fun <reified R, reified P0, reified P1, reified P2, reified P3, reified P4, reified P5, reified P6> function(
name: String,
crossinline body: (p0: P0, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6) -> R
) {
methods[name] = if (P6::class == Promise::class) {
PromiseMethod(name, arrayOf(typeOf<P0>().toAnyType(), typeOf<P1>().toAnyType(), typeOf<P2>().toAnyType(), typeOf<P3>().toAnyType(), typeOf<P4>().toAnyType(), typeOf<P5>().toAnyType())) { args, promise -> body(args[0] as P0, args[1] as P1, args[2] as P2, args[3] as P3, args[4] as P4, args[5] as P5, promise as P6) }
} else {
Method(name, arrayOf(typeOf<P0>().toAnyType(), typeOf<P1>().toAnyType(), typeOf<P2>().toAnyType(), typeOf<P3>().toAnyType(), typeOf<P4>().toAnyType(), typeOf<P5>().toAnyType(), typeOf<P6>().toAnyType())) { body(it[0] as P0, it[1] as P1, it[2] as P2, it[3] as P3, it[4] as P4, it[5] as P5, it[6] as P6) }
}
}
inline fun <reified R, reified P0, reified P1, reified P2, reified P3, reified P4, reified P5, reified P6, reified P7> function(
name: String,
crossinline body: (p0: P0, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7) -> R
) {
methods[name] = if (P7::class == Promise::class) {
PromiseMethod(name, arrayOf(typeOf<P0>().toAnyType(), typeOf<P1>().toAnyType(), typeOf<P2>().toAnyType(), typeOf<P3>().toAnyType(), typeOf<P4>().toAnyType(), typeOf<P5>().toAnyType(), typeOf<P6>().toAnyType())) { args, promise -> body(args[0] as P0, args[1] as P1, args[2] as P2, args[3] as P3, args[4] as P4, args[5] as P5, args[6] as P6, promise as P7) }
} else {
Method(name, arrayOf(typeOf<P0>().toAnyType(), typeOf<P1>().toAnyType(), typeOf<P2>().toAnyType(), typeOf<P3>().toAnyType(), typeOf<P4>().toAnyType(), typeOf<P5>().toAnyType(), typeOf<P6>().toAnyType(), typeOf<P7>().toAnyType())) { body(it[0] as P0, it[1] as P1, it[2] as P2, it[3] as P3, it[4] as P4, it[5] as P5, it[6] as P6, it[7] as P7) }
}
}
/**
* Creates the view manager definition that scopes other view-related definitions.
*/
inline fun viewManager(body: ViewManagerDefinitionBuilder.() -> Unit) {
require(viewManagerDefinition == null) { "The module definition may have exported only one view manager." }
val viewManagerDefinitionBuilder = ViewManagerDefinitionBuilder()
body.invoke(viewManagerDefinitionBuilder)
viewManagerDefinition = viewManagerDefinitionBuilder.build()
}
/**
* Creates module's lifecycle listener that is called right after the module initialization.
*/
inline fun onCreate(crossinline body: () -> Unit) {
eventListeners[EventName.MODULE_CREATE] = BasicEventListener(EventName.MODULE_CREATE) { body() }
}
/**
* Creates module's lifecycle listener that is called when the module is about to be deallocated.
*/
inline fun onDestroy(crossinline body: () -> Unit) {
eventListeners[EventName.MODULE_DESTROY] = BasicEventListener(EventName.MODULE_DESTROY) { body() }
}
/**
* Creates module's lifecycle listener that is called right after the activity is resumed.
*/
inline fun onActivityEntersForeground(crossinline body: () -> Unit) {
eventListeners[EventName.ACTIVITY_ENTERS_FOREGROUND] = BasicEventListener(EventName.ACTIVITY_ENTERS_FOREGROUND) { body() }
}
/**
* Creates module's lifecycle listener that is called right after the activity is paused.
*/
inline fun onActivityEntersBackground(crossinline body: () -> Unit) {
eventListeners[EventName.ACTIVITY_ENTERS_BACKGROUND] = BasicEventListener(EventName.ACTIVITY_ENTERS_BACKGROUND) { body() }
}
/**
* Creates module's lifecycle listener that is called right after the activity is destroyed.
*/
inline fun onActivityDestroys(crossinline body: () -> Unit) {
eventListeners[EventName.ACTIVITY_DESTROYS] = BasicEventListener(EventName.ACTIVITY_DESTROYS) { body() }
}
/**
* Defines event names that this module can send to JavaScript.
*/
fun events(vararg events: String) {
eventsDefinition = EventsDefinition(events)
}
/**
* Creates module's lifecycle listener that is called right after the first event listener is added.
*/
inline fun onStartObserving(crossinline body: () -> Unit) {
function("startObserving", body)
}
/**
* Creates module's lifecycle listener that is called right after all event listeners are removed.
*/
inline fun onStopObserving(crossinline body: () -> Unit) {
function("stopObserving", body)
}
/**
* Creates module's lifecycle listener that is called right after the new intent was received.
*/
inline fun onNewIntent(crossinline body: (Intent) -> Unit) {
eventListeners[EventName.ON_NEW_INTENT] = EventListenerWithPayload<Intent>(EventName.ON_NEW_INTENT) { body(it) }
}
/**
* Creates module's lifecycle listener that is called right after the activity has received a result.
*/
inline fun onActivityResult(crossinline body: (Activity, OnActivityResultPayload) -> Unit) {
eventListeners[EventName.ON_ACTIVITY_RESULT] =
EventListenerWithSenderAndPayload<Activity, OnActivityResultPayload>(EventName.ON_ACTIVITY_RESULT) { sender, payload -> body(sender, payload) }
}
}
| bsd-3-clause | d6f62691a778a8f8830205511abca160 | 44.355805 | 362 | 0.677704 | 3.454079 | false | false | false | false |
peterLaurence/TrekAdvisor | app/src/main/java/com/peterlaurence/trekme/util/encrypt/AES.kt | 1 | 1777 | package com.peterlaurence.trekme.util.encrypt
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
private val keyValue = toByte("0161E6E45E4A09DFC14D47B41DE04006408B82C4EE087CBD710C3D5B3086FE51")
private val key = SecretKeySpec(keyValue, "AES")
private const val HEX = "0123456789ABCDEF"
private const val initVector = "encryptionIntVec"
val iv = IvParameterSpec(initVector.toByteArray())
@Throws(Exception::class)
fun String.encrypt(): String {
val result = encrypt(toByteArray())
return toHex(result)
}
@Throws(Exception::class)
fun String.decrypt(): String {
val enc = toByte(this)
val result = decrypt(enc)
return String(result)
}
@Throws(Exception::class)
private fun encrypt(clear: ByteArray): ByteArray {
val cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING")
cipher.init(Cipher.ENCRYPT_MODE, key, iv)
return cipher.doFinal(clear)
}
@Throws(Exception::class)
private fun decrypt(encrypted: ByteArray): ByteArray {
val cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING")
cipher.init(Cipher.DECRYPT_MODE, key, iv)
return cipher.doFinal(encrypted)
}
fun toByte(hexString: String): ByteArray {
val len = hexString.length / 2
val result = ByteArray(len)
for (i in 0 until len)
result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
16).toByte()
return result
}
fun toHex(buf: ByteArray?): String {
if (buf == null)
return ""
val result = StringBuffer(2 * buf.size)
for (i in buf.indices) {
appendHex(result, buf[i])
}
return result.toString()
}
private fun appendHex(sb: StringBuffer, b: Byte) {
sb.append(HEX[(b.toInt() shr 4) and 0x0f]).append(HEX[b.toInt() and 0x0f])
} | gpl-3.0 | 238e1beb4e7531b68c40b37a3e5bcabc | 27.222222 | 97 | 0.703995 | 3.430502 | false | false | false | false |
AndroidX/androidx | wear/watchface/watchface-style/src/main/java/androidx/wear/watchface/style/CurrentUserStyleRepository.kt | 3 | 30893 | /*
* 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.wear.watchface.style
import android.content.res.Resources
import android.content.res.XmlResourceParser
import android.graphics.drawable.Icon
import android.os.Build
import androidx.annotation.RestrictTo
import androidx.wear.watchface.complications.IllegalNodeException
import androidx.wear.watchface.complications.iterate
import androidx.wear.watchface.style.UserStyleSetting.ComplicationSlotsUserStyleSetting.ComplicationSlotsOption
import androidx.wear.watchface.style.UserStyleSetting.Option
import androidx.wear.watchface.style.data.UserStyleSchemaWireFormat
import androidx.wear.watchface.style.data.UserStyleWireFormat
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.DataInputStream
import java.io.DataOutputStream
import java.io.IOException
import java.io.OutputStream
import java.security.DigestOutputStream
import java.security.MessageDigest
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import org.xmlpull.v1.XmlPullParserException
/**
* An immutable representation of user style choices that maps each [UserStyleSetting] to
* [UserStyleSetting.Option].
*
* This is intended for use by the WatchFace and entries are the same as the ones specified in
* the [UserStyleSchema]. This means you can't serialize a UserStyle directly, instead you need
* to use a [UserStyleData] (see [toUserStyleData]).
*
* To modify the user style, you should call [toMutableUserStyle] and construct a new [UserStyle]
* instance with [MutableUserStyle.toUserStyle].
*
* @param selectedOptions The [UserStyleSetting.Option] selected for each [UserStyleSetting]
* @param copySelectedOptions Whether to create a copy of the provided [selectedOptions]. If
* `false`, no mutable copy of the [selectedOptions] map should be retained outside this class.
*/
public class UserStyle private constructor(
selectedOptions: Map<UserStyleSetting, UserStyleSetting.Option>,
copySelectedOptions: Boolean
) : Map<UserStyleSetting, UserStyleSetting.Option> {
private val selectedOptions =
if (copySelectedOptions) HashMap(selectedOptions) else selectedOptions
/**
* Constructs a copy of the [UserStyle]. It is backed by the same map.
*/
public constructor(userStyle: UserStyle) : this(userStyle.selectedOptions, false)
/**
* Constructs a [UserStyle] with the given selected options for each setting.
*
* A copy of the [selectedOptions] map will be created, so that changed to the map will not be
* reflected by this object.
*/
public constructor(
selectedOptions: Map<UserStyleSetting, UserStyleSetting.Option>
) : this(selectedOptions, true)
/** Constructs this UserStyle from data serialized to a [ByteArray] by [toByteArray]. */
internal constructor(
byteArray: ByteArray,
styleSchema: UserStyleSchema
) : this(
UserStyleData(
HashMap<String, ByteArray>().apply {
val bais = ByteArrayInputStream(byteArray)
val reader = DataInputStream(bais)
val numKeys = reader.readInt()
for (i in 0 until numKeys) {
val key = reader.readUTF()
val numBytes = reader.readInt()
val value = ByteArray(numBytes)
reader.read(value, 0, numBytes)
put(key, value)
}
reader.close()
bais.close()
}
),
styleSchema
)
/** The number of entries in the style. */
override val size: Int by selectedOptions::size
/**
* Constructs a [UserStyle] from a [UserStyleData] and the [UserStyleSchema]. Unrecognized
* style settings will be ignored. Unlisted style settings will be initialized with that
* setting's default option.
*
* @param userStyle The [UserStyle] represented as a [UserStyleData].
* @param styleSchema The [UserStyleSchema] for this UserStyle, describes how we interpret
* [userStyle].
*/
@Suppress("Deprecation") // userStyleSettings
public constructor(
userStyle: UserStyleData,
styleSchema: UserStyleSchema
) : this(
HashMap<UserStyleSetting, UserStyleSetting.Option>().apply {
for (styleSetting in styleSchema.userStyleSettings) {
val option = userStyle.userStyleMap[styleSetting.id.value]
if (option != null) {
this[styleSetting] = styleSetting.getSettingOptionForId(option)
} else {
this[styleSetting] = styleSetting.defaultOption
}
}
}
)
/** @hide */
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public fun toWireFormat(): UserStyleWireFormat = UserStyleWireFormat(toMap())
/** Returns the style as a [UserStyleData]. */
public fun toUserStyleData(): UserStyleData = UserStyleData(toMap())
/** Returns a mutable instance initialized with the same mapping. */
public fun toMutableUserStyle(): MutableUserStyle = MutableUserStyle(this)
/** Returns the style as a [Map]<[String], [ByteArray]>. */
private fun toMap(): Map<String, ByteArray> =
selectedOptions.entries.associate { it.key.id.value to it.value.id.value }
/** Returns the style encoded as a [ByteArray]. */
internal fun toByteArray(): ByteArray {
val baos = ByteArrayOutputStream()
val writer = DataOutputStream(baos)
writer.writeInt(selectedOptions.size)
for ((key, value) in selectedOptions) {
writer.writeUTF(key.id.value)
writer.writeInt(value.id.value.size)
writer.write(value.id.value, 0, value.id.value.size)
}
writer.close()
baos.close()
val ba = baos.toByteArray()
return ba
}
/** Returns the [UserStyleSetting.Option] for [key] if there is one or `null` otherwise. */
public override operator fun get(key: UserStyleSetting): UserStyleSetting.Option? =
selectedOptions[key]
/**
* Returns the [UserStyleSetting.Option] for [settingId] if there is one or `null` otherwise.
* Note this is an O(n) operation.
*/
public operator fun get(settingId: UserStyleSetting.Id): UserStyleSetting.Option? =
selectedOptions.firstNotNullOfOrNull { if (it.key.id == settingId) it.value else null }
override fun toString(): String =
"UserStyle[" + selectedOptions.entries.joinToString(
transform = { "${it.key.id} -> ${it.value}" }
) + "]"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as UserStyle
if (selectedOptions != other.selectedOptions) return false
return true
}
override fun hashCode(): Int {
return selectedOptions.hashCode()
}
internal companion object {
/**
* Merges the content of [overrides] with [base].
*
* This function merges the content of [base] by overriding any setting that is in [base]
* with the corresponding options from [overrides].
*
* Any setting in [overrides] that is not set in [base] will be ignored. Any setting that is
* not present in [overrides] but it is in [base] will be kept unmodified.
*
* Returns the merged [UserStyle] or null if the merged [UserStyle] is not different from
* [base], i.e., if applying the [overrides] does not change any of the [base] settings.
*/
@JvmStatic
internal fun merge(base: UserStyle, overrides: UserStyle): UserStyle? {
// Created only if there are changes to apply.
var merged: MutableUserStyle? = null
for ((setting, option) in overrides.selectedOptions) {
// Ignore an unrecognized setting.
val currentOption = base[setting] ?: continue
if (currentOption != option) {
merged = merged ?: base.toMutableUserStyle()
merged[setting] = option
}
}
return merged?.toUserStyle()
}
}
override val entries: Set<Map.Entry<UserStyleSetting, UserStyleSetting.Option>>
get() = selectedOptions.entries
override val keys: Set<UserStyleSetting>
get() = selectedOptions.keys
override val values: Collection<UserStyleSetting.Option>
get() = selectedOptions.values
override fun containsKey(key: UserStyleSetting): Boolean = selectedOptions.containsKey(key)
override fun containsValue(value: UserStyleSetting.Option): Boolean =
selectedOptions.containsValue(value)
override fun isEmpty(): Boolean = selectedOptions.isEmpty()
}
/**
* A mutable [UserStyle]. This must be converted back to a [UserStyle] by calling [toUserStyle].
*/
public class MutableUserStyle internal constructor(userStyle: UserStyle) :
Iterable<Map.Entry<UserStyleSetting, UserStyleSetting.Option>> {
/** The map from the available settings and the selected option. */
private val selectedOptions = HashMap<UserStyleSetting, UserStyleSetting.Option>().apply {
for ((setting, option) in userStyle) {
this[setting] = option
}
}
/** The number of entries in the style. */
val size: Int get() = selectedOptions.size
/** Iterator over the elements of the user style. */
override fun iterator(): Iterator<Map.Entry<UserStyleSetting, UserStyleSetting.Option>> =
selectedOptions.iterator()
/** Returns the [UserStyleSetting.Option] for [setting] if there is one or `null` otherwise. */
public operator fun get(setting: UserStyleSetting): UserStyleSetting.Option? =
selectedOptions[setting]
/**
* Returns the [UserStyleSetting.Option] for [settingId] if there is one or `null` otherwise.
* Note this is an O(n) operation.
*/
public operator fun get(settingId: UserStyleSetting.Id): UserStyleSetting.Option? =
selectedOptions.firstNotNullOfOrNull { if (it.key.id == settingId) it.value else null }
/**
* Sets the [UserStyleSetting.Option] for [setting] to the given [option].
*
* @param setting The [UserStyleSetting] we're setting the [option] for, must be in the schema.
* @param option the [UserStyleSetting.Option] we're setting. Must be a valid option for
* [setting].
* @throws IllegalArgumentException if [setting] is not in the schema or if [option] is invalid
* for [setting].
*/
public operator fun set(setting: UserStyleSetting, option: UserStyleSetting.Option) {
require(selectedOptions.containsKey(setting)) { "Unknown setting $setting" }
require(option.getUserStyleSettingClass() == setting::class.java) {
"The option class (${option::class.java.canonicalName}) must match the setting class " +
setting::class.java.canonicalName
}
selectedOptions[setting] = option
}
/**
* Sets the [UserStyleSetting.Option] for the setting with the given [settingId] to the given
* [option].
*
* @param settingId The [UserStyleSetting.Id] of the [UserStyleSetting] we're setting the
* [option] for, must be in the schema.
* @param option the [UserStyleSetting.Option] we're setting. Must be a valid option for
* [settingId].
* @throws IllegalArgumentException if [settingId] is not in the schema or if [option] is
* invalid for [settingId].
*/
public operator fun set(settingId: UserStyleSetting.Id, option: UserStyleSetting.Option) {
val setting = getSettingForId(settingId)
require(setting != null) { "Unknown setting $settingId" }
require(option.getUserStyleSettingClass() == setting::class.java) {
"The option must be a subclass of the setting"
}
selectedOptions[setting] = option
}
/**
* Sets the [UserStyleSetting.Option] for [setting] to the option with the given [optionId].
*
* @param setting The [UserStyleSetting] we're setting the [optionId] for, must be in the
* schema.
* @param optionId the [UserStyleSetting.Option.Id] for the [UserStyleSetting.Option] we're
* setting.
* @throws IllegalArgumentException if [setting] is not in the schema or if [optionId] is
* unrecognized.
*/
public operator fun set(setting: UserStyleSetting, optionId: UserStyleSetting.Option.Id) {
require(selectedOptions.containsKey(setting)) { "Unknown setting $setting" }
val option = getOptionForId(setting, optionId)
require(option != null) { "Unrecognized optionId $optionId" }
selectedOptions[setting] = option
}
/**
* Sets the [UserStyleSetting.Option] for the setting with the given [settingId] to the option
* with the given [optionId].
* @throws IllegalArgumentException if [settingId] is not in the schema or if [optionId] is
* unrecognized.
*/
public operator fun set(settingId: UserStyleSetting.Id, optionId: UserStyleSetting.Option.Id) {
val setting = getSettingForId(settingId)
require(setting != null) { "Unknown setting $settingId" }
val option = getOptionForId(setting, optionId)
require(option != null) { "Unrecognized optionId $optionId" }
selectedOptions[setting] = option
}
/** Converts this instance to an immutable [UserStyle] with the same mapping. */
public fun toUserStyle(): UserStyle = UserStyle(selectedOptions)
private fun getSettingForId(settingId: UserStyleSetting.Id): UserStyleSetting? {
for (setting in selectedOptions.keys) {
if (setting.id == settingId) {
return setting
}
}
return null
}
private fun getOptionForId(
setting: UserStyleSetting,
optionId: UserStyleSetting.Option.Id
): UserStyleSetting.Option? {
for (option in setting.options) {
if (option.id == optionId) {
return option
}
}
return null
}
override fun toString(): String =
"MutableUserStyle[" + selectedOptions.entries.joinToString(
transform = { "${it.key.id} -> ${it.value}" }
) + "]"
}
/**
* A form of [UserStyle] which is easy to serialize. This is intended for use by the watch face
* clients and the editor where we can't practically use [UserStyle] due to its limitations.
*/
public class UserStyleData(
public val userStyleMap: Map<String, ByteArray>
) {
/** @hide */
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public constructor(
userStyle: UserStyleWireFormat
) : this(userStyle.mUserStyle)
override fun toString(): String = "{" + userStyleMap.entries.joinToString(
transform = {
try {
it.key + "=" + it.value.decodeToString()
} catch (e: Exception) {
it.key + "=" + it.value
}
}
) + "}"
/** @hide */
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public fun toWireFormat(): UserStyleWireFormat = UserStyleWireFormat(userStyleMap)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as UserStyleData
// Check if references are the same.
if (userStyleMap == other.userStyleMap) return true
// Check if contents are the same.
if (userStyleMap.size != other.userStyleMap.size) return false
for ((key, value) in userStyleMap) {
val otherValue = other.userStyleMap[key] ?: return false
if (!otherValue.contentEquals(value)) return false
}
return true
}
override fun hashCode(): Int {
return userStyleMap.hashCode()
}
}
/**
* Describes the list of [UserStyleSetting]s the user can configure. Note style schemas can be
* hierarchical (see [UserStyleSetting.Option.childSettings]), editors should use
* [rootUserStyleSettings] rather than [userStyleSettings] for populating the top level UI.
*
* @param userStyleSettings The user configurable style categories associated with this watch face.
* Empty if the watch face doesn't support user styling. Note we allow at most one
* [UserStyleSetting.CustomValueUserStyleSetting] in the list. Prior to android T ot most one
* [UserStyleSetting.ComplicationSlotsUserStyleSetting] is allowed, however from android T it's
* possible with hierarchical styles for there to be more than one, but at most one can be active at
* any given time.
*/
public class UserStyleSchema constructor(
userStyleSettings: List<UserStyleSetting>
) {
public val userStyleSettings = userStyleSettings
@Deprecated("use rootUserStyleSettings instead")
get
/** For use with hierarchical schemas, lists all the settings with no parent [Option]. */
public val rootUserStyleSettings by lazy {
userStyleSettings.filter { !it.hasParent }
}
/** @hide */
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
companion object {
@Throws(IOException::class, XmlPullParserException::class)
fun inflate(
resources: Resources,
parser: XmlResourceParser,
complicationScaleX: Float,
complicationScaleY: Float
): UserStyleSchema {
require(parser.name == "UserStyleSchema") {
"Expected a UserStyleSchema node"
}
val idToSetting = HashMap<String, UserStyleSetting>()
val userStyleSettings = ArrayList<UserStyleSetting>()
// Parse the UserStyle declaration.
parser.iterate {
when (parser.name) {
"BooleanUserStyleSetting" -> userStyleSettings.add(
UserStyleSetting.BooleanUserStyleSetting.inflate(resources, parser)
)
"ComplicationSlotsUserStyleSetting" -> userStyleSettings.add(
UserStyleSetting.ComplicationSlotsUserStyleSetting.inflate(
resources,
parser,
complicationScaleX,
complicationScaleY
)
)
"DoubleRangeUserStyleSetting" -> userStyleSettings.add(
UserStyleSetting.DoubleRangeUserStyleSetting.inflate(resources, parser)
)
"ListUserStyleSetting" -> userStyleSettings.add(
UserStyleSetting.ListUserStyleSetting.inflate(
resources,
parser,
idToSetting
)
)
"LongRangeUserStyleSetting" -> userStyleSettings.add(
UserStyleSetting.LongRangeUserStyleSetting.inflate(resources, parser)
)
else -> throw IllegalNodeException(parser)
}
idToSetting[userStyleSettings.last().id.value] = userStyleSettings.last()
}
return UserStyleSchema(userStyleSettings)
}
}
init {
var complicationSlotsUserStyleSettingCount = 0
var customValueUserStyleSettingCount = 0
for (setting in userStyleSettings) {
when (setting) {
is UserStyleSetting.ComplicationSlotsUserStyleSetting ->
complicationSlotsUserStyleSettingCount++
is UserStyleSetting.CustomValueUserStyleSetting ->
customValueUserStyleSettingCount++
else -> {
// Nothing
}
}
for (option in setting.options) {
for (childSetting in option.childSettings) {
require(userStyleSettings.contains(childSetting)) {
"childSettings must be in the list of settings the UserStyleSchema is " +
"constructed with"
}
}
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
validateComplicationSettings(rootUserStyleSettings, null)
} else {
require(complicationSlotsUserStyleSettingCount <= 1) {
"Prior to Android T, at most only one ComplicationSlotsUserStyleSetting is allowed"
}
}
// There's a hard limit to how big Schema + UserStyle can be and since this data is sent
// over bluetooth to the companion there will be performance issues well before we hit
// that the limit. As a result we want the total size of custom data to be kept small and
// we are initially restricting there to be at most one CustomValueUserStyleSetting.
require(customValueUserStyleSettingCount <= 1) {
"At most only one CustomValueUserStyleSetting is allowed"
}
}
private fun validateComplicationSettings(
settings: Collection<UserStyleSetting>,
initialPrevSetting: UserStyleSetting.ComplicationSlotsUserStyleSetting?
) {
var prevSetting = initialPrevSetting
for (setting in settings) {
if (setting is UserStyleSetting.ComplicationSlotsUserStyleSetting) {
require(prevSetting == null) {
"From Android T multiple ComplicationSlotsUserStyleSettings are allowed, but" +
" at most one can be active for any permutation of UserStyle. Note: " +
"$setting and $prevSetting"
}
prevSetting = setting
}
}
for (setting in settings) {
for (option in setting.options) {
validateComplicationSettings(option.childSettings, prevSetting)
}
}
}
/** @hide */
@Suppress("Deprecation") // userStyleSettings
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public constructor(wireFormat: UserStyleSchemaWireFormat) : this(
wireFormat.mSchema.map { UserStyleSetting.createFromWireFormat(it) }
) {
val wireUserStyleSettingsIterator = wireFormat.mSchema.iterator()
for (userStyle in userStyleSettings) {
val wireUserStyleSetting = wireUserStyleSettingsIterator.next()
wireUserStyleSetting.mOptionChildIndices?.let {
// Unfortunately due to VersionedParcelable limitations, we can not extend the
// Options wire format (extending the contents of a list is not supported!!!).
// This means we need to encode/decode the childSettings in a round about way.
val optionsIterator = userStyle.options.iterator()
var option: Option? = null
for (childIndex in it) {
if (option == null) {
option = optionsIterator.next()
}
if (childIndex == -1) {
option = null
} else {
val childSettings = option.childSettings as ArrayList
val child = userStyleSettings[childIndex]
childSettings.add(child)
child.hasParent = true
}
}
}
}
}
/** @hide */
@Suppress("Deprecation") // userStyleSettings
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public fun toWireFormat(): UserStyleSchemaWireFormat =
UserStyleSchemaWireFormat(
userStyleSettings.map { userStyleSetting ->
val wireFormat = userStyleSetting.toWireFormat()
// Unfortunately due to VersionedParcelable limitations, we can not extend the
// Options wire format (extending the contents of a list is not supported!!!).
// This means we need to encode/decode the childSettings in a round about way.
val optionChildIndices = ArrayList<Int>()
for (option in userStyleSetting.options) {
for (child in option.childSettings) {
optionChildIndices.add(
userStyleSettings.indexOfFirst {
it == child
}
)
}
optionChildIndices.add(-1)
}
wireFormat.mOptionChildIndices = optionChildIndices
wireFormat
}
)
/** @hide */
@Suppress("Deprecation") // userStyleSettings
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public fun getDefaultUserStyle() = UserStyle(
HashMap<UserStyleSetting, UserStyleSetting.Option>().apply {
for (setting in userStyleSettings) {
this[setting] = setting.defaultOption
}
}
)
@Suppress("Deprecation") // userStyleSettings
override fun toString(): String = "[" + userStyleSettings.joinToString() + "]"
/**
* Returns the [UserStyleSetting] whose [UserStyleSetting.Id] matches [settingId] or `null` if
* none match.
*/
@Suppress("Deprecation") // userStyleSettings
operator fun get(settingId: UserStyleSetting.Id): UserStyleSetting? {
// NB more than one match is not allowed, UserStyleSetting id's are required to be unique.
return userStyleSettings.firstOrNull { it.id == settingId }
}
/**
* Computes a SHA-1 [MessageDigest] hash of the [UserStyleSchema]. Note that for performance
* reasons where possible the resource id or url for [Icon]s in the schema are used rather than
* the image bytes. This means that this hash should be considered insensitive to changes to the
* contents of icons between APK versions, which the developer should account for accordingly.
*/
fun getDigestHash(): ByteArray {
val md = MessageDigest.getInstance("SHA-1")
val digestOutputStream = DigestOutputStream(NullOutputStream(), md)
@Suppress("Deprecation")
for (setting in userStyleSettings) {
setting.updateMessageDigest(digestOutputStream)
}
return md.digest()
}
private class NullOutputStream : OutputStream() {
override fun write(value: Int) {}
}
private fun findActiveComplicationSetting(
settings: Collection<UserStyleSetting>,
userStyle: UserStyle
): UserStyleSetting.ComplicationSlotsUserStyleSetting? {
for (setting in settings) {
if (setting is UserStyleSetting.ComplicationSlotsUserStyleSetting) {
return setting
}
findActiveComplicationSetting(userStyle[setting]!!.childSettings, userStyle)?.let {
return it
}
}
return null
}
/**
* When a UserStyleSchema contains hierarchical styles, only part of it is deemed to be active
* based on the user’s options in [userStyle]. Conversely if the UserStyleSchema doesn’t contain
* any hierarchical styles then all of it is considered to be active all the time.
*
* From the active portion of the UserStyleSchema we only allow there to be at most one
* [UserStyleSetting.ComplicationSlotsUserStyleSetting]. This function searches the active
* portion of the UserStyleSchema for the [UserStyleSetting.ComplicationSlotsUserStyleSetting],
* if one is found then it returns the selected [ComplicationSlotsOption] from that, based on
* the [userStyle]. If a [UserStyleSetting.ComplicationSlotsUserStyleSetting] is not found in
* the active portion of the UserStyleSchema it returns `null`.
*
* @param userStyle The [UserStyle] for which the function will search for the selected
* [ComplicationSlotsOption], if any.
* @return The selected [ComplicationSlotsOption] based on the [userStyle] if any, or `null`
* otherwise.
*/
public fun findComplicationSlotsOptionForUserStyle(
userStyle: UserStyle
): ComplicationSlotsOption? =
findActiveComplicationSetting(rootUserStyleSettings, userStyle)?.let {
userStyle[it] as ComplicationSlotsOption
}
}
/**
* In memory storage for the current user style choices represented as a
* [MutableStateFlow]<[UserStyle]>.
*
* @param schema The [UserStyleSchema] for this CurrentUserStyleRepository which describes the
* available style categories.
*/
public class CurrentUserStyleRepository(public val schema: UserStyleSchema) {
// Mutable backing field for [userStyle].
private val mutableUserStyle = MutableStateFlow(schema.getDefaultUserStyle())
/**
* The current [UserStyle]. If accessed from java, consider using
* [androidx.lifecycle.FlowLiveDataConversions.asLiveData] to observe changes.
*/
public val userStyle: StateFlow<UserStyle> by CurrentUserStyleRepository::mutableUserStyle
/**
* The UserStyle options must be from the supplied [UserStyleSchema].
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public fun updateUserStyle(newUserStyle: UserStyle) {
validateUserStyle(newUserStyle)
mutableUserStyle.value = newUserStyle
}
@Suppress("Deprecation") // userStyleSettings
internal fun validateUserStyle(userStyle: UserStyle) {
for ((key, value) in userStyle) {
val setting = schema.userStyleSettings.firstOrNull { it == key }
require(setting != null) {
"UserStyleSetting $key is not a reference to a UserStyleSetting within " +
"the schema."
}
require(setting::class.java == value.getUserStyleSettingClass()) {
"The option class (${value::class.java.canonicalName}) in $key must " +
"match the setting class " + setting::class.java.canonicalName
}
}
}
}
| apache-2.0 | 916c4b426f85654572cd6d381666ecd0 | 40.021248 | 111 | 0.640066 | 5.103933 | false | false | false | false |
AndroidX/androidx | compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/layout/LayoutId.kt | 3 | 3012 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.layout
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.InspectorInfo
import androidx.compose.ui.platform.InspectorValueInfo
import androidx.compose.ui.platform.debugInspectorInfo
import androidx.compose.ui.unit.Density
/**
* Tag the element with [layoutId] to identify the element within its parent.
*
* Example usage:
* @sample androidx.compose.ui.samples.LayoutTagChildrenUsage
*/
@Stable
fun Modifier.layoutId(layoutId: Any) = this.then(
LayoutId(
layoutId = layoutId,
inspectorInfo = debugInspectorInfo {
name = "layoutId"
value = layoutId
}
)
)
/**
* A [ParentDataModifier] which tags the target with the given [id][layoutId]. The provided tag
* will act as parent data, and can be used for example by parent layouts to associate
* composable children to [Measurable]s when doing layout, as shown below.
*/
@Immutable
private class LayoutId(
override val layoutId: Any,
inspectorInfo: InspectorInfo.() -> Unit
) : ParentDataModifier, LayoutIdParentData, InspectorValueInfo(inspectorInfo) {
override fun Density.modifyParentData(parentData: Any?): Any? {
return this@LayoutId
}
override fun hashCode(): Int =
layoutId.hashCode()
override fun equals(other: Any?): Boolean {
if (this === other) return true
val otherModifier = other as? LayoutId ?: return false
return layoutId == otherModifier.layoutId
}
override fun toString(): String =
"LayoutId(id=$layoutId)"
}
/**
* Can be implemented by values used as parent data to make them usable as tags.
* If a parent data value implements this interface, it can then be returned when querying
* [Measurable.layoutId] for the corresponding child.
*/
interface LayoutIdParentData {
val layoutId: Any
}
/**
* Retrieves the tag associated to a composable with the [Modifier.layoutId] modifier.
* For a parent data value to be returned by this property when not using the [Modifier.layoutId]
* modifier, the parent data value should implement the [LayoutIdParentData] interface.
*
* Example usage:
* @sample androidx.compose.ui.samples.LayoutTagChildrenUsage
*/
val Measurable.layoutId: Any?
get() = (parentData as? LayoutIdParentData)?.layoutId | apache-2.0 | 74843ce2947067f67a1ef5401808e310 | 32.853933 | 97 | 0.73008 | 4.352601 | false | false | false | false |
kittinunf/Fuel | fuel/src/main/kotlin/com/github/kittinunf/fuel/core/interceptors/LoggingInterceptors.kt | 1 | 2056 | package com.github.kittinunf.fuel.core.interceptors
import com.github.kittinunf.fuel.core.FoldableRequestInterceptor
import com.github.kittinunf.fuel.core.FoldableResponseInterceptor
import com.github.kittinunf.fuel.core.Request
import com.github.kittinunf.fuel.core.RequestTransformer
import com.github.kittinunf.fuel.core.Response
import com.github.kittinunf.fuel.core.ResponseTransformer
import com.github.kittinunf.fuel.core.extensions.cUrlString
object LogRequestInterceptor : FoldableRequestInterceptor {
override fun invoke(next: RequestTransformer): RequestTransformer {
return { request ->
println(request)
next(request)
}
}
}
object LogRequestAsCurlInterceptor : FoldableRequestInterceptor {
override fun invoke(next: RequestTransformer): RequestTransformer {
return { request ->
println(request.cUrlString())
next(request)
}
}
}
object LogResponseInterceptor : FoldableResponseInterceptor {
override fun invoke(next: ResponseTransformer): ResponseTransformer {
return { request, response ->
println(response.toString())
next(request, response)
}
}
}
@Deprecated("Use LogRequestInterceptor", replaceWith = ReplaceWith("LogRequestInterceptor"))
fun <T> loggingRequestInterceptor() =
{ next: (T) -> T ->
{ t: T ->
println(t)
next(t)
}
}
@Deprecated("Use LogRequestAsCurlInterceptor", replaceWith = ReplaceWith("LogRequestAsCurlInterceptor"))
fun cUrlLoggingRequestInterceptor() =
{ next: (Request) -> Request ->
{ r: Request ->
println(r.cUrlString())
next(r)
}
}
@Deprecated("Use LogRequestAsCurlInterceptor (remove braces)", replaceWith = ReplaceWith("LogResponseInterceptor"))
fun loggingResponseInterceptor(): (Request, Response) -> Response =
{ _: Request, response: Response ->
println(response)
response
}
| mit | 758373c514d245f7b7b5c46c81de10f1 | 32.704918 | 115 | 0.668288 | 4.849057 | false | false | false | false |
satamas/fortran-plugin | src/main/kotlin/org/jetbrains/fortran/lang/stubs/FortranFileStub.kt | 1 | 1291 | package org.jetbrains.fortran.lang.stubs
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiFile
import com.intellij.psi.StubBuilder
import com.intellij.psi.stubs.*
import com.intellij.psi.tree.IStubFileElementType
import org.jetbrains.fortran.FortranLanguage
import org.jetbrains.fortran.lang.parser.FortranFileParser
import org.jetbrains.fortran.lang.psi.FortranFile
class FortranFileStub(file: FortranFile?) : PsiFileStubImpl<FortranFile>(file) {
override fun getType() = Type
object Type : IStubFileElementType<FortranFileStub>(FortranLanguage) {
override fun parseContents(chameleon: ASTNode): ASTNode? {
return FortranFileParser.parse(this, chameleon)
}
override fun getStubVersion(): Int = 2
override fun getBuilder(): StubBuilder = object : DefaultStubBuilder() {
override fun createStubForFile(file: PsiFile): StubElement<*> = FortranFileStub(file as FortranFile)
}
override fun serialize(stub: FortranFileStub, dataStream: StubOutputStream) {
}
override fun deserialize(dataStream: StubInputStream, parentStub: StubElement<*>?): FortranFileStub {
return FortranFileStub(null)
}
override fun getExternalId(): String = "Fortran.file"
}
} | apache-2.0 | 0fcd23576db5ffab645e817b4b0a4f97 | 34.888889 | 112 | 0.728892 | 4.781481 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/stdext/Profiling.kt | 3 | 6291 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
@file:Suppress("unused", "MemberVisibilityCanBePrivate")
package org.rust.stdext
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicLong
import kotlin.math.max
import kotlin.math.pow
import kotlin.math.sqrt
import kotlin.system.measureNanoTime
import kotlin.system.measureTimeMillis
class Timings(
private val valuesTotal: LinkedHashMap<String, Long> = LinkedHashMap(),
private val invokes: MutableMap<String, Long> = mutableMapOf()
) {
fun <T: Any> measure(name: String, f: () -> T): T {
check(name !in valuesTotal)
return measureInternal(name, f)
}
fun <T: Any> measureAverage(name: String, f: () -> T): T = measureInternal(name, f)
private fun <T: Any> measureInternal(name: String, f: () -> T): T {
val result: T
val time = measureTimeMillis { result = f() }
valuesTotal.merge(name, time, Long::plus)
invokes.merge(name, 1, Long::plus)
return result
}
fun <T: Any> measureSum(name: String, f: () -> T): T {
val result: T
val time = measureTimeMillis { result = f() }
valuesTotal.merge(name, time, Long::plus)
invokes[name] = 1
return result
}
fun values(): Map<String, Long> {
val result = LinkedHashMap<String, Long>()
for ((k, sum) in valuesTotal) {
result[k] = (sum.toDouble() / invokes[k]!!).toLong()
}
return result
}
}
class ListTimings {
private val timings: MutableMap<String, MutableList<Long>> = LinkedHashMap()
fun add(t: Timings) {
for ((k, v) in t.values()) {
timings.computeIfAbsent(k) { mutableListOf() }.add(v)
}
}
fun add(action: (Timings) -> Unit) {
val t = Timings()
action(t)
add(t)
}
fun print() {
val values = timings.mapValues { (_, v) -> calculate(v) }
val table = listOf(listOf("LABEL", "MIN (ms)", "MAX (ms)", "AVG (ms)", "ERROR")) +
values.map { (k, v) ->
listOf(
k,
v.min.toString(),
v.max.toString(),
v.avg.toInt().toString(),
String.format("± %.2f", v.standardDeviation)
)
}
val widths = IntArray(table[0].size)
for (row in table) {
row.forEachIndexed { i, s -> widths[i] = max(widths[i], s.length) }
}
for (row in table) {
println(row.withIndex().joinToString(" ") { (i, s) ->
s.padEnd(widths[i])
})
}
}
private fun calculate(values: MutableList<Long>): Statistics {
val min = values.minOrNull() ?: error("Empty timings!")
val max = values.maxOrNull() ?: error("Empty timings!")
val avg = values.sum() / values.size.toDouble()
val variance = if (values.size > 1) {
values.fold(0.0) { acc, i -> acc + (i - avg).pow(2.0) } / (values.size - 1)
} else {
Double.NaN
}
val standardDeviation = sqrt(variance)
return Statistics(min, max, avg, standardDeviation)
}
}
data class Statistics(
val min: Long,
val max: Long,
val avg: Double,
val standardDeviation: Double
)
fun repeatBenchmark(warmupIterations: Int = 10, iterations: Int = 10, action: (Timings) -> Unit) {
repeatBenchmarkInternal(warmupIterations, "Warmup iteration", action)
repeatBenchmarkInternal(iterations, "Iteration", action)
}
private fun repeatBenchmarkInternal(times: Int = 10, label: String, action: (Timings) -> Unit) {
val timings = ListTimings()
repeat(times) { i ->
println("$label #${i + 1}")
timings.add {
action(it)
}
timings.print()
println()
}
}
interface RsWatch {
val name: String
val totalNs: AtomicLong
}
/**
* Useful to quickly measure total times of a certain repeated
* operation during profiling.
*
* Create a global StopWatch instance, use [messages] function
* around interesting block, see the results at the end. Note
* that [measure] is not reentrant, and will double count
* recursive activities like resolve. If you want reentrancy,
* use [RsReentrantStopWatch]
*
* **FOR DEVELOPMENT ONLY**
*/
class RsStopWatch(
override val name: String
) : RsWatch {
override var totalNs: AtomicLong = AtomicLong(0)
init {
WATCHES += this
}
fun <T> measure(block: () -> T): T {
val result: T
totalNs.addAndGet(measureNanoTime { result = block() })
return result
}
}
/**
* Like [RsStopWatch], but requires an explicit start and is reentrant
*/
class RsReentrantStopWatch(override val name: String) : RsWatch {
override val totalNs: AtomicLong = AtomicLong(0)
private val started: AtomicBoolean = AtomicBoolean(false)
private val nesting = NestingCounter()
init {
WATCHES += this
}
fun start() {
started.set(true)
}
fun <T> measure(block: () -> T): T {
val result: T
if (nesting.enter() && started.get()) {
totalNs.addAndGet(measureNanoTime { result = block() })
} else {
result = block()
}
nesting.exit()
return result
}
}
private class NestingCounter : ThreadLocal<Int>() {
override fun initialValue(): Int = 0
fun enter(): Boolean {
val v = get()
set(v + 1)
return v == 0
}
fun exit() {
set(get() - 1)
}
}
private object WATCHES {
private val registered = ConcurrentHashMap.newKeySet<RsWatch>()
init {
Runtime.getRuntime().addShutdownHook(object : Thread() {
override fun run() {
println("\nWatches:")
for (watch in registered.sortedBy { -it.totalNs.get() }) {
val ms = watch.totalNs.get() / 1_000_000
println(" ${ms.toString().padEnd(4)} ms ${watch.name}")
}
}
})
}
operator fun plusAssign(watch: RsWatch) {
registered += watch
}
}
| mit | 9b6ffd7e80ac19dab968c3be423524e8 | 26.709251 | 98 | 0.573927 | 4.01148 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/cargo/project/model/impl/CargoPackageIndex.kt | 2 | 2690 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.project.model.impl
import com.intellij.openapi.Disposable
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.indexing.LightDirectoryIndex
import org.rust.cargo.project.model.CargoProject
import org.rust.cargo.project.model.CargoProjectsService
import org.rust.cargo.project.workspace.CargoWorkspace.Package
import org.rust.cargo.project.workspace.additionalRoots
import org.rust.openapiext.checkReadAccessAllowed
import org.rust.openapiext.checkWriteAccessAllowed
import java.util.*
class CargoPackageIndex(
private val project: Project,
private val service: CargoProjectsService
) : CargoProjectsService.CargoProjectsListener {
private val indices: MutableMap<CargoProject, LightDirectoryIndex<Optional<Package>>> = hashMapOf()
private var indexDisposable: Disposable? = null
init {
project.messageBus.connect(project).subscribe(CargoProjectsService.CARGO_PROJECTS_TOPIC, this)
}
override fun cargoProjectsUpdated(service: CargoProjectsService, projects: Collection<CargoProject>) {
checkWriteAccessAllowed()
resetIndex()
val disposable = Disposer.newDisposable("CargoPackageIndexDisposable")
Disposer.register(project, disposable)
for (cargoProject in projects) {
val packages = cargoProject.workspace?.packages.orEmpty()
indices[cargoProject] = LightDirectoryIndex(disposable, Optional.empty()) { index ->
for (pkg in packages) {
val info = Optional.of(pkg)
index.putInfo(pkg.contentRoot, info)
index.putInfo(pkg.outDir, info)
for (additionalRoot in pkg.additionalRoots()) {
index.putInfo(additionalRoot, info)
}
for (target in pkg.targets) {
index.putInfo(target.crateRoot?.parent, info)
}
}
}
}
indexDisposable = disposable
}
fun findPackageForFile(file: VirtualFile): Package? {
checkReadAccessAllowed()
val cargoProject = service.findProjectForFile(file) ?: return null
return indices[cargoProject]?.getInfoForFile(file)?.orElse(null)
}
private fun resetIndex() {
val disposable = indexDisposable
if (disposable != null) {
Disposer.dispose(disposable)
}
indexDisposable = null
indices.clear()
}
}
| mit | 050be2c25120c389e506518711d7d390 | 36.887324 | 106 | 0.676952 | 4.864376 | false | false | false | false |
googlecast/CastAndroidTvReceiver | app-kotlin/src/main/kotlin/com/google/sample/cast/atvreceiver/data/Movie.kt | 1 | 1478 | /**
* Copyright 2022 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.sample.cast.atvreceiver.data
import java.io.Serializable
/**
* Movie class represents video entity with title, description, image thumbs and video url.
*/
class Movie : Serializable {
var id = 0
var title: String? = null
var description: String? = null
var backgroundImageUrl: String? = null
var cardImageUrl: String? = null
var videoUrl: String? = null
var studio: String? = null
override fun toString(): String {
return "Movie{" +
"id=" + id +
", title='" + title + '\'' +
", videoUrl='" + videoUrl + '\'' +
", backgroundImageUrl='" + backgroundImageUrl + '\'' +
", cardImageUrl='" + cardImageUrl + '\'' +
'}'
}
companion object {
const val serialVersionUID = 727566175075960653L
}
} | apache-2.0 | f02b1aa0dfd0a8b12503cc9adbaa301b | 32.613636 | 91 | 0.638024 | 4.39881 | false | false | false | false |
noemus/kotlin-eclipse | kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/search/KotlinReferenceMatchPresentation.kt | 1 | 4582 | /*******************************************************************************
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*******************************************************************************/
package org.jetbrains.kotlin.ui.search
import org.eclipse.jdt.ui.search.IMatchPresentation
import org.eclipse.jface.viewers.ILabelProvider
import org.eclipse.search.ui.text.Match
import org.eclipse.jface.viewers.LabelProvider
import org.jetbrains.kotlin.psi.KtReferenceExpression
import org.eclipse.swt.graphics.Image
import com.intellij.psi.util.PsiTreeUtil
import org.eclipse.jdt.ui.JavaUI
import org.eclipse.jdt.ui.ISharedImages
import org.jetbrains.kotlin.eclipse.ui.utils.EditorUtil
import org.jetbrains.kotlin.eclipse.ui.utils.getTextDocumentOffset
import org.eclipse.search.internal.ui.text.EditorOpener
import org.eclipse.core.resources.ResourcesPlugin
import org.eclipse.ui.PlatformUI
import org.jetbrains.kotlin.core.builder.KotlinPsiManager
import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider.IStyledLabelProvider
import org.eclipse.jface.viewers.StyledString
import org.eclipse.jface.viewers.ITreeContentProvider
import org.eclipse.jface.viewers.Viewer
import org.eclipse.jdt.ui.JavaElementLabels
import org.eclipse.jdt.internal.corext.util.Strings
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.ui.editors.completion.KotlinCompletionUtils
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.eclipse.ui.utils.KotlinImageProvider
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.core.asJava.getTypeFqName
public class KotlinReferenceMatchPresentation : IMatchPresentation {
private val editorOpener = EditorOpener()
override fun createLabelProvider(): ILabelProvider = KotlinReferenceLabelProvider()
override fun showMatch(match: Match, currentOffset: Int, currentLength: Int, activate: Boolean) {
if (match !is KotlinElementMatch) return
val element = match.jetElement
val eclipseFile = KotlinPsiManager.getEclipseFile(element.getContainingKtFile())
if (eclipseFile != null) {
val document = EditorUtil.getDocument(eclipseFile)
editorOpener.openAndSelect(
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(),
eclipseFile,
element.getTextDocumentOffset(document),
element.getTextLength(),
activate)
}
}
}
public class KotlinReferenceLabelProvider : LabelProvider() {
override fun getText(element: Any): String {
if (element !is KotlinAdaptableElement) {
throw IllegalArgumentException("KotlinReferenceLabelProvider asked for non-reference expression: $element")
}
val declaration = getContainingDeclaration(element.jetElement)
return when (declaration) {
is KtNamedDeclaration -> declaration.let {
with (it) {
getFqName()?.asString() ?: getNameAsSafeName().asString()
}
}
is KtFile -> getTypeFqName(declaration)?.asString() ?: ""
else -> ""
}
}
override fun getImage(element: Any): Image? {
val jetElement = (element as KotlinAdaptableElement).jetElement
val containingDeclaration = getContainingDeclaration(jetElement)
return containingDeclaration?.let { KotlinImageProvider.getImage(it) } ?: null
}
private fun getContainingDeclaration(jetElement: KtElement): KtElement? {
return PsiTreeUtil.getNonStrictParentOfType(jetElement,
KtNamedFunction::class.java,
KtProperty::class.java,
KtClassOrObject::class.java,
KtFile::class.java)
}
} | apache-2.0 | 9d56b04fae0d579eb8c4e8c30bfcbdde | 43.067308 | 119 | 0.703841 | 4.82824 | false | false | false | false |
andstatus/andstatus | app/src/androidTest/kotlin/org/andstatus/app/timeline/ListActivityTestHelper.kt | 1 | 18402 | /*
* Copyright (C) 2015 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.timeline
import android.app.Activity
import android.app.Instrumentation.ActivityMonitor
import android.view.View
import android.widget.ListAdapter
import android.widget.ListView
import androidx.test.platform.app.InstrumentationRegistry
import org.andstatus.app.activity.ActivityViewItem
import org.andstatus.app.context.TestSuite
import org.andstatus.app.data.DbUtils
import org.andstatus.app.data.DownloadStatus
import org.andstatus.app.data.MyQuery
import org.andstatus.app.database.table.NoteTable
import org.andstatus.app.list.ContextMenuItem
import org.andstatus.app.list.MyBaseListActivity
import org.andstatus.app.note.BaseNoteViewItem
import org.andstatus.app.note.NoteViewItem
import org.andstatus.app.util.EspressoUtils
import org.andstatus.app.util.EspressoUtils.waitForIdleSync
import org.andstatus.app.util.MyLog
import org.andstatus.app.view.SelectorDialog
import org.junit.Assert
import java.util.function.Predicate
class ListActivityTestHelper<T : MyBaseListActivity> {
private val mActivity: T?
private var mActivityMonitor: ActivityMonitor? = null
private var dialogTagToMonitor: String? = null
private val dialogToMonitor: SelectorDialog? = null
constructor(activity: T?) : super() {
mActivity = activity
}
constructor(activity: T, classOfActivityToMonitor: Class<out Activity>) : super() {
addMonitor(classOfActivityToMonitor)
mActivity = activity
}
/**
* @return success
*/
fun invokeContextMenuAction4ListItemId(
methodExt: String, listItemId: Long, menuItem: ContextMenuItem,
childViewId: Int
): Boolean {
val method = "invokeContextMenuAction4ListItemId"
requireNotNull(mActivity)
var success = false
var msg = ""
for (attempt in 1..3) {
EspressoUtils.waitForIdleSync()
val position = getPositionOfListItemId(listItemId)
msg = "listItemId=$listItemId; menu Item=$menuItem; position=$position; attempt=$attempt"
MyLog.v(this, msg)
if (position >= 0 && getListItemIdAtPosition(position) == listItemId) {
selectListPosition(methodExt, position)
if (invokeContextMenuAction(methodExt, mActivity, position, menuItem.getId(), childViewId)) {
val id2 = getListItemIdAtPosition(position)
if (id2 == listItemId) {
success = true
break
} else {
MyLog.i(methodExt, "$method; Position changed, now pointing to listItemId=$id2; $msg")
}
}
}
}
MyLog.v(methodExt, "$method ended $success; $msg")
EspressoUtils.waitForIdleSync()
return success
}
@JvmOverloads
fun selectListPosition(
methodExt: String?, positionIn: Int,
listView: ListView? = mActivity?.listView,
listAdapter: ListAdapter? = getListAdapter()
) {
val method = "selectListPosition"
if (listView == null || listAdapter == null) {
MyLog.v(methodExt, "$method no listView or adapter")
return
}
MyLog.v(methodExt, "$method started; position=$positionIn")
InstrumentationRegistry.getInstrumentation().runOnMainSync {
var position = positionIn
if (listAdapter.getCount() <= position) {
position = listAdapter.getCount() - 1
}
MyLog.v(
methodExt, method + " on setSelection " + position
+ " of " + (listAdapter.getCount() - 1)
)
listView.setSelectionFromTop(position, 0)
}
EspressoUtils.waitForIdleSync()
MyLog.v(methodExt, "$method ended")
}
/**
* @return success
*
* Note: This method cannot be invoked on the main thread.
* See https://github.com/google/google-authenticator-android/blob/master/tests/src/com/google/android/apps/authenticator/TestUtilities.java
*/
private fun invokeContextMenuAction(
methodExt: String, activity: MyBaseListActivity,
position: Int, menuItemId: Int, childViewId: Int
): Boolean {
val method = "invokeContextMenuAction"
MyLog.v(methodExt, "$method started on menuItemId=$menuItemId at position=$position")
var success = false
var position1 = position
for (attempt in 1..3) {
goToPosition(methodExt, position)
if (!longClickListAtPosition(methodExt, position1, childViewId)) {
break
}
if (mActivity?.getPositionOfContextMenu() == position) {
success = true
break
}
MyLog.i(
methodExt, method + "; Context menu created for position " + mActivity?.getPositionOfContextMenu()
+ " instead of " + position
+ "; was set to " + position1 + "; attempt " + attempt
)
position1 = position + (position1 - (mActivity?.getPositionOfContextMenu() ?: 0))
}
if (success) {
InstrumentationRegistry.getInstrumentation().runOnMainSync {
MyLog.v(methodExt, "$method; before performContextMenuIdentifierAction")
activity.getWindow().performContextMenuIdentifierAction(menuItemId, 0)
}
EspressoUtils.waitForIdleSync()
}
MyLog.v(methodExt, "$method ended $success")
return success
}
private fun longClickListAtPosition(methodExt: String?, position: Int, childViewId: Int): Boolean {
val parentView = getViewByPosition(position)
if (parentView == null) {
MyLog.i(methodExt, "Parent view at list position $position doesn't exist")
return false
}
var childView: View? = null
if (childViewId != 0) {
childView = parentView.findViewById(childViewId)
if (childView == null) {
MyLog.i(methodExt, "Child view $childViewId at list position $position doesn't exist")
return false
}
}
val viewToClick = childView ?: parentView
InstrumentationRegistry.getInstrumentation().runOnMainSync {
val msg = ("performLongClick on "
+ (if (childViewId == 0) "" else "child $childViewId ")
+ viewToClick + " at position " + position)
MyLog.v(methodExt, msg)
try {
viewToClick.performLongClick()
} catch (e: Exception) {
MyLog.e(msg, e)
}
}
EspressoUtils.waitForIdleSync()
return true
}
fun goToPosition(methodExt: String?, position: Int) {
mActivity?.listView?.let { listView ->
InstrumentationRegistry.getInstrumentation().runOnMainSync {
val msg = "goToPosition $position"
MyLog.v(methodExt, msg)
try {
listView.setSelectionFromTop(position + listView.getHeaderViewsCount(), 0)
} catch (e: Exception) {
MyLog.e(msg, e)
}
}
}
EspressoUtils.waitForIdleSync()
}
// See http://stackoverflow.com/questions/24811536/android-listview-get-item-view-by-position
fun getViewByPosition(position: Int): View? {
return getViewByPosition(position, mActivity?.listView, getListAdapter())
}
fun getViewByPosition(position: Int, listView: ListView?, listAdapter: ListAdapter?): View? {
if (listView == null) return null
val method = "getViewByPosition"
val firstListItemPosition = listView.getFirstVisiblePosition() - listView.getHeaderViewsCount()
val lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1 - listView.getHeaderViewsCount()
val view: View?
view = if (position < firstListItemPosition || position > lastListItemPosition) {
if (position < 0 || listAdapter == null || listAdapter.count < position + 1) {
null
} else {
listAdapter.getView(position, null, listView)
}
} else {
val childIndex = position - firstListItemPosition
listView.getChildAt(childIndex)
}
MyLog.v(
this, method + ": pos:" + position + ", first:" + firstListItemPosition
+ ", last:" + lastListItemPosition + ", view:" + view
)
return view
}
fun getListItemIdOfLoadedReply(): Long {
return getListItemIdOfLoadedReply { any: BaseNoteViewItem<*>? -> true }
}
fun getListItemIdOfLoadedReply(predicate: Predicate<BaseNoteViewItem<*>>): Long {
return findListItemId("Loaded reply") { item: BaseNoteViewItem<*> ->
if (item.inReplyToNoteId != 0L && item.noteStatus == DownloadStatus.LOADED && predicate.test(item)) {
val statusOfReplied: DownloadStatus = DownloadStatus.Companion.load(
MyQuery.noteIdToLongColumnValue(NoteTable.NOTE_STATUS, item.inReplyToNoteId)
)
statusOfReplied == DownloadStatus.LOADED
} else false
}
}
fun findListItemId(description: String?, predicate: Predicate<BaseNoteViewItem<*>>): Long {
return findListItem(description, predicate).getId()
}
fun findListItem(description: String?, predicate: Predicate<BaseNoteViewItem<*>>): ViewItem<*> {
val method = "findListItemId"
val listAdapter = getListAdapter()
if (listAdapter == null) {
MyLog.v(method, "$method no listAdapter")
} else {
for (ind in 0 until listAdapter.count) {
val viewItem = listAdapter.getItem(ind) as ViewItem<*>
val item: BaseNoteViewItem<*> = toBaseNoteViewItem(viewItem)
if (!item.isEmpty) {
if (predicate.test(item)) {
MyLog.v(this, "$method $ind. found $description : $item")
return viewItem
} else {
MyLog.v(this, "$ind. skipped : $item")
}
}
}
}
Assert.fail(method + " didn't find '" + description + "' in " + listAdapter)
return EmptyViewItem.EMPTY
}
fun getPositionOfListItemId(itemId: Long): Int {
var position = -1
val listAdapter = getListAdapter()
if (listAdapter != null) for (ind in 0 until listAdapter.count) {
if (itemId == listAdapter.getItemId(ind)) {
position = ind
break
}
}
return position
}
fun getListItemIdAtPosition(position: Int): Long {
var itemId: Long = 0
val listAdapter = getListAdapter()
if (listAdapter != null && position >= 0 && position < listAdapter.count) {
itemId = listAdapter.getItemId(position)
}
return itemId
}
private fun getListAdapter(): ListAdapter? {
return mActivity?.getListAdapter()
}
@JvmOverloads
fun clickListAtPosition(
methodExt: String?, position: Int,
listView: ListView? = mActivity?.listView,
listAdapter: ListAdapter? = getListAdapter()
) {
val method = "clickListAtPosition"
if (listView == null || listAdapter == null) {
MyLog.v(methodExt, "$method no listView or adapter")
return
}
val viewToClick = getViewByPosition(position, listView, listAdapter)
val listItemId = listAdapter.getItemId(position)
val msgLog = "$method; id:$listItemId, position:$position, view:$viewToClick"
InstrumentationRegistry.getInstrumentation().runOnMainSync {
MyLog.v(methodExt, "onPerformClick $msgLog")
// One of the two should work
viewToClick?.performClick()
listView.performItemClick(
viewToClick,
position + listView.getHeaderViewsCount(), listItemId
)
MyLog.v(methodExt, "afterClick $msgLog")
}
MyLog.v(methodExt, "$method ended, $msgLog")
EspressoUtils.waitForIdleSync()
}
fun addMonitor(classOfActivity: Class<out Activity>) {
mActivityMonitor = InstrumentationRegistry.getInstrumentation()
.addMonitor(classOfActivity.getName(), null, false)
}
fun waitForNextActivity(methodExt: String?, timeOut: Long): Activity? {
val nextActivity =
InstrumentationRegistry.getInstrumentation().waitForMonitorWithTimeout(mActivityMonitor, timeOut)
MyLog.v(methodExt, "After waitForMonitor: $nextActivity")
Assert.assertNotNull("$methodExt; Next activity should be created", nextActivity)
TestSuite.waitForListLoaded(nextActivity, 2)
mActivityMonitor = null
return nextActivity
}
fun waitForSelectorDialog(methodExt: String?, timeout: Int): SelectorDialog? {
val method = "waitForSelectorDialog"
var selectorDialog: SelectorDialog? = null
var isVisible = false
for (ind in 0..19) {
waitForIdleSync()
selectorDialog =
mActivity?.getSupportFragmentManager()?.findFragmentByTag(dialogTagToMonitor) as SelectorDialog?
if (selectorDialog != null && selectorDialog.isVisible) {
isVisible = true
break
}
if (DbUtils.waitMs(method, 1000)) {
break
}
}
Assert.assertTrue(
"$methodExt: Didn't find SelectorDialog with tag:'$dialogTagToMonitor'",
selectorDialog != null
)
Assert.assertTrue(isVisible)
val list = selectorDialog?.listView
requireNotNull(list)
var itemsCount = 0
val minCount = 1
for (ind in 0..59) {
if (DbUtils.waitMs(method, 2000)) {
break
}
waitForIdleSync()
val itemsCountNew = list.count
MyLog.v(methodExt, "waitForSelectorDialog; countNew=$itemsCountNew, prev=$itemsCount, min=$minCount")
if (itemsCountNew >= minCount && itemsCount == itemsCountNew) {
break
}
itemsCount = itemsCountNew
}
Assert.assertTrue(
"There are $itemsCount items (min=$minCount) in the list of $dialogTagToMonitor",
itemsCount >= minCount
)
return selectorDialog
}
fun selectIdFromSelectorDialog(method: String?, id: Long) {
val selector = waitForSelectorDialog(method, 15000)
val position = selector?.getListAdapter()?.getPositionById(id) ?: -1
Assert.assertTrue("$method; Item id:$id found", position >= 0)
requireNotNull(selector)
selectListPosition(method, position, selector.listView, selector.getListAdapter())
clickListAtPosition(method, position, selector.listView, selector.getListAdapter())
}
// TODO: Unify interface with my List Activity
fun getSelectorViewByPosition(position: Int): View? {
val selector = dialogToMonitor
val method = "getSelectorViewByPosition"
requireNotNull(selector)
val listView = selector.listView
val listAdapter = selector.getListAdapter()
if (listView == null || listAdapter == null) {
MyLog.v(method, "$method no listView or adapter")
return null
}
val firstListItemPosition = listView.firstVisiblePosition
val lastListItemPosition = firstListItemPosition + listView.childCount - 1
val view: View?
view = if (position < firstListItemPosition || position > lastListItemPosition) {
if (position < 0 || listAdapter.count < position + 1) {
null
} else {
listAdapter.getView(position, null, listView)
}
} else {
val childIndex = position - firstListItemPosition
listView.getChildAt(childIndex)
}
MyLog.v(
this, method + ": pos:" + position + ", first:" + firstListItemPosition
+ ", last:" + lastListItemPosition + ", view:" + view
)
return view
}
fun clickView(methodExt: String, resourceId: Int) {
mActivity?.findViewById<View>(resourceId)?.let {
clickView(methodExt, it)
}
}
fun clickView(methodExt: String, view: View) {
val clicker = Runnable {
MyLog.v(methodExt, "Before click view")
view.performClick()
}
InstrumentationRegistry.getInstrumentation().runOnMainSync(clicker)
MyLog.v(methodExt, "After click view")
EspressoUtils.waitForIdleSync()
}
companion object {
fun <T : MyBaseListActivity> newForSelectorDialog(
activity: T?,
dialogTagToMonitor: String?
): ListActivityTestHelper<T> {
val helper = ListActivityTestHelper(activity)
helper.dialogTagToMonitor = dialogTagToMonitor
return helper
}
fun toBaseNoteViewItem(objItem: Any): BaseNoteViewItem<*> {
if (ActivityViewItem::class.java.isAssignableFrom(objItem.javaClass)) {
return (objItem as ActivityViewItem).noteViewItem
} else if (BaseNoteViewItem::class.java.isAssignableFrom(objItem.javaClass)) {
return objItem as BaseNoteViewItem<*>
}
return NoteViewItem.Companion.EMPTY
}
}
}
| apache-2.0 | aa7593e66810a1aa3200b503219420fa | 38.831169 | 144 | 0.609119 | 4.978896 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/insight/generation/MinecraftClassCreateAction.kt | 1 | 6578 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.insight.generation
import com.demonwav.mcdev.asset.GeneralAssets
import com.demonwav.mcdev.asset.PlatformAssets
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.platform.fabric.FabricModuleType
import com.demonwav.mcdev.platform.forge.ForgeModuleType
import com.demonwav.mcdev.platform.mcp.McpModuleType
import com.demonwav.mcdev.util.MinecraftTemplates
import com.demonwav.mcdev.util.MinecraftVersions
import com.demonwav.mcdev.util.SemanticVersion
import com.demonwav.mcdev.util.findModule
import com.intellij.codeInsight.daemon.JavaErrorBundle
import com.intellij.codeInsight.daemon.impl.analysis.HighlightClassUtil
import com.intellij.ide.actions.CreateFileFromTemplateDialog
import com.intellij.ide.actions.CreateTemplateInPackageAction
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.InputValidatorEx
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.JavaDirectoryService
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNameHelper
import com.intellij.psi.util.PsiUtil
import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes
class MinecraftClassCreateAction :
CreateTemplateInPackageAction<PsiClass>(
CAPTION,
"Class generation for modders",
GeneralAssets.MC_TEMPLATE,
JavaModuleSourceRootTypes.SOURCES
),
DumbAware {
override fun getActionName(directory: PsiDirectory?, newName: String, templateName: String?): String = CAPTION
override fun buildDialog(project: Project, directory: PsiDirectory, builder: CreateFileFromTemplateDialog.Builder) {
builder.setTitle(CAPTION)
builder.setValidator(ClassInputValidator(project, directory))
val module = directory.findModule() ?: return
val isForge = MinecraftFacet.getInstance(module, ForgeModuleType) != null
val isFabric = MinecraftFacet.getInstance(module, FabricModuleType) != null
val mcVersion = MinecraftFacet.getInstance(module, McpModuleType)?.getSettings()
?.minecraftVersion?.let(SemanticVersion::parse)
if (isForge && mcVersion != null) {
val icon = PlatformAssets.FORGE_ICON
if (mcVersion < MinecraftVersions.MC1_17) {
builder.addKind("Block", icon, MinecraftTemplates.FORGE_BLOCK_TEMPLATE)
builder.addKind("Item", icon, MinecraftTemplates.FORGE_ITEM_TEMPLATE)
builder.addKind("Packet", icon, MinecraftTemplates.FORGE_PACKET_TEMPLATE)
builder.addKind("Enchantment", icon, MinecraftTemplates.FORGE_ENCHANTMENT_TEMPLATE)
} else if (mcVersion < MinecraftVersions.MC1_18) {
builder.addKind("Block", icon, MinecraftTemplates.FORGE_1_17_BLOCK_TEMPLATE)
builder.addKind("Item", icon, MinecraftTemplates.FORGE_1_17_ITEM_TEMPLATE)
builder.addKind("Packet", icon, MinecraftTemplates.FORGE_1_17_PACKET_TEMPLATE)
builder.addKind("Enchantment", icon, MinecraftTemplates.FORGE_1_17_ENCHANTMENT_TEMPLATE)
} else {
builder.addKind("Block", icon, MinecraftTemplates.FORGE_1_17_BLOCK_TEMPLATE)
builder.addKind("Item", icon, MinecraftTemplates.FORGE_1_17_ITEM_TEMPLATE)
builder.addKind("Packet", icon, MinecraftTemplates.FORGE_1_18_PACKET_TEMPLATE)
builder.addKind("Enchantment", icon, MinecraftTemplates.FORGE_1_17_ENCHANTMENT_TEMPLATE)
}
}
if (isFabric) {
val icon = PlatformAssets.FABRIC_ICON
builder.addKind("Block", icon, MinecraftTemplates.FABRIC_BLOCK_TEMPLATE)
builder.addKind("Item", icon, MinecraftTemplates.FABRIC_ITEM_TEMPLATE)
builder.addKind("Enchantment", icon, MinecraftTemplates.FABRIC_ENCHANTMENT_TEMPLATE)
}
}
override fun isAvailable(dataContext: DataContext): Boolean {
val psi = dataContext.getData(CommonDataKeys.PSI_ELEMENT)
val module = psi?.findModule() ?: return false
val isFabricMod = MinecraftFacet.getInstance(module, FabricModuleType) != null
val isForgeMod = MinecraftFacet.getInstance(module, ForgeModuleType) != null
val hasMcVersion = MinecraftFacet.getInstance(module, McpModuleType)?.getSettings()?.minecraftVersion != null
return (isFabricMod || isForgeMod && hasMcVersion) && super.isAvailable(dataContext)
}
override fun checkPackageExists(directory: PsiDirectory): Boolean {
val pkg = JavaDirectoryService.getInstance().getPackage(directory) ?: return false
val name = pkg.qualifiedName
return StringUtil.isEmpty(name) || PsiNameHelper.getInstance(directory.project).isQualifiedName(name)
}
override fun getNavigationElement(createdElement: PsiClass): PsiElement? {
return createdElement.lBrace
}
override fun doCreate(dir: PsiDirectory, className: String, templateName: String): PsiClass? {
return JavaDirectoryService.getInstance().createClass(dir, className, templateName, false)
}
private class ClassInputValidator(
private val project: Project,
private val directory: PsiDirectory
) : InputValidatorEx {
override fun getErrorText(inputString: String): String? {
if (inputString.isNotEmpty() && !PsiNameHelper.getInstance(project).isQualifiedName(inputString)) {
return JavaErrorBundle.message("create.class.action.this.not.valid.java.qualified.name")
}
val shortName = StringUtil.getShortName(inputString)
val languageLevel = PsiUtil.getLanguageLevel(directory)
return if (HighlightClassUtil.isRestrictedIdentifier(shortName, languageLevel)) {
JavaErrorBundle.message("restricted.identifier", shortName)
} else {
null
}
}
override fun checkInput(inputString: String): Boolean =
inputString.isNotBlank() && getErrorText(inputString) == null
override fun canClose(inputString: String): Boolean =
checkInput(inputString)
}
private companion object {
private const val CAPTION = "Minecraft Class"
}
}
| mit | b8f6e5975ef08d7f909c1b30fafa2401 | 44.680556 | 120 | 0.718912 | 4.763215 | false | false | false | false |
esofthead/mycollab | mycollab-web/src/main/java/com/mycollab/module/project/fielddef/ClientTableFieldDef.kt | 3 | 1640 | package com.mycollab.module.project.fielddef
import com.mycollab.common.TableViewField
import com.mycollab.common.i18n.ClientI18nEnum
import com.mycollab.common.i18n.GenericI18Enum
import com.mycollab.vaadin.web.ui.WebUIConstants
/**
* @author MyCollab Ltd
* @since 7.0.0
*/
object ClientTableFieldDef {
@JvmField
val selected = TableViewField(null, "selected", WebUIConstants.TABLE_CONTROL_WIDTH)
@JvmField
val action = TableViewField(null, "id", WebUIConstants.TABLE_ACTION_CONTROL_WIDTH)
@JvmField
val accountname = TableViewField(ClientI18nEnum.FORM_ACCOUNT_NAME, "name", WebUIConstants.TABLE_X_LABEL_WIDTH)
@JvmField
val city = TableViewField(ClientI18nEnum.FORM_BILLING_CITY, "city", WebUIConstants.TABLE_X_LABEL_WIDTH)
@JvmField
val phoneoffice = TableViewField(ClientI18nEnum.FORM_OFFICE_PHONE, "phoneoffice", WebUIConstants.TABLE_M_LABEL_WIDTH)
@JvmField
val email = TableViewField(GenericI18Enum.FORM_EMAIL, "email", WebUIConstants.TABLE_EMAIL_WIDTH)
@JvmField
val assignUser = TableViewField(GenericI18Enum.FORM_ASSIGNEE, "assignUserFullName", WebUIConstants.TABLE_X_LABEL_WIDTH)
@JvmField
val website = TableViewField(ClientI18nEnum.FORM_WEBSITE, "website", WebUIConstants.TABLE_X_LABEL_WIDTH)
@JvmField
val type = TableViewField(GenericI18Enum.FORM_TYPE, "type", WebUIConstants.TABLE_X_LABEL_WIDTH)
@JvmField
val ownership = TableViewField(ClientI18nEnum.FORM_OWNERSHIP, "ownership", WebUIConstants.TABLE_X_LABEL_WIDTH)
@JvmField
val fax = TableViewField(ClientI18nEnum.FORM_FAX, "fax", WebUIConstants.TABLE_M_LABEL_WIDTH)
} | agpl-3.0 | 2e211e74dea96e23c23557d789b9c45d | 35.466667 | 123 | 0.764634 | 3.580786 | false | false | false | false |
Tvede-dk/CommonsenseAndroidKotlin | system/src/main/kotlin/com/commonsense/android/kotlin/system/base/BaseSplashActivity.kt | 1 | 4293 | package com.commonsense.android.kotlin.system.base
import android.app.*
import android.os.*
import android.support.annotation.*
import android.view.*
import com.commonsense.android.kotlin.base.debug.*
import com.commonsense.android.kotlin.system.*
import com.commonsense.android.kotlin.system.base.helpers.*
import com.commonsense.android.kotlin.system.extensions.*
import kotlinx.coroutines.*
import kotlinx.coroutines.android.*
/**
* Created by Kasper Tvede on 1/29/2018.
* Purpose: handling the splash screen as an activity; it will basically disallow the wrong way to make real splash screens;
* the intention is to help, educate, and guide, the implementation of a splash screen;
* calling basically any view related functions will throw a describing exception with the
*
*/
abstract class BaseSplashActivity : Activity() {
/**
* The text should say enough.
* Its the full blown description of what you / the user did wrong.
*/
private val basicDescriptionString = "\n\nAccessing / using the view as/ in a splash screen is wrong\n" +
"The splash screen should only present the next activity after the app has loaded\n" +
"this means that you are properly trying to make the splash screen in code;\n" +
"how to make a proper splash screen in android , see\n" +
"https://www.youtube.com/watch?v=E5Xu2iNHRkk (App Launch time & Themed launch screens (Android Performance Patterns Season 6 Ep. 4))\n" +
"or the example splash screen bundled with the library.\n" +
"https://github.com/Tvede-dk/CommonsenseAndroidKotlin/tree/master/system/src/main/java/com/commonsense/android/kotlin/system/base/BaseSplashActivity.kt\n"
//region forbidden function calls for a splash screen (will throw the bad usage exception).
// The RestrictTo to is to further allow lint to also help "catching" this,
// although not the correct naming and error message, the error will be highlighted.
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
final override fun setContentView(layoutResID: Int): Unit =
throw BadUsageException(basicDescriptionString)
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
final override fun setContentView(view: View?): Unit =
throw BadUsageException(basicDescriptionString)
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
final override fun setContentView(view: View?, params: ViewGroup.LayoutParams?): Unit =
throw BadUsageException(basicDescriptionString)
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
final override fun <T : View> findViewById(id: Int): T =
throw BadUsageException(basicDescriptionString)
//endregion
/**
* Called when the application is loaded and the splash is ready to be dismissed.
* You may not call finish or alike, since that is taken care of.
* all you have to do is start the next activity and or "any other"
* business logic that needs taken care of before the app is "ready".
*/
abstract fun onAppLoaded()
// should give a warning if someone tries to override the onCreate, this is very discouraged.
// use the onAppLoaded hook.
final override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
afterOnCreate()
}
private fun afterOnCreate() = GlobalScope.launch(Dispatchers.Main, CoroutineStart.UNDISPATCHED) {
//start pre loading views. since we are a splash screen, we are "allowed" to take "some"
//time, thus we can stall the loading (not the ui thread) until we have loaded all the views to preload.
preloadViews(viewsToPreload)
//when pre loading is done, then prepare the next screen and start the app.
onAppLoaded()
//and close the splash screen
safeFinish()
}
/**
* Specifies which layouts should be loaded in the background
* (if that fails, no pre loading will occur for that view).
*/
abstract val viewsToPreload: LayoutResList
fun toPrettyString(): String {
return "Base splash activity - viewsToPreload" +
viewsToPreload.views.map { "layout id: $it" }.prettyStringContent()
}
override fun toString(): String = toPrettyString()
}
| mit | 16a908650506b344a4f16a75d19041e5 | 44.670213 | 166 | 0.710692 | 4.448705 | false | false | false | false |
vmiklos/vmexam | osm/addr-osmify-kotlin/src/main/kotlin/NominatimResult.kt | 1 | 669 | /*
* Copyright 2020 Miklos Vajna. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package hu.vmiklos.addr_osmify
import com.google.gson.annotations.SerializedName
/**
* NominatimResult represents one element in the result array from
* Nominatim.
*/
class NominatimResult {
@SerializedName("class")
var clazz: String = String()
var lat: String = String()
var lon: String = String()
@SerializedName("osm_type")
var osmType: String = String()
@SerializedName("osm_id")
var osmId: String = String()
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
| mit | 7cc6541ee806e6753bdfbbf467d0fa94 | 25.76 | 73 | 0.698057 | 3.558511 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/controls/AnswersCounterFragment.kt | 1 | 4502 | package de.westnordost.streetcomplete.controls
import android.content.SharedPreferences
import androidx.fragment.app.Fragment
import de.westnordost.streetcomplete.Injector
import de.westnordost.streetcomplete.Prefs
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.quest.UnsyncedChangesCountListener
import de.westnordost.streetcomplete.data.quest.UnsyncedChangesCountSource
import de.westnordost.streetcomplete.data.upload.UploadProgressListener
import de.westnordost.streetcomplete.data.upload.UploadProgressSource
import de.westnordost.streetcomplete.data.user.QuestStatisticsDao
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import javax.inject.Inject
/** Fragment that shows (and hides) the undo button, based on whether there is anything to undo */
class AnswersCounterFragment : Fragment(R.layout.fragment_answers_counter),
CoroutineScope by CoroutineScope(Dispatchers.Main) {
@Inject internal lateinit var uploadProgressSource: UploadProgressSource
@Inject internal lateinit var prefs: SharedPreferences
@Inject internal lateinit var questStatisticsDao: QuestStatisticsDao
@Inject internal lateinit var unsyncedChangesCountSource: UnsyncedChangesCountSource
private val answersCounterView get() = view as AnswersCounterView
private val uploadProgressListener = object : UploadProgressListener {
override fun onStarted() { launch(Dispatchers.Main) { updateProgress(true) } }
override fun onFinished() { launch(Dispatchers.Main) { updateProgress(false) } }
}
private val unsyncedChangesCountListener = object : UnsyncedChangesCountListener {
override fun onUnsyncedChangesCountIncreased() { launch(Dispatchers.Main) { updateCount(true) }}
override fun onUnsyncedChangesCountDecreased() { launch(Dispatchers.Main) { updateCount(true) }}
}
private val questStatisticsListener = object : QuestStatisticsDao.Listener {
override fun onAddedOne(questType: String) {
launch(Dispatchers.Main) {
answersCounterView.setUploadedCount(answersCounterView.uploadedCount + 1, true)
}
}
override fun onSubtractedOne(questType: String) {
launch(Dispatchers.Main) {
launch(Dispatchers.Main) {
answersCounterView.setUploadedCount(answersCounterView.uploadedCount - 1, true)
}
}
}
override fun onReplacedAll() {
launch(Dispatchers.Main) { updateCount(false) }
}
}
/* --------------------------------------- Lifecycle ---------------------------------------- */
init {
Injector.applicationComponent.inject(this)
}
override fun onStart() {
super.onStart()
/* If autosync is on, the answers counter also shows the upload progress bar instead of
* upload button, and shows the uploaded + uploadable amount of quests.
*/
updateProgress(uploadProgressSource.isUploadInProgress)
updateCount(false)
if (isAutosync) {
uploadProgressSource.addUploadProgressListener(uploadProgressListener)
unsyncedChangesCountSource.addListener(unsyncedChangesCountListener)
}
questStatisticsDao.addListener(questStatisticsListener)
}
override fun onStop() {
super.onStop()
uploadProgressSource.removeUploadProgressListener(uploadProgressListener)
questStatisticsDao.removeListener(questStatisticsListener)
unsyncedChangesCountSource.removeListener(unsyncedChangesCountListener)
}
override fun onDestroy() {
super.onDestroy()
coroutineContext.cancel()
}
private val isAutosync: Boolean get() =
Prefs.Autosync.valueOf(prefs.getString(Prefs.AUTOSYNC, "ON")!!) == Prefs.Autosync.ON
private fun updateProgress(isUploadInProgress: Boolean) {
answersCounterView.showProgress = isUploadInProgress && isAutosync
}
private fun updateCount(animated: Boolean) {
/* if autosync is on, show the uploaded count + the to-be-uploaded count (but only those
uploadables that will be part of the statistics, so no note stuff) */
val amount = questStatisticsDao.getTotalAmount() + if (isAutosync) unsyncedChangesCountSource.questCount else 0
answersCounterView.setUploadedCount(amount, animated)
}
} | gpl-3.0 | 2f8defb48c4533acc9117fea50105927 | 42.718447 | 119 | 0.721235 | 5.058427 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/codegen/lambda/lambda9.kt | 1 | 536 | fun main(args : Array<String>) {
val lambdas = ArrayList<() -> Unit>()
for (i in 0..1) {
var x = Integer(0)
val istr = i.toString()
lambdas.add {
println(istr)
println(x.toString())
x = x + 1
}
}
val lambda1 = lambdas[0]
val lambda2 = lambdas[1]
lambda1()
lambda2()
lambda1()
lambda2()
}
class Integer(val value: Int) {
override fun toString() = value.toString()
operator fun plus(other: Int) = Integer(value + other)
} | apache-2.0 | a0ae74a9db74cbaab09ccd3f993408e1 | 18.888889 | 58 | 0.522388 | 3.621622 | false | false | false | false |
Adventech/sabbath-school-android-2 | features/media/src/main/kotlin/app/ss/media/playback/ui/spec/VideosInfoSpec.kt | 1 | 1574 | /*
* Copyright (c) 2022. Adventech <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package app.ss.media.playback.ui.spec
import androidx.compose.runtime.Immutable
import app.ss.models.media.SSVideo
import app.ss.models.media.SSVideosInfo
@Immutable
data class VideosInfoSpec(
val id: String,
val artist: String,
val clips: List<SSVideo>,
val lessonIndex: String
)
internal fun SSVideosInfo.toSpec() = VideosInfoSpec(
id = id,
artist = artist,
clips = clips,
lessonIndex = lessonIndex
)
| mit | d86969ea9e1f43dd96113fda6f087b7a | 36.47619 | 80 | 0.751588 | 4.197333 | false | false | false | false |
PolymerLabs/arcs | java/arcs/core/util/ArcsInstant.kt | 1 | 2608 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.util
/**
* Provides a platform-independent version of [ArcsInstant]
* from java.time.Instant.
*/
class ArcsInstant private constructor(
val platformInstant: PlatformInstant
) : Number(), Comparable<ArcsInstant> {
@Suppress("NewApi") // See b/167491554
fun toEpochMilli(): Long = platformInstant.toEpochMilli()
@Suppress("NewApi") // See b/167491554
override operator fun compareTo(other: ArcsInstant): Int =
platformInstant.compareTo(other.platformInstant)
@Suppress("NewApi") // See b/167491554
override fun toString(): String = platformInstant.toString()
@Suppress("NewApi") // See b/167491554
override fun equals(other: Any?): Boolean {
if (other == null || other !is ArcsInstant) return false
return platformInstant == other.platformInstant
}
override fun hashCode(): Int {
return platformInstant.hashCode()
}
@Suppress("NewApi") // See b/167491554
fun plus(time: ArcsDuration): ArcsInstant =
ArcsInstant(platformInstant.plus(time.toPlatform()))
@Suppress("NewApi") // See b/167491554
fun minus(time: ArcsDuration): ArcsInstant =
ArcsInstant(platformInstant.minus(time.toPlatform()))
fun toPlatform() = platformInstant
companion object {
@Suppress("NewApi") // See b/167491554
fun ofEpochMilli(millis: Long): ArcsInstant =
ArcsInstant(PlatformInstant.ofEpochMilli(millis))
@Suppress("NewApi") // See b/167491554
fun now(): ArcsInstant = ArcsInstant(PlatformInstant.now())
}
@Suppress("NewApi") // See b/167491554
override fun toByte(): Byte = platformInstant.toEpochMilli().toByte()
@Suppress("NewApi") // See b/167491554
override fun toChar(): Char = platformInstant.toEpochMilli().toChar()
@Suppress("NewApi") // See b/167491554
override fun toDouble(): Double = platformInstant.toEpochMilli().toDouble()
@Suppress("NewApi") // See b/167491554
override fun toFloat(): Float = platformInstant.toEpochMilli().toFloat()
@Suppress("NewApi") // See b/167491554
override fun toInt(): Int = platformInstant.toEpochMilli().toInt()
@Suppress("NewApi") // See b/167491554
override fun toLong(): Long = platformInstant.toEpochMilli().toLong()
@Suppress("NewApi") // See b/167491554
override fun toShort(): Short = platformInstant.toEpochMilli().toShort()
}
| bsd-3-clause | fa3d36349fa1a21968c5f07fc9d425f4 | 31.6 | 96 | 0.716258 | 3.97561 | false | false | false | false |
Maccimo/intellij-community | java/compiler/tests/com/intellij/compiler/artifacts/propertybased/ArtifactsPropertyTest.kt | 2 | 42816 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.compiler.artifacts.propertybased
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.packaging.artifacts.*
import com.intellij.packaging.elements.*
import com.intellij.packaging.impl.artifacts.PlainArtifactType
import com.intellij.packaging.impl.artifacts.workspacemodel.ArtifactBridge
import com.intellij.packaging.impl.artifacts.workspacemodel.ArtifactManagerBridge.Companion.artifactsMap
import com.intellij.packaging.impl.artifacts.workspacemodel.forThisAndFullTree
import com.intellij.packaging.impl.elements.ArtifactRootElementImpl
import com.intellij.packaging.impl.elements.DirectoryPackagingElement
import com.intellij.packaging.impl.elements.FileCopyPackagingElement
import com.intellij.packaging.ui.ArtifactEditorContext
import com.intellij.packaging.ui.PackagingElementPresentation
import com.intellij.testFramework.ApplicationRule
import com.intellij.testFramework.DisposableRule
import com.intellij.testFramework.UsefulTestCase.assertNotEmpty
import com.intellij.testFramework.rules.ProjectModelRule
import com.intellij.util.ui.EmptyIcon
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.addArtifactEntity
import com.intellij.workspaceModel.storage.bridgeEntities.addArtifactRootElementEntity
import com.intellij.workspaceModel.storage.bridgeEntities.api.ArtifactEntity
import com.intellij.workspaceModel.storage.bridgeEntities.api.CompositePackagingElementEntity
import com.intellij.workspaceModel.storage.bridgeEntities.api.PackagingElementEntity
import com.intellij.workspaceModel.storage.impl.VersionedEntityStorageImpl
import org.jetbrains.jetCheck.Generator
import org.jetbrains.jetCheck.ImperativeCommand
import org.jetbrains.jetCheck.PropertyChecker
import com.intellij.workspaceModel.storage.bridgeEntities.api.modifyEntity
import org.junit.Assert.*
import org.junit.Assume.assumeTrue
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import java.util.function.Supplier
import javax.swing.Icon
class ArtifactsPropertyTest {
companion object {
@ClassRule
@JvmField
val application = ApplicationRule()
private const val MAX_ARTIFACT_NUMBER = 50
}
@Rule
@JvmField
val projectModel = ProjectModelRule()
@Rule
@JvmField
val disposableRule = DisposableRule()
// This is a code generator for failed tests.
// At the moment it's incomplete and should be updated if some execution paths are missing
lateinit var codeMaker: CodeMaker
@Test
fun `property test`() {
assumeTrue(WorkspaceModel.enabledForArtifacts)
val writeDisposable = writeActionDisposable(disposableRule.disposable)
invokeAndWaitIfNeeded {
PackagingElementType.EP_NAME.point.registerExtension(MyWorkspacePackagingElementType, writeDisposable)
PackagingElementType.EP_NAME.point.registerExtension(MyCompositeWorkspacePackagingElementType, writeDisposable)
customArtifactTypes.forEach {
ArtifactType.EP_NAME.point.registerExtension(it, writeDisposable)
}
}
PropertyChecker.checkScenarios {
codeMaker = CodeMaker()
ImperativeCommand {
try {
it.executeCommands(Generator.sampledFrom(
RenameArtifact(),
AddArtifact(),
RemoveArtifact(),
ChangeBuildOnMake(),
ChangeArtifactType(),
AddPackagingElementTree(),
GetPackagingElement(),
FindCompositeChild(),
RemoveAllChildren(),
GetAllArtifacts(),
GetSortedArtifacts(),
GetAllArtifactsIncludingInvalid(),
FindByNameExisting(),
FindByNameNonExisting(),
FindByType(),
CreateViaWorkspaceModel(),
RenameViaWorkspaceModel(),
ChangeOnBuildViaWorkspaceModel(),
ChangeArtifactTypeViaWorkspaceModel(),
RemoveViaWorkspaceModel(),
))
}
finally {
codeMaker.finish()
makeChecksHappy {
val artifacts = ArtifactManager.getInstance(projectModel.project).artifacts
val modifiableModel = ArtifactManager.getInstance(projectModel.project).createModifiableModel()
artifacts.forEach {
modifiableModel.removeArtifact(it)
}
modifiableModel.commit()
WorkspaceModel.getInstance(projectModel.project).updateProjectModel {
it.replaceBySource({ true }, MutableEntityStorage.create())
}
}
it.logMessage("------- Code -------")
it.logMessage(codeMaker.get())
}
}
}
}
inner class GetPackagingElement : ImperativeCommand {
override fun performCommand(env: ImperativeCommand.Environment) {
val artifactBridge = selectArtifactBridge(env, "get packaging element") ?: return
makeChecksHappy {
val modifiableModel = ArtifactManager.getInstance(projectModel.project).createModifiableModel()
val modifiableArtifact = modifiableModel.getOrCreateModifiableArtifact(artifactBridge)
val (parent, child) = chooseSomeElementFromTree(env, modifiableArtifact)
if (parent == null) {
modifiableModel.dispose()
return@makeChecksHappy
}
val newChild = parent.addOrFindChild(child)
checkResult(env) {
assertSame(child, newChild)
}
modifiableModel.commit()
}
}
}
inner class FindCompositeChild : ImperativeCommand {
override fun performCommand(env: ImperativeCommand.Environment) {
val artifactBridge = selectArtifactBridge(env, "get packaging element") ?: return
makeChecksHappy {
val modifiableModel = ArtifactManager.getInstance(projectModel.project).createModifiableModel()
val modifiableArtifact = modifiableModel.getOrCreateModifiableArtifact(artifactBridge)
val (parent, child) = chooseSomeElementFromTree(env, modifiableArtifact)
if (parent == null || child !is CompositePackagingElement<*>) {
modifiableModel.dispose()
return@makeChecksHappy
}
val names = parent.children.filterIsInstance<CompositePackagingElement<*>>().map { it.name }
if (names.size != names.toSet().size) {
modifiableModel.dispose()
return@makeChecksHappy
}
val newChild = parent.findCompositeChild(child.name)
checkResult(env) {
assertSame(child, newChild)
}
modifiableModel.commit()
}
}
}
inner class RemoveAllChildren : ImperativeCommand {
override fun performCommand(env: ImperativeCommand.Environment) {
val artifactBridge = selectArtifactBridge(env, "get packaging element") ?: return
val (rootElement, removedChild, parent) = makeChecksHappy {
val modifiableModel = ArtifactManager.getInstance(projectModel.project).createModifiableModel()
val modifiableArtifact = modifiableModel.getOrCreateModifiableArtifact(artifactBridge)
val modifiableModelVal = codeMaker.makeVal("modifiableModel", "ArtifactManager.getInstance(project).createModifiableModel()")
val modifiableArtifactVal = codeMaker.makeVal("modifiableArtifact", "${modifiableModelVal}.getOrCreateModifiableArtifact(${
codeMaker.v("chosenArtifact")
})")
val (parent, child) = chooseSomeElementFromTree(env, modifiableArtifact)
if (parent == null) {
modifiableModel.dispose()
return@makeChecksHappy null
}
parent.removeAllChildren()
env.logMessage("Removing some package element for ${artifactBridge.name}")
codeMaker.addLine("${codeMaker.v("chosenParent")}.removeAllChildren()")
// It's important to get root element
// Otherwise diff will be injected into the root element
val rootElement = modifiableArtifact.rootElement
modifiableModel.commit()
val rootElementVal = codeMaker.makeVal("rootElement", "$modifiableArtifactVal.rootElement")
codeMaker.addLine("$modifiableModelVal.commit()")
codeMaker.addLine("return@runWriteAction Triple($rootElementVal, ${codeMaker.v("chosenChild")}, ${codeMaker.v("chosenParent")})")
Triple(rootElement, child, parent)
} ?: return
checkResult(env) {
val manager = ArtifactManager.getInstance(projectModel.project)
val foundArtifact = runReadAction { manager.findArtifact(artifactBridge.name) }!!
val managerVal = codeMaker.makeVal("manager", "ArtifactManager.getInstance(project)")
val foundArtifactVal = codeMaker.makeVal("foundArtifact",
"$managerVal.findArtifact(${codeMaker.v("chosenArtifact")}.name)!!")
val artifactEntity = WorkspaceModel.getInstance(projectModel.project).entityStorage.current
.entities(ArtifactEntity::class.java).find { it.name == artifactBridge.name }!!
assertElementsEquals(rootElement, foundArtifact.rootElement)
assertTreesEquals(projectModel.project, foundArtifact.rootElement, artifactEntity.rootElement!!)
codeMaker.scope("$foundArtifactVal.rootElement.forThisAndFullTree") {
codeMaker.scope("if (it === ${codeMaker.v("happyResult")}.third)") {
codeMaker.addLine("assertTrue(it.children.none { it.isEqualTo(${codeMaker.v("happyResult")}.second) })")
}
}
foundArtifact.rootElement.forThisAndFullTree {
if (it === parent) {
assertTrue(it.children.none { it.isEqualTo(removedChild) })
}
}
}
}
}
inner class AddPackagingElementTree : ImperativeCommand {
override fun performCommand(env: ImperativeCommand.Environment) {
val (selectedArtifact, manager) = selectArtifactViaBridge(env, "adding package element") ?: return
env.logMessage("Add new packaging elements tree to: ${selectedArtifact.name}")
val rootElement = makeChecksHappy {
val modifiableModel = manager.createModifiableModel()
val modifiableArtifact = modifiableModel.getOrCreateModifiableArtifact(selectedArtifact)
val (parent, _) = chooseSomeElementFromTree(env, modifiableArtifact)
val newTree = makeElementsTree(env).first
parent?.let { addChildSomehow(env, it, newTree) }
// It's important to get root element
// Otherwise diff will be injected into the root element
val rootElement = modifiableArtifact.rootElement
modifiableModel.commit()
rootElement
}
checkResult(env) {
val foundArtifact = runReadAction { manager.findArtifact(selectedArtifact.name) }!!
val artifactEntity = WorkspaceModel.getInstance(projectModel.project).entityStorage.current
.entities(ArtifactEntity::class.java).find { it.name == selectedArtifact.name }!!
assertElementsEquals(rootElement, foundArtifact.rootElement)
assertTreesEquals(projectModel.project, foundArtifact.rootElement, artifactEntity.rootElement!!)
}
}
private fun addChildSomehow(env: ImperativeCommand.Environment,
parent: CompositePackagingElement<*>,
newTree: PackagingElement<*>) {
when (env.generateValue(Generator.integers(0, 1), null)) {
0 -> parent.addOrFindChild(newTree)
1 -> parent.addFirstChild(newTree)
else -> error("Unexpected")
}
}
}
inner class CreateViaWorkspaceModel : ImperativeCommand {
override fun performCommand(env: ImperativeCommand.Environment) {
val workspaceModel = WorkspaceModel.getInstance(projectModel.project)
val artifactName = selectArtifactName(
env,
workspaceModel.entityStorage
.current
.entities(ArtifactEntity::class.java)
.map { it.name }
.toList()
) ?: run {
env.logMessage("Cannot select name for new artifact via workspace model")
return
}
makeChecksHappy {
workspaceModel.updateProjectModel {
val rootElement = createCompositeElementEntity(env, it)
val (_, id, _) = selectArtifactType(env)
it.addArtifactEntity(artifactName, id, true, null, rootElement, TestEntitySource)
}
}
env.logMessage("Add artifact via model: $artifactName")
checkResult(env) {
val foundArtifact = runReadAction { ArtifactManager.getInstance(projectModel.project).findArtifact(artifactName) }
assertNotNull(foundArtifact)
}
}
}
inner class RenameViaWorkspaceModel : ImperativeCommand {
override fun performCommand(env: ImperativeCommand.Environment) {
val workspaceModel = WorkspaceModel.getInstance(projectModel.project)
val artifactName = selectArtifactName(
env,
workspaceModel.entityStorage
.current
.entities(ArtifactEntity::class.java)
.map { it.name }
.toList()
) ?: run {
env.logMessage("Cannot select name for new artifact via workspace model")
return
}
val selectedArtifact = selectArtifactViaModel(env, workspaceModel, "renaming") ?: return
env.logMessage("Rename artifact via workspace model: ${selectedArtifact.name} -> $artifactName")
makeChecksHappy {
workspaceModel.updateProjectModel {
it.modifyEntity(selectedArtifact) {
this.name = artifactName
}
}
}
checkResult(env) {
val entities = workspaceModel.entityStorage.current.entities(ArtifactEntity::class.java)
assertTrue(entities.none { it.name == selectedArtifact.name })
assertTrue(entities.any { it.name == artifactName })
onManager(env) { manager ->
val allArtifacts = runReadAction{ manager.artifacts }
assertTrue(allArtifacts.none { it.name == selectedArtifact.name })
assertTrue(allArtifacts.any { it.name == artifactName })
}
}
}
}
inner class ChangeOnBuildViaWorkspaceModel : ImperativeCommand {
override fun performCommand(env: ImperativeCommand.Environment) {
val workspaceModel = WorkspaceModel.getInstance(projectModel.project)
val selectedArtifact = selectArtifactViaModel(env, workspaceModel, "changing option") ?: return
env.logMessage("Change build on make option for ${selectedArtifact.name}: Prev value: ${selectedArtifact.includeInProjectBuild}")
makeChecksHappy {
workspaceModel.updateProjectModel {
it.modifyEntity(selectedArtifact) {
this.includeInProjectBuild = !this.includeInProjectBuild
}
}
}
checkResult(env) {
val artifactEntity = workspaceModel.entityStorage.current.resolve(selectedArtifact.persistentId)!!
assertEquals(!selectedArtifact.includeInProjectBuild, artifactEntity.includeInProjectBuild)
onManager(env) { manager ->
val artifact = runReadAction { manager.findArtifact(selectedArtifact.name) }!!
assertEquals(!selectedArtifact.includeInProjectBuild, artifact.isBuildOnMake)
}
}
}
}
inner class ChangeArtifactTypeViaWorkspaceModel : ImperativeCommand {
override fun performCommand(env: ImperativeCommand.Environment) {
val workspaceModel = WorkspaceModel.getInstance(projectModel.project)
val selectedArtifact = selectArtifactViaModel(env, workspaceModel, "changing artifact type") ?: return
val (_, id, _) = selectArtifactType(env)
env.logMessage("Change artifact type for ${selectedArtifact.name}: Prev value: ${selectedArtifact.artifactType}")
makeChecksHappy {
workspaceModel.updateProjectModel {
it.modifyEntity(selectedArtifact) {
this.artifactType = id
}
}
}
checkResult(env) {
val artifactEntity = artifactEntity(projectModel.project, selectedArtifact.name)
assertEquals(id, artifactEntity.artifactType)
onManager(env) { manager ->
val artifact = runReadAction { manager.findArtifact(selectedArtifact.name)!! }
assertEquals(id, artifact.artifactType.id)
}
}
}
}
inner class RemoveViaWorkspaceModel : ImperativeCommand {
override fun performCommand(env: ImperativeCommand.Environment) {
val workspaceModel = WorkspaceModel.getInstance(projectModel.project)
val selectedArtifact = selectArtifactViaModel(env, workspaceModel, "removing") ?: return
env.logMessage("Remove artifact: ${selectedArtifact.name}")
makeChecksHappy {
workspaceModel.updateProjectModel {
it.removeEntity(selectedArtifact)
}
}
checkResult(env) {
val entities = workspaceModel.entityStorage.current.entities(ArtifactEntity::class.java)
assertTrue(entities.none { it.name == selectedArtifact.name })
onManager(env) { manager ->
val allArtifacts = runReadAction { manager.artifacts }
assertTrue(allArtifacts.none { it.name == selectedArtifact.name })
}
}
}
}
inner class FindByType : ImperativeCommand {
override fun performCommand(env: ImperativeCommand.Environment) {
val (selectedArtifact, _) = selectArtifactViaBridge(env, "finding by type") ?: return
val searchType = selectedArtifact.artifactType.id
env.logMessage("Search for artifact by type: $searchType")
onManager(env) { manager ->
assertNotEmpty(runReadAction { manager.getArtifactsByType(ArtifactType.findById(searchType)!!) })
}
}
}
inner class FindByNameNonExisting : ImperativeCommand {
override fun performCommand(env: ImperativeCommand.Environment) {
val artifactEntities = WorkspaceModel.getInstance(projectModel.project).entityStorage.current.entities(
ArtifactEntity::class.java).toList()
val artifactName = selectArtifactName(env, artifactEntities.map { it.name }) ?: run {
env.logMessage("Cannot select non-existing name for search")
return
}
env.logMessage("Search for artifact by name: $artifactName")
onManager(env) { manager ->
assertNull(runReadAction { manager.findArtifact (artifactName) })
}
}
}
inner class FindByNameExisting : ImperativeCommand {
override fun performCommand(env: ImperativeCommand.Environment) {
val artifactEntities = WorkspaceModel.getInstance(projectModel.project).entityStorage.current.entities(
ArtifactEntity::class.java).toList()
if (artifactEntities.isEmpty()) {
env.logMessage("Cannot select artifact for finding")
return
}
val artifactName = env.generateValue(Generator.sampledFrom(artifactEntities), null).name
env.logMessage("Search for artifact by name: $artifactName")
onManager(env) { manager ->
assertNotNull(runReadAction { manager.findArtifact (artifactName) })
}
}
}
inner class GetAllArtifactsIncludingInvalid : ImperativeCommand {
override fun performCommand(env: ImperativeCommand.Environment) {
val manager = ArtifactManager.getInstance(projectModel.project)
env.logMessage("Get all artifacts including invalid")
val artifacts = runReadAction { manager.allArtifactsIncludingInvalid }
artifacts.forEach { _ ->
// Nothing
}
}
}
inner class GetAllArtifacts : ImperativeCommand {
override fun performCommand(env: ImperativeCommand.Environment) {
val manager = ArtifactManager.getInstance(projectModel.project)
env.logMessage("Get all artifacts")
val artifacts = runReadAction { manager.artifacts }
artifacts.forEach { _ ->
// Nothing
}
}
}
inner class GetSortedArtifacts : ImperativeCommand {
override fun performCommand(env: ImperativeCommand.Environment) {
val manager = ArtifactManager.getInstance(projectModel.project)
env.logMessage("Get all artifacts sorted")
val artifacts = runReadAction { manager.sortedArtifacts }
artifacts.forEach { _ ->
// Nothing
}
}
}
inner class RemoveArtifact : ImperativeCommand {
override fun performCommand(env: ImperativeCommand.Environment) {
val (artifactForRemoval, _) = selectArtifactViaBridge(env, "removing") ?: return
val manager = ArtifactManager.getInstance(projectModel.project)
val initialArtifactsSize = runReadAction { manager.artifacts }.size
val removalName = artifactForRemoval.name
invokeAndWaitIfNeeded {
runWriteAction {
val modifiableModel = manager.createModifiableModel()
modifiableModel.removeArtifact(artifactForRemoval)
modifiableModel.commit()
}
}
checkResult(env) {
val newArtifactsList = runReadAction { manager.artifacts }
assertEquals(initialArtifactsSize - 1, newArtifactsList.size)
assertTrue(newArtifactsList.none { it.name == removalName })
val artifactEntities = WorkspaceModel.getInstance(projectModel.project).entityStorage.current.entities(ArtifactEntity::class.java)
assertTrue(artifactEntities.none { it.name == removalName })
}
}
}
inner class AddArtifact : ImperativeCommand {
override fun performCommand(env: ImperativeCommand.Environment) {
val artifactName = selectArtifactName(env)
val createRootElement = env.generateValue(Generator.sampledFrom(false, true, true, true, true, true), null)
val (rootElement, rootVal) = if (createRootElement) createCompositeElement(env) else null to null
val newArtifact = makeChecksHappy {
val (instance, _, typeVal) = selectArtifactType(env)
codeMaker.addLine("ArtifactManager.getInstance(project).addArtifact(\"$artifactName\", $typeVal, $rootVal)")
ArtifactManager.getInstance(projectModel.project).addArtifact(artifactName, instance, rootElement)
}
val newArtifactName = newArtifact.name
env.logMessage("Add new artifact via bridge: $newArtifactName. Final name: $newArtifactName")
checkResult(env) {
val bridgeVal = codeMaker.makeVal("bridgeArtifact", "artifact(project, \"$newArtifactName\")")
val bridgeArtifact = artifact(projectModel.project, newArtifactName)
val artifactEntityVal = codeMaker.makeVal("artifactEntity", "artifactEntity(project, \"$newArtifactName\")")
val artifactEntity = artifactEntity(projectModel.project, newArtifactName)
codeMaker.addLine("assertTreesEquals(project, $bridgeVal.rootElement, $artifactEntityVal.rootElement)")
assertTreesEquals(projectModel.project, bridgeArtifact.rootElement, artifactEntity.rootElement!!)
}
}
}
inner class RenameArtifact : ImperativeCommand {
override fun performCommand(env: ImperativeCommand.Environment) {
val manager = ArtifactManager.getInstance(projectModel.project)
val artifacts = runReadAction { manager.artifacts }
if (artifacts.isEmpty()) return
val index = env.generateValue(Generator.integers(0, artifacts.lastIndex), null)
val artifact = artifacts[index]
val newName = selectArtifactName(env, artifacts.map { it.name })
val oldName = artifact.name
env.logMessage("Rename artifact: $oldName -> $newName")
makeChecksHappy {
val modifiableModel = manager.createModifiableModel()
val modifiableArtifact = modifiableModel.getOrCreateModifiableArtifact(artifact)
modifiableArtifact.name = newName
modifiableModel.commit()
}
checkResult(env) {
assertEquals(newName, runReadAction{ manager.artifacts }[index].name)
val artifactEntities = WorkspaceModel.getInstance(projectModel.project).entityStorage.current.entities(ArtifactEntity::class.java)
assertTrue(artifactEntities.any { it.name == newName })
assertTrue(artifactEntities.none { it.name == oldName })
}
}
}
inner class ChangeBuildOnMake : ImperativeCommand {
override fun performCommand(env: ImperativeCommand.Environment) {
val manager = ArtifactManager.getInstance(projectModel.project)
val artifacts = runReadAction { manager.artifacts }
if (artifacts.isEmpty()) return
val index = env.generateValue(Generator.integers(0, artifacts.lastIndex), null)
val artifact = artifacts[index]
val oldBuildOnMake = artifact.isBuildOnMake
env.logMessage("Change isBuildOnMake for ${artifact.name}. New value: ${oldBuildOnMake}")
makeChecksHappy {
val modifiableModel = manager.createModifiableModel()
val modifiableArtifact = modifiableModel.getOrCreateModifiableArtifact(artifact)
modifiableArtifact.isBuildOnMake = !modifiableArtifact.isBuildOnMake
modifiableModel.commit()
}
checkResult(env) {
assertEquals(!oldBuildOnMake, runReadAction{ manager.artifacts }[index].isBuildOnMake)
val artifactEntities = WorkspaceModel.getInstance(projectModel.project).entityStorage.current.entities(ArtifactEntity::class.java)
assertTrue(artifactEntities.single { it.name == artifact.name }.includeInProjectBuild == !oldBuildOnMake)
}
}
}
inner class ChangeArtifactType : ImperativeCommand {
override fun performCommand(env: ImperativeCommand.Environment) {
val artifact = selectArtifactBridge(env, "change artifact type") ?: return
val artifactVal = codeMaker.v("chosenArtifact")
val (newArtifactType, id, typeVal) = selectArtifactType(env)
env.logMessage("Change artifact type for ${artifact.name}. New value: ${newArtifactType}")
makeChecksHappy {
modifyArtifact(artifact, artifactVal) {
codeMaker.addLine("$it.artifactType = $typeVal")
artifactType = newArtifactType
}
}
checkResult(env) {
assertEquals(newArtifactType, artifact(projectModel.project, artifact.name).artifactType)
val artifactEntityVal = codeMaker.makeVal("artifactEntity", "artifactEntity(project, \"${artifact.name}\")")
codeMaker.addLine("assertTrue($artifactEntityVal.artifactType == \"$id\")")
val artifactEntity = artifactEntity(projectModel.project, artifact.name)
assertTrue(artifactEntity.artifactType == id)
}
}
}
private fun modifyArtifact(artifact: Artifact, artifactVal: String, modification: ModifiableArtifact.(String) -> Unit) {
val modifiableModel = ArtifactManager.getInstance(projectModel.project).createModifiableModel()
val modifiableArtifact = modifiableModel.getOrCreateModifiableArtifact(artifact)
val modifiableModelVal = codeMaker.makeVal("modifiableModel", "ArtifactManager.getInstance(project).createModifiableModel()")
val modifiableArtifactVal = codeMaker.makeVal("modifiableArtifact", "$modifiableModelVal.getOrCreateModifiableArtifact($artifactVal)")
modifiableArtifact.modification(modifiableArtifactVal)
codeMaker.addLine("$modifiableModelVal.commit()")
modifiableModel.commit()
}
private fun selectArtifactName(env: ImperativeCommand.Environment): String {
return "Artifact-${env.generateValue(Generator.integers(0, MAX_ARTIFACT_NUMBER), null)}"
}
private fun selectArtifactName(env: ImperativeCommand.Environment, notLike: List<String>): String? {
var counter = 50
while (counter > 0) {
val name = "Artifact-${env.generateValue(Generator.integers(0, MAX_ARTIFACT_NUMBER), null)}"
if (name !in notLike) return name
counter--
}
return null
}
private fun createCompositeElement(env: ImperativeCommand.Environment): Pair<CompositePackagingElement<*>, String> {
val root = ArtifactRootElementImpl()
val rootVal = codeMaker.makeVal("artifactRoot", "ArtifactRootElementImpl()")
val value = env.generateValue(Generator.booleans(), null)
if (value) {
root.addFirstChild(makeElementsTree(env).first)
codeMaker.addLine("$rootVal.addFirstChild(${codeMaker.v("element_0")})")
}
return root to rootVal
}
private fun makeElementsTree(env: ImperativeCommand.Environment, depth: Int = 0): Pair<PackagingElement<*>, String> {
val value = env.generateValue(Generator.integers(0, 3), null)
val indent = " ".repeat(depth)
val (element, elementName) = when (value) {
0 -> {
val directoryName = env.generateValue(Generator.sampledFrom(names), null)
val element = DirectoryPackagingElement(directoryName)
val currentElementName = codeMaker.makeVal("element_$depth", "DirectoryPackagingElement(\"$directoryName\")")
env.logMessage("${indent}Generate DirectoryPackagingElement: $directoryName")
element to currentElementName
}
1 -> {
val outputName = env.generateValue(Generator.sampledFrom(names), null)
val pathName = "/" + env.generateValue(Generator.sampledFrom(names), null)
env.logMessage("${indent}Generate FileCopyPackagingElement ($pathName -> $outputName)")
val currentElementName = codeMaker.makeVal("element_$depth", "FileCopyPackagingElement(\"$pathName\", \"$outputName\")")
FileCopyPackagingElement(pathName, outputName) to currentElementName
}
2 -> {
val data = env.generateValue(Generator.sampledFrom(names), null)
env.logMessage("${indent}Generate MyWorkspacePackagingElement ($data)")
val currentElementName = codeMaker.makeVal("element_$depth", "MyWorkspacePackagingElement(\"$data\")")
MyWorkspacePackagingElement(data) to currentElementName
}
3 -> {
val data = env.generateValue(Generator.sampledFrom(names), null)
val name = env.generateValue(Generator.sampledFrom(names), null)
env.logMessage("${indent}Generate MyCompositeWorkspacePackagingElement ($data, $name)")
val currentElementName = codeMaker.makeVal("element_$depth", "MyCompositeWorkspacePackagingElement(\"$data\", \"$name\")")
MyCompositeWorkspacePackagingElement(data, name) to currentElementName
}
else -> error("Unexpected branch")
}
if (element is CompositePackagingElement<*>) {
if (depth < 5) {
// This is all magic numbers. Just trying to make less children for deeper layers of package elements tree
val maxChildren = when {
depth == 0 -> 5
depth in 1..2 -> 3
depth in 3..4 -> 2
depth > 4 -> 1
else -> 0
}
val amountOfChildren = env.generateValue(Generator.integers(0, maxChildren), null)
env.logMessage("${indent}- Generate $amountOfChildren children:")
for (i in 0 until amountOfChildren) {
val (child, name) = makeElementsTree(env, depth + 1)
element.addFirstChild(child)
codeMaker.addLine("$elementName.addFirstChild($name)")
}
}
}
return element to elementName
}
private fun createCompositeElementEntity(env: ImperativeCommand.Environment,
builder: MutableEntityStorage): CompositePackagingElementEntity {
return builder.addArtifactRootElementEntity(emptyList(), TestEntitySource)
}
private fun chooseSomeElementFromTree(env: ImperativeCommand.Environment,
artifact: Artifact): Pair<CompositePackagingElement<*>?, PackagingElement<*>> {
val root = artifact.rootElement
val allElements: MutableList<Pair<CompositePackagingElement<*>?, PackagingElement<*>>> = mutableListOf(null to root)
flatElements(root, allElements)
val (parent, child) = env.generateValue(Generator.sampledFrom(allElements), null)
val artifactVal = codeMaker.vOrNull("modifiableArtifact") ?: codeMaker.v("chosenArtifact")
var rootElementVal = codeMaker.makeVal("rootElement", "$artifactVal.rootElement")
if (root != child) {
val address = generateAddress(root, child)!!
var childElementVal = "($rootElementVal as CompositePackagingElement<*>).children[${address[0]}]"
address.drop(1).forEach {
rootElementVal = childElementVal
childElementVal = "($rootElementVal as CompositePackagingElement<*>).children[$it]"
}
codeMaker.makeVal("chosenParent", "$rootElementVal as CompositePackagingElement<*>")
codeMaker.makeVal("chosenChild", childElementVal)
}
else {
codeMaker.makeVal("chosenParent", null)
codeMaker.makeVal("chosenChild", rootElementVal)
}
return parent to child
}
private fun generateAddress(root: CompositePackagingElement<*>, child: PackagingElement<*>): List<Int>? {
root.children.forEachIndexed { index, packagingElement ->
val indexList = listOf(index)
if (packagingElement === child) return indexList
if (packagingElement is CompositePackagingElement<*>) {
val result = generateAddress(packagingElement, child)
if (result != null) {
return indexList + result
}
}
}
return null
}
private fun generateAddress(root: CompositePackagingElementEntity, child: PackagingElementEntity): List<Int>? {
root.children.forEachIndexed { index, packagingElement ->
if (packagingElement == child) return listOf(index)
if (packagingElement is CompositePackagingElementEntity) {
val result = generateAddress(packagingElement, child)
if (result != null) {
return result
}
}
}
return null
}
private fun selectArtifactType(env: ImperativeCommand.Environment): Triple<ArtifactType, String, String> {
val selector = env.generateValue(Generator.integers(0, allArtifactTypes.lastIndex), null)
val artifactVal = codeMaker.makeVal("artifactType", "allArtifactTypes[$selector]")
val instance = allArtifactTypes[selector]
return Triple(instance, instance.id, artifactVal)
}
private fun flatElements(currentElement: CompositePackagingElement<*>,
result: MutableList<Pair<CompositePackagingElement<*>?, PackagingElement<*>>>) {
currentElement.children.forEach {
result.add(currentElement to it)
if (it is CompositePackagingElement<*>) {
flatElements(it, result)
}
}
}
private fun selectArtifactViaBridge(env: ImperativeCommand.Environment, reason: String): Pair<Artifact, ArtifactManager>? {
val manager = ArtifactManager.getInstance(projectModel.project)
val artifacts = runReadAction { manager.artifacts }
if (artifacts.isEmpty()) {
env.logMessage("Cannot select artifact for $reason")
return null
}
val selectedArtifact = env.generateValue(Generator.sampledFrom(*artifacts), null)
val artifactIndex = artifacts.indexOf(selectedArtifact)
val managerVal = codeMaker.makeVal("manager", "ArtifactManager.getInstance(project)")
val artifactsVal = codeMaker.makeVal("artifacts", "$managerVal.artifacts")
codeMaker.makeVal("chosenArtifact", "$artifactsVal[$artifactIndex]")
return selectedArtifact to manager
}
fun selectArtifactViaModel(env: ImperativeCommand.Environment, workspaceModel: WorkspaceModel, reason: String): ArtifactEntity? {
val existingArtifacts = workspaceModel.entityStorage.current.entities(ArtifactEntity::class.java).toList()
if (existingArtifacts.isEmpty()) {
env.logMessage("Cannot select artifact for $reason")
return null
}
val selectedArtifact = env.generateValue(Generator.sampledFrom(existingArtifacts), null)
val artifactEntityId = existingArtifacts.indexOf(selectedArtifact)
codeMaker.makeVal("chosenArtifactEntity", "WorkspaceModel.getInstance(project).entityStorage.current.entities(ArtifactEntity::class.java).toList()[$artifactEntityId]")
return selectedArtifact
}
private fun selectArtifactBridge(env: ImperativeCommand.Environment, reason: String): Artifact? {
val viaBridge = env.generateValue(Generator.booleans(), null)
return if (viaBridge) {
selectArtifactViaBridge(env, reason)?.first
}
else {
val workspaceModel = WorkspaceModel.getInstance(projectModel.project)
val entity = selectArtifactViaModel(env, workspaceModel, reason) ?: return null
codeMaker.makeVal("chosenArtifact", "WorkspaceModel.getInstance(project).entityStorage.current.artifactsMap.getDataByEntity(${codeMaker.v("chosenArtifactEntity")})")
workspaceModel.entityStorage.current.artifactsMap.getDataByEntity(entity)
}
}
private inline fun checkResult(env: ImperativeCommand.Environment, action: () -> Unit) {
val checkResult = env.generateValue(Generator.booleans(), null)
env.logMessage("Check result: $checkResult")
if (checkResult) {
action()
}
assertArtifactsHaveStableStore()
}
private inline fun onManager(env: ImperativeCommand.Environment, action: (ArtifactModel) -> Unit) {
val onModifiableModel = env.generateValue(Generator.booleans(), null)
val manager = if (onModifiableModel) {
ArtifactManager.getInstance(projectModel.project).createModifiableModel()
}
else {
ArtifactManager.getInstance(projectModel.project)
}
action(manager)
if (onModifiableModel) (manager as ModifiableArtifactModel).dispose()
}
private fun assertArtifactsHaveStableStore() {
val manager = ArtifactManager.getInstance(projectModel.project)
runReadAction{ manager.artifacts }.forEach {
assertTrue((it as ArtifactBridge).entityStorage is VersionedEntityStorageImpl)
}
}
private val names = List(20) { "Name-$it" }
private fun <T> makeChecksHappy(action: () -> T): T {
return invokeAndWaitIfNeeded {
runWriteAction {
codeMaker.startScope("happyResult", "invokeAndWaitIfNeeded")
codeMaker.startScope("runWriteAction")
try {
return@runWriteAction action()
}
finally {
if (codeMaker.last()?.trimIndent()?.startsWith("return") != true) {
codeMaker.addLine("return@runWriteAction null")
}
codeMaker.finishScope()
codeMaker.finishScope()
}
}
}
}
private fun writeActionDisposable(parent: Disposable): Disposable {
val writeDisposable = Disposer.newDisposable()
Disposer.register(parent) {
invokeAndWaitIfNeeded {
runWriteAction {
Disposer.dispose(writeDisposable)
}
}
}
return writeDisposable
}
}
object TestEntitySource : EntitySource
class MyWorkspacePackagingElement(data: String) : PackagingElement<MyWorkspacePackagingElementState>(PackagingElementType.EP_NAME.findExtensionOrFail(MyWorkspacePackagingElementType::class.java)) {
constructor(): this("")
private val state: MyWorkspacePackagingElementState = MyWorkspacePackagingElementState(data)
override fun getState(): MyWorkspacePackagingElementState = state
override fun loadState(state: MyWorkspacePackagingElementState) {
this.state.data = state.data
}
override fun isEqualTo(element: PackagingElement<*>): Boolean = (element as? MyWorkspacePackagingElement)?.state?.data == state.data
override fun createPresentation(context: ArtifactEditorContext): PackagingElementPresentation {
throw UnsupportedOperationException()
}
}
class MyWorkspacePackagingElementState(var data: String = "")
object MyWorkspacePackagingElementType : PackagingElementType<MyWorkspacePackagingElement>("Custom-element", Supplier { "Custom Element" }) {
override fun canCreate(context: ArtifactEditorContext, artifact: Artifact): Boolean = true
override fun chooseAndCreate(context: ArtifactEditorContext,
artifact: Artifact,
parent: CompositePackagingElement<*>): MutableList<out PackagingElement<*>> {
throw UnsupportedOperationException()
}
override fun createEmpty(project: Project): MyWorkspacePackagingElement {
return MyWorkspacePackagingElement()
}
}
class MyCompositeWorkspacePackagingElement(data: String, name: String) : CompositePackagingElement<MyCompositeWorkspacePackagingElementState>(PackagingElementType.EP_NAME.findExtensionOrFail(MyCompositeWorkspacePackagingElementType::class.java)) {
constructor(): this("", "")
private val state: MyCompositeWorkspacePackagingElementState = MyCompositeWorkspacePackagingElementState(data, name)
override fun getState(): MyCompositeWorkspacePackagingElementState = state
override fun loadState(state: MyCompositeWorkspacePackagingElementState) {
this.state.data = state.data
}
override fun isEqualTo(element: PackagingElement<*>): Boolean = (element as? MyCompositeWorkspacePackagingElement)?.state?.data == state.data
override fun getName(): String = state.name
override fun rename(newName: String) {
state.name = newName
}
override fun createPresentation(context: ArtifactEditorContext): PackagingElementPresentation {
throw UnsupportedOperationException()
}
override fun toString(): String {
return "MyCompositeWorkspacePackagingElement(state=$state)"
}
}
data class MyCompositeWorkspacePackagingElementState(var data: String = "", var name: String = "")
object MyCompositeWorkspacePackagingElementType : PackagingElementType<MyCompositeWorkspacePackagingElement>("Composite-custom-element", Supplier { "Composite Custom Element" }) {
override fun canCreate(context: ArtifactEditorContext, artifact: Artifact): Boolean = true
override fun chooseAndCreate(context: ArtifactEditorContext,
artifact: Artifact,
parent: CompositePackagingElement<*>): MutableList<out PackagingElement<*>> {
throw UnsupportedOperationException()
}
override fun createEmpty(project: Project): MyCompositeWorkspacePackagingElement {
return MyCompositeWorkspacePackagingElement()
}
}
internal val customArtifactTypes: List<ArtifactType> = List(10) {
object : ArtifactType("myArtifactType-$it", Supplier{ "myArtifactType-$it" }) {
override fun getIcon(): Icon = EmptyIcon.ICON_16
override fun getDefaultPathFor(kind: PackagingElementOutputKind): String = ""
override fun createRootElement(artifactName: String): CompositePackagingElement<*> {
return PackagingElementFactory.getInstance().createArtifactRootElement()
}
}
}
internal val allArtifactTypes = customArtifactTypes + PlainArtifactType.getInstance()
| apache-2.0 | 4052a8529e614ee14906ea1603fd53d1 | 40.730994 | 247 | 0.711206 | 5.156069 | false | false | false | false |
Tiofx/semester_6 | IAD/IAD_lab_2/src/main/kotlin/main/parse.kt | 1 | 1188 | package main
import util.*
import java.io.File
fun getUnionInformation(areaFile: File = "area.txt".getFromResources(),
populationFile: File = "population.txt".getFromResources(),
gdpFile: File = "gdp.txt".getFromResources()): Set<CountryInformation> =
union(areaFile.parseArea(), populationFile.parsePopulation(), gdpFile.parseGdp())
fun union(area: List<Area>, population: List<Population>, gdp: List<Gdp>): Set<CountryInformation> {
val countrySet = area.map {
val countryInformation = CountryInformation(it.country.getShortCountryName())
countryInformation.area = it.area
countryInformation
}.toSet()
population.forEach {
val countryName = it.country
countrySet.find { it.name == countryName.getShortCountryName() }?.population = it.populationAbsolute
}
gdp.forEach {
val countryName = it.country
countrySet.find { it.name == countryName.getShortCountryName() }?.gdp = it.gdp
}
val countryWithFullInfo = countrySet.filterNot {
it.area == -1.0 || it.population == -1 || it.gdp == -1.0
}.toSet()
return countryWithFullInfo
} | gpl-3.0 | 761a0666890192bb2008373f742cae7d | 35.030303 | 108 | 0.659933 | 4.068493 | false | false | false | false |
Tiofx/semester_6 | TOPK/TOPK_lab_4/src/main/kotlin/lab4/preCalculations/util.kt | 1 | 1091 | package lab4.preCalculations
import golem.eachIndexed
import golem.matrix.Matrix
import golem.set
val F_VALUE = 1 shl 0
val EQ_VALUE = 1 shl 1
val L_VALUE = 1 shl 2
fun Matrix<Double>.toF(): Matrix<Double> {
return this.toValue(lab4.preCalculations.F_VALUE)
}
fun Matrix<Double>.toEQ(): Matrix<Double> {
return this.toValue(lab4.preCalculations.EQ_VALUE)
}
fun Matrix<Double>.toL(): Matrix<Double> {
return this.toValue(lab4.preCalculations.L_VALUE)
}
private fun Matrix<Double>.toValue(value: Int): Matrix<Double> {
val copy = this.copy()
this.forEachIndexed { index, d ->
copy[index] =
(if (d.toInt() and value > 0) 1 else 0).toDouble()
}
return copy
}
fun Matrix<Double>.warshall(): Matrix<Double> {
val matrixPlus = this.copy()
matrixPlus.eachIndexed(fun(i: Int, j: Int, d: Double) {
if (matrixPlus[j, i] > 0) {
for (k in 0..matrixPlus.numCols() - 1) {
matrixPlus[j, k] = matrixPlus[j, k].toInt() or matrixPlus[i, k].toInt()
}
}
})
return matrixPlus
} | gpl-3.0 | 38a8ca695fe5d329d4e939e4e711683c | 22.234043 | 87 | 0.626031 | 3.180758 | false | false | false | false |
RadiationX/ForPDA | app/src/main/java/forpdateam/ru/forpda/presentation/devdb/search/SearchDevicesPresenter.kt | 1 | 2358 | package forpdateam.ru.forpda.presentation.devdb.search
import moxy.InjectViewState
import forpdateam.ru.forpda.common.Utils
import forpdateam.ru.forpda.common.mvp.BasePresenter
import forpdateam.ru.forpda.entity.remote.devdb.Brand
import forpdateam.ru.forpda.model.repository.devdb.DevDbRepository
import forpdateam.ru.forpda.presentation.IErrorHandler
import forpdateam.ru.forpda.presentation.Screen
import forpdateam.ru.forpda.presentation.TabRouter
/**
* Created by radiationx on 11.11.17.
*/
@InjectViewState
class SearchDevicesPresenter(
private val devDbRepository: DevDbRepository,
private val router: TabRouter,
private val errorHandler: IErrorHandler
) : BasePresenter<SearchDevicesView>() {
var searchQuery: String? = null
var currentData: Brand? = null
override fun onFirstViewAttach() {
super.onFirstViewAttach()
}
fun refresh() = search(searchQuery)
fun search(query: String?) {
searchQuery = query
if (searchQuery.isNullOrEmpty()) {
return
}
devDbRepository
.search(searchQuery.orEmpty())
.doOnSubscribe { viewState.setRefreshing(true) }
.doAfterTerminate { viewState.setRefreshing(false) }
.subscribe({
currentData = it
viewState.showData(it, searchQuery.orEmpty())
}, {
errorHandler.handle(it)
})
.untilDestroy()
}
fun openDevice(item: Brand.DeviceItem) {
currentData?.let {
router.navigateTo(Screen.DevDbDevice().apply {
deviceId = item.id
})
}
}
fun openSearch() {
router.navigateTo(Screen.DevDbSearch())
}
fun copyLink(item: Brand.DeviceItem) {
currentData?.let {
Utils.copyToClipBoard("https://4pda.to/devdb/${item.id}")
}
}
fun shareLink(item: Brand.DeviceItem) {
currentData?.let {
Utils.shareText("https://4pda.to/devdb/${item.id}")
}
}
fun createNote(item: Brand.DeviceItem) {
currentData?.let {
val title = "DevDb: ${it.title} ${item.title}"
val url = "https://4pda.to/devdb/" + item.id
viewState.showCreateNote(title, url)
}
}
}
| gpl-3.0 | 5fa501aadd5513744a9db8a626bcbacf | 27.756098 | 69 | 0.611959 | 4.5 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/debug/cookies/DebugCookiesViewModel.kt | 1 | 2051 | package org.wordpress.android.ui.debug.cookies
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import org.wordpress.android.ui.debug.cookies.DebugCookiesAdapter.DebugCookieItem
import org.wordpress.android.ui.utils.ListItemInteraction
import javax.inject.Inject
class DebugCookiesViewModel @Inject constructor(
private val debugCookieManager: DebugCookieManager
) : ViewModel() {
private val _uiState = MutableLiveData(UiState(getUpdatedItems()))
val uiState: LiveData<UiState> = _uiState
fun setCookie(host: String?, name: String?, value: String?) {
if (!host.isNullOrBlank() && !name.isNullOrBlank()) {
debugCookieManager.add(DebugCookie(host, name, value))
_uiState.value = UiState(
items = getUpdatedItems(),
hostInputText = host,
nameInputText = name,
valueInputText = value
)
}
}
private fun onItemClick(debugCookie: DebugCookie) {
_uiState.value = _uiState.value?.copy(
hostInputText = debugCookie.host,
nameInputText = debugCookie.name,
valueInputText = debugCookie.value
)
}
private fun onDeleteClick(debugCookie: DebugCookie) {
debugCookieManager.remove(debugCookie)
_uiState.value = _uiState.value?.copy(
items = getUpdatedItems()
)
}
private fun getUpdatedItems() = debugCookieManager.getAll().sortedBy { it.key }.map {
DebugCookieItem(
it.key,
it.host,
it.name,
it.value,
ListItemInteraction.create(it, ::onItemClick),
ListItemInteraction.create(it, ::onDeleteClick)
)
}
data class UiState(
val items: List<DebugCookieItem>,
val hostInputText: String? = null,
val nameInputText: String? = null,
val valueInputText: String? = null
)
}
| gpl-2.0 | a568c6b9d444feb43b6b4ec31cf6d79c | 33.183333 | 89 | 0.622623 | 4.837264 | false | false | false | false |
KotlinNLP/SimpleDNN | src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/recurrent/cfn/CFNLayer.kt | 1 | 3688 | /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.core.layers.models.recurrent.cfn
import com.kotlinnlp.simplednn.core.arrays.AugmentedArray
import com.kotlinnlp.simplednn.core.functionalities.activations.ActivationFunction
import com.kotlinnlp.simplednn.core.functionalities.activations.Sigmoid
import com.kotlinnlp.simplednn.core.layers.LayerType
import com.kotlinnlp.simplednn.core.layers.models.recurrent.*
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory
import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.Shape
/**
* The CFN Layer Structure.
*
* @property inputArray the input array of the layer
* @property inputType the input array type (default Dense)
* @property outputArray the output array of the layer
* @property params the parameters which connect the input to the output
* @property layersWindow the context window used for the forward and the backward
* @property activationFunction the activation function of the layer
* @property dropout the probability of dropout
*/
internal class CFNLayer<InputNDArrayType : NDArray<InputNDArrayType>>(
inputArray: AugmentedArray<InputNDArrayType>,
inputType: LayerType.Input,
outputArray: AugmentedArray<DenseNDArray>,
override val params: CFNLayerParameters,
layersWindow: LayersWindow,
activationFunction: ActivationFunction? = null,
dropout: Double
) : GatedRecurrentLayer<InputNDArrayType>(
inputArray = inputArray,
inputType = inputType,
outputArray = outputArray,
params = params,
layersWindow = layersWindow,
activationFunction = activationFunction,
dropout = dropout
) {
/**
*
*/
val candidate = AugmentedArray(values = DenseNDArrayFactory.emptyArray(Shape(outputArray.size)))
/**
*
*/
val inputGate = RecurrentLayerUnit<InputNDArrayType>(outputArray.size)
/**
*
*/
val forgetGate = RecurrentLayerUnit<InputNDArrayType>(outputArray.size)
/**
*
*/
var activatedPrevOutput: DenseNDArray? = null
/**
* The helper which executes the forward
*/
override val forwardHelper = CFNForwardHelper(layer = this)
/**
* The helper which executes the backward
*/
override val backwardHelper = CFNBackwardHelper(layer = this)
/**
* The helper which calculates the relevance
*/
override val relevanceHelper: GatedRecurrentRelevanceHelper? = null
/**
* Initialization: set the activation function of the gates
*/
init {
this.inputGate.setActivation(Sigmoid)
this.forgetGate.setActivation(Sigmoid)
if (this.activationFunction != null) {
this.candidate.setActivation(this.activationFunction)
}
}
/**
* Set the initial hidden array.
* This method should be used when this layer is used as initial hidden state in a recurrent neural network.
*
* @param array the initial hidden array
*/
override fun setInitHidden(array: DenseNDArray) {
TODO("not implemented")
}
/**
* Get the errors of the initial hidden array.
* This method should be used only if this layer is used as initial hidden state in a recurrent neural network.
*
* @return the errors of the initial hidden array
*/
override fun getInitHiddenErrors(): DenseNDArray {
TODO("not implemented")
}
}
| mpl-2.0 | 5fee85c3cebe1c6e8a8c3264bfbb4bea | 30.793103 | 113 | 0.736171 | 4.564356 | false | false | false | false |
square/picasso | picasso/src/main/java/com/squareup/picasso3/ContentStreamRequestHandler.kt | 1 | 2392 | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.picasso3
import android.content.ContentResolver
import android.content.Context
import android.net.Uri
import androidx.exifinterface.media.ExifInterface
import androidx.exifinterface.media.ExifInterface.ORIENTATION_NORMAL
import androidx.exifinterface.media.ExifInterface.TAG_ORIENTATION
import com.squareup.picasso3.Picasso.LoadedFrom.DISK
import okio.Source
import okio.source
import java.io.FileNotFoundException
internal open class ContentStreamRequestHandler(val context: Context) : RequestHandler() {
override fun canHandleRequest(data: Request): Boolean =
ContentResolver.SCHEME_CONTENT == data.uri?.scheme ?: false
override fun load(
picasso: Picasso,
request: Request,
callback: Callback
) {
var signaledCallback = false
try {
val requestUri = checkNotNull(request.uri)
val source = getSource(requestUri)
val bitmap = BitmapUtils.decodeStream(source, request)
val exifRotation = getExifOrientation(requestUri)
signaledCallback = true
callback.onSuccess(Result.Bitmap(bitmap, DISK, exifRotation))
} catch (e: Exception) {
if (!signaledCallback) {
callback.onError(e)
}
}
}
fun getSource(uri: Uri): Source {
val contentResolver = context.contentResolver
val inputStream = contentResolver.openInputStream(uri)
?: throw FileNotFoundException("can't open input stream, uri: $uri")
return inputStream.source()
}
protected open fun getExifOrientation(uri: Uri): Int {
val contentResolver = context.contentResolver
contentResolver.openInputStream(uri)?.use { input ->
return ExifInterface(input).getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL)
} ?: throw FileNotFoundException("can't open input stream, uri: $uri")
}
}
| apache-2.0 | 667bffee6bd17e489b413d2d6b780b0d | 34.701493 | 90 | 0.742475 | 4.513208 | false | false | false | false |
Abdel-RhmanAli/Inventory-App | app/src/main/java/com/example/android/inventory/ui/ItemsRecyclerViewAdapter.kt | 1 | 3857 | package com.example.android.inventory.ui
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.example.android.inventory.R
import com.example.android.inventory.model.Item
import kotlinx.android.synthetic.main.items_list_item.view.*
class ItemsRecyclerViewAdapter(
private var mItems: MutableList<Item>? = null,
private val mListener: ListInteractionListener,
private val mResources: RecyclerViewResources)
: RecyclerView.Adapter<ItemsRecyclerViewAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.items_list_item, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = mItems?.get(position)
var text: String?
item?.let {
holder.apply {
it.picture?.let { picture ->
//val pic = BitmapFactory.decodeByteArray(picture, 0, picture.size)
mItemImage.setImageBitmap(picture)
}
mItemName.text = it.name
text = when {
!it.type.isNullOrBlank() ->
mResources.getString(R.string.type) + it.type
else -> mResources.getString(R.string.type_unknown)
}
mItemType.text = text
text = when {
!it.amount.isNullOrBlank() -> mResources.getString(R.string.amount) + it.amount
else -> mResources.getString(R.string.amount_unknown)
}
mItemAmount.text = text
text = when {
!it.supplier.isNullOrBlank() -> mResources.getString(R.string.supplier) + it.type
else -> mResources.getString(R.string.supplier_unknown)
}
mItemSupplier.text = text
mView.setOnClickListener { _ ->
mListener.onRecyclerViewItemClickListener(it)
}
}
}
}
fun setItems(items: List<Item>?) {
mItems = items?.toMutableList()
notifyDataSetChanged()
}
fun getItem(position: Int): Item? {
return mItems?.get(position)
}
fun removeItem(position: Int): Item? {
mItems?.let {
val itemRemoved = it.removeAt(position)
notifyItemRemoved(position)
return itemRemoved
}
return null
}
fun addItem(item: Item?, position: Int) {
mItems?.let { mItems ->
item?.let { item ->
mItems.add(position, item)
notifyItemInserted(position)
}
}
}
fun removeAll() {
mItems?.let {
it.clear()
notifyDataSetChanged()
}
}
override fun getItemCount(): Int {
mItems?.let { return it.size }
return 0
}
inner class ViewHolder(val mView: View) : RecyclerView.ViewHolder(mView) {
val mItemImage: ImageView = mView.iv_item_image
val mItemName: TextView = mView.tv_item_name
val mItemSupplier: TextView = mView.tv_item_supplier
val mItemAmount: TextView = mView.tv_item_amount
val mItemType: TextView = mView.tv_type
}
interface ListInteractionListener {
fun onRecyclerViewItemClickListener(item: Item)
}
interface RecyclerViewResources {
fun getString(id: Int): String
}
}
| apache-2.0 | a3483532c44dac187a1968f50bf17de7 | 29.876033 | 101 | 0.568058 | 4.970361 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/resolve/lazy/BodyResolveMode.kt | 4 | 1790 | // 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.resolve.lazy
import org.jetbrains.kotlin.resolve.BindingTraceFilter
enum class BodyResolveMode(val bindingTraceFilter: BindingTraceFilter, val doControlFlowAnalysis: Boolean, val resolveAdditionals: Boolean = true) {
// All body statements are analyzed, diagnostics included
FULL(BindingTraceFilter.ACCEPT_ALL, doControlFlowAnalysis = true),
// Analyzes only dependent statements, including all declaration statements (difference from PARTIAL_WITH_CFA)
PARTIAL_FOR_COMPLETION(BindingTraceFilter.NO_DIAGNOSTICS, doControlFlowAnalysis = true),
// Analyzes only dependent statements, diagnostics included
PARTIAL_WITH_DIAGNOSTICS(BindingTraceFilter.ACCEPT_ALL, doControlFlowAnalysis = true),
// Analyzes only dependent statements, performs control flow analysis (mostly needed for isUsedAsExpression / AsStatement)
PARTIAL_WITH_CFA(BindingTraceFilter.NO_DIAGNOSTICS, doControlFlowAnalysis = true),
// Analyzes only dependent statements, including only used declaration statements, does not perform control flow analysis
PARTIAL(BindingTraceFilter.NO_DIAGNOSTICS, doControlFlowAnalysis = false),
// Resolve mode to resolve only the element itself without the additional elements (annotation resolve would not lead to function resolve or default parameters)
PARTIAL_NO_ADDITIONAL(BindingTraceFilter.NO_DIAGNOSTICS, doControlFlowAnalysis = false, resolveAdditionals = false)
;
fun doesNotLessThan(other: BodyResolveMode): Boolean {
return this <= other && this.bindingTraceFilter.includesEverythingIn(other.bindingTraceFilter)
}
}
| apache-2.0 | cbfd4b4e65f8558ae28653937ad15133 | 58.666667 | 164 | 0.795531 | 4.931129 | false | false | false | false |
donglua/JZAndroidChart | app/src/main/java/cn/jingzhuan/lib/chart/demo/BarChartModel.kt | 1 | 1640 | package cn.jingzhuan.lib.chart.demo
import androidx.databinding.ViewDataBinding
import android.graphics.Color
import android.view.View
import android.view.ViewGroup
import cn.jingzhuan.lib.chart.data.BarDataSet
import cn.jingzhuan.lib.chart.data.BarValue
import cn.jingzhuan.lib.chart.demo.databinding.LayoutBarChartBinding
import com.airbnb.epoxy.DataBindingEpoxyModel
import com.airbnb.epoxy.EpoxyModelClass
import java.util.ArrayList
/**
* Created by Donglua on 17/8/2.
*/
@EpoxyModelClass(layout = R.layout.layout_bar_chart)
abstract class BarChartModel : DataBindingEpoxyModel() {
private val barDataSet: BarDataSet
init {
val barValueList = ArrayList<BarValue>()
barValueList.add(BarValue(11f))
barValueList.add(BarValue(10f))
barValueList.add(BarValue(11f))
barValueList.add(BarValue(13f))
barValueList.add(BarValue(11f))
barValueList.add(BarValue(12f))
barValueList.add(BarValue(12f))
barValueList.add(BarValue(13f).apply { setGradientColors(Color.WHITE, Color.BLACK) })
barValueList.add(BarValue(15f).apply { setGradientColors(Color.WHITE, Color.BLACK) })
barDataSet = BarDataSet(barValueList)
barDataSet.isAutoBarWidth = true
}
override fun buildView(parent: ViewGroup): View {
val rootView = super.buildView(parent)
val barBinding = rootView.tag as LayoutBarChartBinding
barBinding.barChart.setDataSet(barDataSet)
barBinding.barChart.axisRight.labelTextColor = Color.BLACK
return rootView
}
override fun setDataBindingVariables(binding: ViewDataBinding) {
binding as LayoutBarChartBinding
binding.barChart.animateY(500)
}
}
| apache-2.0 | 3b89b9877ec69d5ec055549c8cabdf70 | 28.285714 | 89 | 0.771951 | 3.588621 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/keyboard/KeyboardPagerViewModel.kt | 2 | 1808 | package org.thoughtcrime.securesms.keyboard
import androidx.annotation.MainThread
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import org.signal.core.util.ThreadUtil
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.stickers.StickerSearchRepository
import org.thoughtcrime.securesms.util.DefaultValueLiveData
class KeyboardPagerViewModel : ViewModel() {
private val page: DefaultValueLiveData<KeyboardPage>
private val pages: DefaultValueLiveData<Set<KeyboardPage>>
init {
val startingPages: MutableSet<KeyboardPage> = KeyboardPage.values().toMutableSet()
if (SignalStore.settings().isPreferSystemEmoji) {
startingPages.remove(KeyboardPage.EMOJI)
}
pages = DefaultValueLiveData(startingPages)
page = DefaultValueLiveData(startingPages.first())
StickerSearchRepository(ApplicationDependencies.getApplication()).getStickerFeatureAvailability { available ->
if (!available) {
val updatedPages = pages.value.toMutableSet().apply { remove(KeyboardPage.STICKER) }
pages.postValue(updatedPages)
if (page.value == KeyboardPage.STICKER) {
switchToPage(KeyboardPage.GIF)
switchToPage(KeyboardPage.EMOJI)
}
}
}
}
fun page(): LiveData<KeyboardPage> = page
fun pages(): LiveData<Set<KeyboardPage>> = pages
@MainThread
fun setOnlyPage(page: KeyboardPage) {
pages.value = setOf(page)
switchToPage(page)
}
fun switchToPage(page: KeyboardPage) {
if (this.pages.value.contains(page) && this.page.value != page) {
if (ThreadUtil.isMainThread()) {
this.page.value = page
} else {
this.page.postValue(page)
}
}
}
}
| gpl-3.0 | 51cb8f830d76732c43ac508edaa0d02f | 31.872727 | 114 | 0.735619 | 4.554156 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/avatar/picker/AvatarPickerItem.kt | 2 | 5791 | package org.thoughtcrime.securesms.avatar.picker
import android.util.TypedValue
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.view.setPadding
import com.airbnb.lottie.SimpleColorFilter
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.avatar.Avatar
import org.thoughtcrime.securesms.avatar.AvatarRenderer
import org.thoughtcrime.securesms.avatar.Avatars
import org.thoughtcrime.securesms.mms.DecryptableStreamUriLoader
import org.thoughtcrime.securesms.mms.GlideApp
import org.thoughtcrime.securesms.util.adapter.mapping.LayoutFactory
import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter
import org.thoughtcrime.securesms.util.adapter.mapping.MappingModel
import org.thoughtcrime.securesms.util.adapter.mapping.MappingViewHolder
import org.thoughtcrime.securesms.util.visible
typealias OnAvatarClickListener = (Avatar, Boolean) -> Unit
typealias OnAvatarLongClickListener = (View, Avatar) -> Boolean
object AvatarPickerItem {
private val SELECTION_CHANGED = Any()
fun register(adapter: MappingAdapter, onAvatarClickListener: OnAvatarClickListener, onAvatarLongClickListener: OnAvatarLongClickListener) {
adapter.registerFactory(Model::class.java, LayoutFactory({ ViewHolder(it, onAvatarClickListener, onAvatarLongClickListener) }, R.layout.avatar_picker_item))
}
class Model(val avatar: Avatar, val isSelected: Boolean) : MappingModel<Model> {
override fun areItemsTheSame(newItem: Model): Boolean = avatar.isSameAs(newItem.avatar)
override fun areContentsTheSame(newItem: Model): Boolean = avatar == newItem.avatar && isSelected == newItem.isSelected
override fun getChangePayload(newItem: Model): Any? {
return if (newItem.avatar == avatar && isSelected != newItem.isSelected) {
SELECTION_CHANGED
} else {
null
}
}
}
class ViewHolder(
itemView: View,
private val onAvatarClickListener: OnAvatarClickListener? = null,
private val onAvatarLongClickListener: OnAvatarLongClickListener? = null
) : MappingViewHolder<Model>(itemView) {
private val imageView: ImageView = itemView.findViewById(R.id.avatar_picker_item_image)
private val textView: TextView = itemView.findViewById(R.id.avatar_picker_item_text)
private val selectedFader: View? = itemView.findViewById(R.id.avatar_picker_item_fader)
private val selectedOverlay: View? = itemView.findViewById(R.id.avatar_picker_item_selection_overlay)
init {
textView.typeface = AvatarRenderer.getTypeface(context)
textView.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ ->
updateFontSize(textView.text.toString())
}
}
private fun updateFontSize(text: String) {
val textSize = Avatars.getTextSizeForLength(context, text, textView.measuredWidth * 0.8f, textView.measuredHeight * 0.45f)
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
if (textView !is EditText) {
textView.text = text
}
}
override fun bind(model: Model) {
val alpha = if (model.isSelected) 1f else 0f
val scale = if (model.isSelected) 0.9f else 1f
imageView.animate().cancel()
textView.animate().cancel()
selectedOverlay?.animate()?.cancel()
selectedFader?.animate()?.cancel()
itemView.setOnLongClickListener {
onAvatarLongClickListener?.invoke(itemView, model.avatar) ?: false
}
itemView.setOnClickListener { onAvatarClickListener?.invoke(model.avatar, model.isSelected) }
if (payload.isNotEmpty() && payload.contains(SELECTION_CHANGED)) {
imageView.animate().scaleX(scale).scaleY(scale)
textView.animate().scaleX(scale).scaleY(scale)
selectedOverlay?.animate()?.alpha(alpha)
selectedFader?.animate()?.alpha(alpha)
return
}
imageView.scaleX = scale
imageView.scaleY = scale
textView.scaleX = scale
textView.scaleY = scale
selectedFader?.alpha = alpha
selectedOverlay?.alpha = alpha
imageView.clearColorFilter()
imageView.setPadding(0)
when (model.avatar) {
is Avatar.Text -> {
textView.visible = true
updateFontSize(model.avatar.text)
if (textView.text.toString() != model.avatar.text) {
textView.text = model.avatar.text
}
imageView.setImageDrawable(null)
imageView.background.colorFilter = SimpleColorFilter(model.avatar.color.backgroundColor)
textView.setTextColor(model.avatar.color.foregroundColor)
}
is Avatar.Vector -> {
textView.visible = false
val drawableId = Avatars.getDrawableResource(model.avatar.key)
if (drawableId == null) {
imageView.setImageDrawable(null)
} else {
imageView.setImageDrawable(AppCompatResources.getDrawable(context, drawableId))
}
imageView.background.colorFilter = SimpleColorFilter(model.avatar.color.backgroundColor)
}
is Avatar.Photo -> {
textView.visible = false
GlideApp.with(imageView).load(DecryptableStreamUriLoader.DecryptableUri(model.avatar.uri)).into(imageView)
}
is Avatar.Resource -> {
imageView.setPadding((imageView.width * 0.2).toInt())
textView.visible = false
GlideApp.with(imageView).clear(imageView)
imageView.setImageResource(model.avatar.resourceId)
imageView.colorFilter = SimpleColorFilter(model.avatar.color.foregroundColor)
imageView.background.colorFilter = SimpleColorFilter(model.avatar.color.backgroundColor)
}
}
}
}
}
| gpl-3.0 | d723c6824dde1b305fb2b7ba500f5cb5 | 38.128378 | 160 | 0.714557 | 4.640224 | false | false | false | false |
jk1/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/singleton/impl.kt | 3 | 1874 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.transformations.singleton
import com.intellij.codeInsight.AnnotationUtil
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiElement
import com.intellij.util.text.nullize
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
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.lang.psi.impl.findDeclaredDetachedValue
import org.jetbrains.plugins.groovy.lang.psi.impl.stringValue
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames
internal val singletonFqn = GroovyCommonClassNames.GROOVY_LANG_SINGLETON
internal val singletonOriginInfo = "by @Singleton"
fun PsiAnnotation.getPropertyName(): String = findDeclaredDetachedValue("property").stringValue().nullize(true) ?: "instance"
internal fun getAnnotation(identifier: PsiElement?): GrAnnotation? {
val parent = identifier?.parent as? GrMethod ?: return null
if (!parent.isConstructor) return null
val clazz = parent.containingClass as? GrTypeDefinition ?: return null
return AnnotationUtil.findAnnotation(clazz, singletonFqn) as? GrAnnotation
}
| apache-2.0 | eaa38fb8dcfa7ab045565225aa804d01 | 47.051282 | 125 | 0.805229 | 4.308046 | false | false | false | false |
marius-m/wt4 | database2/src/test/java/lt/markmerkk/WorklogStorageUpdateTest.kt | 1 | 7558 | package lt.markmerkk
import com.nhaarman.mockitokotlin2.*
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.MockitoAnnotations
class WorklogStorageUpdateTest {
@Mock
lateinit var dbInteractor: DBInteractorLogJOOQ
lateinit var worklogStorage: WorklogStorage
private val timeProvider = TimeProviderTest()
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
worklogStorage = WorklogStorage(
timeProvider = timeProvider,
dbInteractor = dbInteractor
)
}
@Test
fun updateLocalLog_noSuchLog() {
// Assemble
val log = Mocks.createLog(timeProvider, id = 1)
doReturn(false).whenever(dbInteractor).existAsLocal(any())
doReturn(false).whenever(dbInteractor).existAsRemote(any())
// Act
worklogStorage.updateSync(log)
// Assert
verify(dbInteractor, never()).insert(any())
verify(dbInteractor, never()).update(any())
verify(dbInteractor, never()).deleteByLocalId(any())
verify(dbInteractor, never()).deleteByRemoteId(any())
}
@Test
fun updateLocalLog_existOnlyAsLocal() {
// Assemble
val log = Mocks.createLog(timeProvider, id = 1)
doReturn(true).whenever(dbInteractor).existAsLocal(any())
doReturn(false).whenever(dbInteractor).existAsRemote(any())
// Act
worklogStorage.updateSync(log)
// Assert
verify(dbInteractor, never()).insert(any())
verify(dbInteractor).update(log)
verify(dbInteractor, never()).deleteByLocalId(any())
verify(dbInteractor, never()).deleteByRemoteId(any())
}
@Test // cannot be possible, can only update local entries
fun updateLocalLog_existOnlyAsRemote() {
// Assemble
val log = Mocks.createLog(timeProvider, id = 1) // not possible, no remote ID
doReturn(false).whenever(dbInteractor).existAsLocal(any())
doReturn(true).whenever(dbInteractor).existAsRemote(any())
// Act
worklogStorage.updateSync(log)
// Assert
verify(dbInteractor, never()).insert(any())
verify(dbInteractor, never()).update(any())
verify(dbInteractor, never()).deleteByLocalId(any())
verify(dbInteractor, never()).deleteByRemoteId(any())
}
@Test
fun updateLocalLog_existAsLocal_existAsRemote() {
// Assemble
val log = Mocks.createLog(timeProvider, id = 1)
doReturn(true).whenever(dbInteractor).existAsLocal(any())
doReturn(true).whenever(dbInteractor).existAsRemote(any()) // not possible, no remote ID
// Act
worklogStorage.updateSync(log)
// Assert
verify(dbInteractor, never()).insert(any())
verify(dbInteractor, never()).update(any())
verify(dbInteractor, never()).deleteByLocalId(any())
verify(dbInteractor, never()).deleteByRemoteId(any())
}
@Test
fun updateRemoteLog_noSuchLog() {
// Assemble
val log = Mocks.createLog(
timeProvider,
id = 1,
remoteData = Mocks.createRemoteData(
timeProvider,
remoteId = 2
)
)
doReturn(false).whenever(dbInteractor).existAsLocal(any())
doReturn(false).whenever(dbInteractor).existAsRemote(any())
// Act
worklogStorage.updateSync(log)
// Assert
verify(dbInteractor, never()).insert(any())
verify(dbInteractor, never()).update(any())
verify(dbInteractor, never()).deleteByLocalId(any())
verify(dbInteractor, never()).deleteByRemoteId(any())
}
@Test
fun updateRemoteLog_existOnlyAsLocal() {
// Assemble
val log = Mocks.createLog(
timeProvider,
id = 1,
remoteData = Mocks.createRemoteData(
timeProvider,
remoteId = 2
)
)
doReturn(true).whenever(dbInteractor).existAsLocal(any())
doReturn(false).whenever(dbInteractor).existAsRemote(any())
// Act
worklogStorage.updateSync(log)
// Assert
verify(dbInteractor).insert(
Mocks.createLog(
timeProvider,
id = Const.NO_ID,
start = log.time.start,
end = log.time.end,
code = log.code.code,
comment = log.comment,
remoteData = null
)
)
verify(dbInteractor, never()).update(any())
verify(dbInteractor).deleteByLocalId(eq(1))
verify(dbInteractor).deleteByRemoteId(eq(2))
}
@Test
fun updateRemoteLog_existOnlyAsRemote() {
// Assemble
val log = Mocks.createLog(
timeProvider,
id = 1,
remoteData = Mocks.createRemoteData(
timeProvider,
remoteId = 2
)
)
doReturn(false).whenever(dbInteractor).existAsLocal(any())
doReturn(true).whenever(dbInteractor).existAsRemote(any())
// Act
worklogStorage.updateSync(log)
// Assert
verify(dbInteractor).insert(
Mocks.createLog(
timeProvider,
id = Const.NO_ID,
remoteData = null
)
)
verify(dbInteractor).update(
Mocks.createLog(
timeProvider,
id = 1,
remoteData = Mocks.createRemoteData(
timeProvider,
remoteId = 2,
isDeleted = true
)
)
)
verify(dbInteractor, never()).deleteByLocalId(any())
verify(dbInteractor, never()).deleteByRemoteId(any())
}
@Test
fun updateRemoteLog_existAsBoth() {
// Assemble
val log = Mocks.createLog(
timeProvider,
id = 1,
remoteData = Mocks.createRemoteData(
timeProvider,
remoteId = 2
)
)
doReturn(true).whenever(dbInteractor).existAsLocal(any())
doReturn(true).whenever(dbInteractor).existAsRemote(any())
// Act
worklogStorage.updateSync(log)
// Assert
verify(dbInteractor).insert(
Mocks.createLog(
timeProvider,
id = Const.NO_ID,
start = log.time.start,
end = log.time.end,
code = log.code.code,
comment = log.comment,
remoteData = null
)
)
verify(dbInteractor).update(
Mocks.createLog(
timeProvider,
id = 1,
remoteData = Mocks.createRemoteData(
timeProvider,
remoteId = 2,
isDeleted = true
)
)
)
verify(dbInteractor, never()).deleteByLocalId(any())
verify(dbInteractor, never()).deleteByRemoteId(any())
}
} | apache-2.0 | 363ba6b0c49d20dea3469917bd34063b | 31.165957 | 96 | 0.526991 | 5.162568 | false | false | false | false |
dahlstrom-g/intellij-community | uast/uast-common/src/com/intellij/patterns/uast/UastPatterns.kt | 6 | 14078 | /*
* 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.
*/
@file:JvmName("UastPatterns")
package com.intellij.patterns.uast
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.util.Key
import com.intellij.patterns.*
import com.intellij.patterns.PsiJavaPatterns.psiClass
import com.intellij.patterns.StandardPatterns.string
import com.intellij.psi.*
import com.intellij.util.ProcessingContext
import com.intellij.util.castSafelyTo
import com.intellij.util.containers.ContainerUtil
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.NotNull
import org.jetbrains.uast.*
fun literalExpression(): ULiteralExpressionPattern = ULiteralExpressionPattern()
@JvmOverloads
fun injectionHostUExpression(strict: Boolean = true): UExpressionPattern<UExpression, *> =
uExpression().filterWithContext { _, processingContext ->
val requestedPsi = processingContext.get(REQUESTED_PSI_ELEMENT)
if (requestedPsi == null) {
if (strict && ApplicationManager.getApplication().isUnitTestMode) {
throw AssertionError("no ProcessingContext with `REQUESTED_PSI_ELEMENT` passed for `injectionHostUExpression`," +
" please consider creating one using `UastPatterns.withRequestedPsi`, providing a source psi for which " +
" this pattern was originally created, or make this `injectionHostUExpression` non-strict.")
}
else return@filterWithContext !strict
}
return@filterWithContext requestedPsi is PsiLanguageInjectionHost
}
fun injectionHostOrReferenceExpression(): UExpressionPattern.Capture<UExpression> =
uExpression().filter { it is UReferenceExpression || it.isInjectionHost() }
fun callExpression(): UCallExpressionPattern = UCallExpressionPattern()
fun uExpression(): UExpressionPattern.Capture<UExpression> = expressionCapture(UExpression::class.java)
fun uMethod(): UDeclarationPattern<UMethod> = UDeclarationPattern(UMethod::class.java)
fun uClass(): UDeclarationPattern<UClass> = UDeclarationPattern(UClass::class.java)
fun <T : UElement> capture(clazz: Class<T>): UElementPattern.Capture<T> = UElementPattern.Capture(clazz)
fun <T : UExpression> expressionCapture(clazz: Class<T>): UExpressionPattern.Capture<T> = UExpressionPattern.Capture(clazz)
fun ProcessingContext.withRequestedPsi(psiElement: PsiElement) = this.apply { put(REQUESTED_PSI_ELEMENT, psiElement) }
fun withRequestedPsi(psiElement: PsiElement) = ProcessingContext().withRequestedPsi(psiElement)
open class UElementPattern<T : UElement, Self : UElementPattern<T, Self>>(clazz: Class<T>) : ObjectPattern<T, Self>(clazz) {
fun withSourcePsiCondition(pattern: PatternCondition<PsiElement>): Self =
this.with(object : PatternCondition<T>("withSourcePsiPattern") {
override fun accepts(t: T, context: ProcessingContext?): Boolean {
val sourcePsiElement = t.sourcePsiElement ?: return false
return pattern.accepts(sourcePsiElement, context)
}
})
fun sourcePsiFilter(filter: (PsiElement) -> Boolean): Self =
this.with(object : PatternCondition<T>("sourcePsiFilter") {
override fun accepts(t: T, context: ProcessingContext?): Boolean {
val sourcePsiElement = t.sourcePsiElement ?: return false
return filter(sourcePsiElement)
}
})
fun filterWithContext(filter: (T, ProcessingContext) -> Boolean): Self =
filterWithContext(null, filter)
fun filterWithContext(debugName: String?, filter: (T, ProcessingContext) -> Boolean): Self =
with(object : PatternCondition<T>(debugName) {
override fun accepts(t: T, context: ProcessingContext?): Boolean = filter.invoke(t, context ?: ProcessingContext())
})
fun filter(filter: (T) -> Boolean): Self = filterWithContext { t, _ -> filter(t) }
fun withUastParent(parentPattern: ElementPattern<out UElement>): Self = filterWithContext { it, context ->
it.uastParent?.let { parentPattern.accepts(it, context) } ?: false
}
fun withUastParentOrSelf(parentPattern: ElementPattern<out UElement>): Self = filterWithContext { it, context ->
parentPattern.accepts(it, context) || it.uastParent?.let { parentPattern.accepts(it, context) } ?: false
}
class Capture<T : UElement>(clazz: Class<T>) : UElementPattern<T, Capture<T>>(clazz)
}
private val constructorOrMethodCall = setOf(UastCallKind.CONSTRUCTOR_CALL, UastCallKind.METHOD_CALL)
private val IS_UAST_CALL_EXPRESSION_PARAMETER: Key<Boolean> = Key.create("UAST_CALL_EXPRESSION_PARAMETER")
private fun isCallExpressionParameter(argumentExpression: UExpression,
parameterIndex: Int,
callPattern: ElementPattern<UCallExpression>, context: ProcessingContext): Boolean {
val sharedContext = context.sharedContext
val isCallParameter = sharedContext.get(IS_UAST_CALL_EXPRESSION_PARAMETER, argumentExpression)
if (isCallParameter == java.lang.Boolean.FALSE) {
return false
}
val call = argumentExpression.uastParent.getUCallExpression(searchLimit = 2)
if (call == null || call.kind !in constructorOrMethodCall) {
sharedContext.put(IS_UAST_CALL_EXPRESSION_PARAMETER, argumentExpression, java.lang.Boolean.FALSE)
return false
}
return callPattern.accepts(call, context)
&& call.getArgumentForParameter(parameterIndex)?.let(::wrapULiteral) == wrapULiteral(argumentExpression)
}
private fun isPropertyAssignCall(argument: UElement, methodPattern: ElementPattern<out PsiMethod>, context: ProcessingContext): Boolean {
val uBinaryExpression = (argument.uastParent as? UBinaryExpression) ?: return false
if (uBinaryExpression.operator != UastBinaryOperator.ASSIGN) return false
val uastReference = uBinaryExpression.leftOperand.castSafelyTo<UReferenceExpression>() ?: return false
val resolved = uastReference.resolve()
return methodPattern.accepts(resolved, context)
}
class UCallExpressionPattern : UElementPattern<UCallExpression, UCallExpressionPattern>(UCallExpression::class.java) {
fun withReceiver(classPattern: ElementPattern<PsiClass>): UCallExpressionPattern =
filterWithContext { it, context -> (it.receiverType as? PsiClassType)?.resolve()?.let { classPattern.accepts(it, context) } ?: false }
fun withMethodName(methodName: String): UCallExpressionPattern = withMethodName(string().equalTo(methodName))
fun withAnyResolvedMethod(method: ElementPattern<out PsiMethod>): UCallExpressionPattern = withResolvedMethod(method, true)
fun withResolvedMethod(method: ElementPattern<out PsiMethod>,
multiResolve: Boolean): UCallExpressionPattern {
val nameCondition = ContainerUtil.findInstance(
method.condition.conditions,
PsiNamePatternCondition::class.java)
return filterWithContext { uCallExpression, context ->
if (nameCondition != null) {
val methodName = uCallExpression.methodName
if (methodName != null && !nameCondition.namePattern.accepts(methodName)) return@filterWithContext false
}
if (multiResolve && uCallExpression is UMultiResolvable) {
uCallExpression.multiResolve().any { method.accepts(it.element, context) }
}
else {
uCallExpression.resolve().let { method.accepts(it, context) }
}
}
}
fun withMethodName(namePattern: ElementPattern<String>): UCallExpressionPattern = filterWithContext { it, context ->
it.methodName?.let {
namePattern.accepts(it, context)
} ?: false
}
fun constructor(classPattern: ElementPattern<PsiClass>, parameterCount: Int): UCallExpressionPattern = filterWithContext { it, context ->
if (it.classReference == null) return@filterWithContext false
val psiMethod = it.resolve() ?: return@filterWithContext false
psiMethod.isConstructor
&& psiMethod.parameterList.parametersCount == parameterCount
&& classPattern.accepts(psiMethod.containingClass, context)
}
fun constructor(classPattern: ElementPattern<PsiClass>): UCallExpressionPattern = filterWithContext { it, context ->
if (it.classReference == null) return@filterWithContext false
val psiMethod = it.resolve() ?: return@filterWithContext false
psiMethod.isConstructor && classPattern.accepts(psiMethod.containingClass, context)
}
fun constructor(className: String): UCallExpressionPattern = constructor(psiClass().withQualifiedName(className))
fun constructor(className: String, parameterCount: Int): UCallExpressionPattern = constructor(psiClass().withQualifiedName(className), parameterCount)
}
private val IS_UAST_ANNOTATION_PARAMETER: Key<Boolean> = Key.create("UAST_ANNOTATION_PARAMETER")
open class UExpressionPattern<T : UExpression, Self : UExpressionPattern<T, Self>>(clazz: Class<T>) : UElementPattern<T, Self>(clazz) {
fun annotationParam(@NonNls parameterName: String, annotationPattern: ElementPattern<UAnnotation>): Self =
annotationParams(annotationPattern, string().equalTo(parameterName))
fun annotationParams(annotationPattern: ElementPattern<UAnnotation>, parameterNames: ElementPattern<String>): Self =
this.with(object : PatternCondition<T>("annotationParam") {
override fun accepts(uElement: T, context: ProcessingContext?): Boolean {
val sharedContext = context?.sharedContext
val isAnnotationParameter = sharedContext?.get(IS_UAST_ANNOTATION_PARAMETER, uElement)
if (isAnnotationParameter == java.lang.Boolean.FALSE) {
return false
}
val containingUAnnotationEntry = getContainingUAnnotationEntry(uElement)
if (containingUAnnotationEntry == null) {
sharedContext?.put(IS_UAST_ANNOTATION_PARAMETER, uElement, java.lang.Boolean.FALSE)
return false
}
return parameterNames.accepts(containingUAnnotationEntry.second ?: "value", context)
&& annotationPattern.accepts(containingUAnnotationEntry.first, context)
}
})
fun annotationParam(annotationQualifiedName: ElementPattern<String>, @NonNls parameterName: String): Self =
annotationParam(parameterName, uAnnotationQualifiedNamePattern(annotationQualifiedName))
fun annotationParam(@NonNls annotationQualifiedName: String, @NonNls parameterName: String): Self =
annotationParam(string().equalTo(annotationQualifiedName), parameterName)
fun annotationParams(@NonNls annotationQualifiedName: String, @NonNls parameterNames: ElementPattern<String>): Self =
annotationParams(uAnnotationQualifiedNamePattern(string().equalTo(annotationQualifiedName)), parameterNames)
fun annotationParams(@NonNls annotationQualifiedNames: List<String>, @NonNls parameterNames: ElementPattern<String>): Self =
annotationParams(uAnnotationQualifiedNamePattern(string().oneOf(annotationQualifiedNames)), parameterNames)
fun inCall(callPattern: ElementPattern<UCallExpression>): Self =
filterWithContext { it, context -> it.getUCallExpression()?.let { callPattern.accepts(it, context) } ?: false }
fun callParameter(parameterIndex: Int, callPattern: ElementPattern<UCallExpression>): Self =
filterWithContext { t, processingContext -> isCallExpressionParameter(t, parameterIndex, callPattern, processingContext) }
fun constructorParameter(parameterIndex: Int, classFQN: String): Self =
callParameter(parameterIndex, callExpression().constructor(classFQN))
fun setterParameter(methodPattern: ElementPattern<out PsiMethod>): Self = filterWithContext { it, context ->
isPropertyAssignCall(it, methodPattern, context) ||
isCallExpressionParameter(it, 0, callExpression().withAnyResolvedMethod(methodPattern), context)
}
@JvmOverloads
fun methodCallParameter(parameterIndex: Int, methodPattern: ElementPattern<out PsiMethod>, multiResolve: Boolean = true): Self =
callParameter(parameterIndex, callExpression().withResolvedMethod(methodPattern, multiResolve))
fun arrayAccessParameterOf(receiverClassPattern: ElementPattern<PsiClass>): Self = filterWithContext { self, context ->
val aae: UArrayAccessExpression = self.uastParent as? UArrayAccessExpression ?: return@filterWithContext false
val receiverClass = (aae.receiver.getExpressionType() as? PsiClassType)?.resolve() ?: return@filterWithContext false
receiverClassPattern.accepts(receiverClass, context)
}
fun inside(strict: Boolean, parentPattern: ElementPattern<out UElement>): Self {
return this.with(object : PatternCondition<T>("inside") {
override fun accepts(element: T, context: ProcessingContext?): Boolean {
if (strict) {
return parentPattern.accepts(element.uastParent)
}
var parent = element.uastParent
while (parent != null) {
if (parentPattern.accepts(parent)) {
return true
}
parent = parent.uastParent
}
return false
}
})
}
open class Capture<T : UExpression>(clazz: Class<T>) : UExpressionPattern<T, Capture<T>>(clazz)
}
class ULiteralExpressionPattern : UExpressionPattern<ULiteralExpression, ULiteralExpressionPattern>(ULiteralExpression::class.java)
fun uAnnotationQualifiedNamePattern(annotationQualifiedName: ElementPattern<String>): UElementPattern<UAnnotation, *> =
capture(UAnnotation::class.java).filterWithContext(annotationQualifiedName.toString()) { it, context ->
it.qualifiedName?.let {
annotationQualifiedName.accepts(it, context)
} ?: false
}
open class UDeclarationPattern<T : UDeclaration>(clazz: Class<T>) : UElementPattern<T, UDeclarationPattern<T>>(clazz) {
fun annotatedWith(@NotNull annotationQualifiedNames: List<String>): UDeclarationPattern<T> {
return this.with(object : PatternCondition<UDeclaration>("annotatedWith") {
override fun accepts(uDeclaration: UDeclaration, context: ProcessingContext?): Boolean {
return uDeclaration.uAnnotations.any { uAnno ->
annotationQualifiedNames.any { annoFqn ->
annoFqn == uAnno.qualifiedName
}
}
}
})
}
} | apache-2.0 | 651da5142825de2ba092b2c1cbb6356e | 47.215753 | 152 | 0.749112 | 4.903518 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/package-search/compat/src/intellij/plugin/ui/toolwindow/models/PackageVersion.kt | 4 | 3729 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models
import com.intellij.util.text.VersionComparatorUtil
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchCompatBundle
import com.jetbrains.packagesearch.intellij.plugin.util.versionTokenPriorityProvider
import kotlinx.serialization.Serializable
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import org.jetbrains.packagesearch.api.v2.ApiStandardPackage
import org.jetbrains.packagesearch.packageversionutils.PackageVersionUtils
@Serializable
sealed class PackageVersion : Comparable<PackageVersion> {
abstract val versionName: String
abstract val isStable: Boolean
abstract val releasedAt: Long?
@get:Nls
abstract val displayName: String
override fun compareTo(other: PackageVersion): Int =
VersionComparatorUtil.compare(versionName, other.versionName, ::versionTokenPriorityProvider)
@Serializable
object Missing : PackageVersion() {
override val versionName = ""
override val isStable = true
override val releasedAt: Long? = null
@Nls
override val displayName = PackageSearchCompatBundle.message("packagesearch.ui.missingVersion")
@NonNls
override fun toString() = "[Missing version]"
}
@Serializable
data class Named(
override val versionName: String,
override val isStable: Boolean,
override val releasedAt: Long?
) : PackageVersion() {
init {
require(versionName.isNotBlank()) { "A Named version name cannot be blank." }
}
@Suppress("HardCodedStringLiteral")
@Nls
override val displayName = versionName
@NonNls
override fun toString() = versionName
fun semanticVersionComponent(): SemVerComponent? {
val groupValues = SEMVER_REGEX.find(versionName)?.groupValues ?: return null
if (groupValues.size <= 1) return null
val semanticVersion = groupValues[1].takeIf { it.isNotBlank() } ?: return null
return SemVerComponent(semanticVersion, this)
}
data class SemVerComponent(val semanticVersion: String, val named: Named)
companion object {
private val SEMVER_REGEX = "^((?:\\d+\\.){0,3}\\d+)".toRegex(option = RegexOption.IGNORE_CASE)
}
}
companion object {
fun from(rawVersion: ApiStandardPackage.ApiStandardVersion): PackageVersion {
if (rawVersion.version.isBlank()) return Missing
return Named(versionName = rawVersion.version.trim(), isStable = rawVersion.stable, releasedAt = rawVersion.lastChanged)
}
fun from(rawVersion: String?): PackageVersion {
if (rawVersion.isNullOrBlank()) return Missing
return Named(rawVersion.trim(), isStable = PackageVersionUtils.evaluateStability(rawVersion), releasedAt = null)
}
}
}
| apache-2.0 | 5213808c9efcc3016e5f2d67cc4a811f | 36.29 | 132 | 0.67498 | 5.266949 | false | false | false | false |
android/privacy-codelab | PhotoLog_End/src/main/java/com/example/photolog_end/ui/theme/Color.kt | 1 | 910 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.photolog_end.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
| apache-2.0 | 3b509c7dc18b2ca12f0ae291eb094551 | 32.703704 | 75 | 0.757143 | 3.527132 | false | false | false | false |
google/intellij-community | platform/lang-api/src/com/intellij/codeInsight/hints/InlayHintsProvider.kt | 5 | 8019 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.codeInsight.hints
import com.intellij.lang.Language
import com.intellij.openapi.application.ApplicationBundle
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.options.UnnamedConfigurable
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsContexts
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiFileFactory
import com.intellij.util.xmlb.annotations.Property
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.Nls
import javax.swing.JComponent
import kotlin.reflect.KMutableProperty0
enum class InlayGroup(val key: String, @Nls val description: String? = null) {
CODE_VISION_GROUP_NEW("settings.hints.new.group.code.vision", ApplicationBundle.message("settings.hints.new.group.code.vision.description")),
CODE_VISION_GROUP("settings.hints.group.code.vision", ApplicationBundle.message("settings.hints.new.group.code.vision.description")),
PARAMETERS_GROUP("settings.hints.group.parameters", ApplicationBundle.message("settings.hints.group.parameters.description")),
TYPES_GROUP("settings.hints.group.types", ApplicationBundle.message("settings.hints.group.types.description")),
VALUES_GROUP("settings.hints.group.values", ApplicationBundle.message("settings.hints.group.values.description")),
ANNOTATIONS_GROUP("settings.hints.group.annotations", ApplicationBundle.message("settings.hints.group.annotations.description")),
METHOD_CHAINS_GROUP("settings.hints.group.method.chains"),
LAMBDAS_GROUP("settings.hints.group.lambdas", ApplicationBundle.message("settings.hints.group.lambdas.description")),
CODE_AUTHOR_GROUP("settings.hints.group.code.author", ApplicationBundle.message("settings.hints.group.code.author.description")),
URL_PATH_GROUP("settings.hints.group.url.path", ApplicationBundle.message("settings.hints.group.url.path.description")),
OTHER_GROUP("settings.hints.group.other");
override fun toString(): @Nls String {
return ApplicationBundle.message(key)
}}
/**
* Provider of inlay hints for single language. If you need to create hints for multiple languages, please use [InlayHintsProviderFactory].
* Both block and inline hints collection are supported.
* Block hints draws between lines of code text. Inline ones are placed on the code text line (like parameter hints)
* @param T settings type of this provider, if no settings required, please, use [NoSettings]
* @see com.intellij.openapi.editor.InlayModel.addInlineElement
* @see com.intellij.openapi.editor.InlayModel.addBlockElement
*
* To test it you may use InlayHintsProviderTestCase.
* Mark as [com.intellij.openapi.project.DumbAware] to enable it in dumb mode.
*/
interface InlayHintsProvider<T : Any> {
/**
* If this method is called, provider is enabled for this file
* Warning! Your collector should not use any settings besides [settings]
*/
fun getCollectorFor(file: PsiFile, editor: Editor, settings: T, sink: InlayHintsSink): InlayHintsCollector?
/**
* Returns quick collector of placeholders.
* Placeholders are shown on editor opening and stay until [getCollectorFor] collector hints are calculated.
*/
@ApiStatus.Experimental
@JvmDefault
fun getPlaceholdersCollectorFor(file: PsiFile, editor: Editor, settings: T, sink: InlayHintsSink): InlayHintsCollector? = null
/**
* Settings must be plain java object, fields of these settings will be copied via serialization.
* Must implement `equals` method, otherwise settings won't be able to track modification.
* Returned object will be used to create configurable and collector.
* It persists automatically.
*/
fun createSettings(): T
@get:Nls(capitalization = Nls.Capitalization.Sentence)
/**
* Name of this kind of hints. It will be used in settings and in context menu.
* Please, do not use word "hints" to avoid duplication
*/
val name: String
@JvmDefault
val group: InlayGroup get() = InlayGroup.OTHER_GROUP
/**
* Used for persisting settings.
*/
val key: SettingsKey<T>
@JvmDefault
val description: String?
@Nls
get() {
return getProperty("inlay." + key.id + ".description")
}
/**
* Text, that will be used in the settings as a preview.
*/
val previewText: String?
/**
* Creates configurable, that immediately applies changes from UI to [settings].
*/
fun createConfigurable(settings: T): ImmediateConfigurable
/**
* Checks whether the language is accepted by the provider.
*/
fun isLanguageSupported(language: Language): Boolean = true
@JvmDefault
fun createFile(project: Project, fileType: FileType, document: Document): PsiFile {
val factory = PsiFileFactory.getInstance(project)
return factory.createFileFromText("dummy", fileType, document.text)
}
@Nls
@JvmDefault
fun getProperty(key: String): String? = null
@JvmDefault
fun preparePreview(editor: Editor, file: PsiFile, settings: T) {
}
@Nls
@JvmDefault
fun getCaseDescription(case: ImmediateConfigurable.Case): String? {
return getProperty("inlay." + this.key.id + "." + case.id)
}
val isVisibleInSettings: Boolean
get() = true
}
/**
* The same as [UnnamedConfigurable], but not waiting for apply() to save settings.
*/
interface ImmediateConfigurable {
/**
* Creates component, which listen to its components and immediately updates state of settings object
* This is required to make preview in settings works instantly
* Note, that if you need to express only cases of this provider, you should use [cases] instead
*/
fun createComponent(listener: ChangeListener): JComponent
/**
* Loads state from its configurable.
*/
@JvmDefault
fun reset() {}
/**
* Text, that will be used in settings for checkbox to enable/disable hints.
*/
@JvmDefault
val mainCheckboxText: String
get() = "Show hints"
@JvmDefault
val cases : List<Case>
get() = emptyList()
class Case(
@Nls val name: String,
val id: String,
private val loadFromSettings: () -> Boolean,
private val onUserChanged: (Boolean) -> Unit,
@NlsContexts.DetailedDescription
val extendedDescription: String? = null
) {
var value: Boolean
get() = loadFromSettings()
set(value) = onUserChanged(value)
constructor(@Nls name: String, id: String, property: KMutableProperty0<Boolean>, @NlsContexts.DetailedDescription extendedDescription: String? = null) : this(
name,
id,
{ property.get() },
{property.set(it)},
extendedDescription
)
}
}
interface ChangeListener {
/**
* This method should be called on any change of corresponding settings.
*/
fun settingsChanged()
}
/**
* This class should be used if provider should not have settings. If you use e.g. [Unit] you will have annoying warning in logs.
*/
@Property(assertIfNoBindings = false)
class NoSettings {
override fun equals(other: Any?): Boolean = other is NoSettings
override fun hashCode(): Int {
return javaClass.hashCode()
}
}
/**
* Similar to [com.intellij.openapi.util.Key], but it also requires language to be unique.
* Allows type-safe access to settings of provider.
*/
data class SettingsKey<T>(val id: String) {
companion object {
fun getFullId(languageId: String, keyId: String): String {
return "$languageId.$keyId"
}
}
fun getFullId(language: Language): String = getFullId(language.id, id)
}
interface AbstractSettingsKey<T: Any> {
fun getFullId(language: Language): String
}
data class InlayKey<T: Any, C: Any>(val id: String) : AbstractSettingsKey<T>, ContentKey<C> {
override fun getFullId(language: Language): String = language.id + "." + id
}
/**
* Allows type-safe access to content of the root presentation.
*/
interface ContentKey<C: Any> | apache-2.0 | 1d76b3d0e3a7fb7edad859e894bc8dc7 | 33.869565 | 162 | 0.736002 | 4.2768 | false | false | false | false |
RuneSuite/client | updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/RawSound.kt | 1 | 2017 | package org.runestar.client.updater.mapper.std.classes
import org.objectweb.asm.Opcodes
import org.objectweb.asm.Type
import org.runestar.client.updater.mapper.IdentityMapper
import org.runestar.client.updater.mapper.OrderMapper
import org.runestar.client.updater.mapper.DependsOn
import org.runestar.client.updater.mapper.MethodParameters
import org.runestar.client.updater.mapper.predicateOf
import org.runestar.client.updater.mapper.type
import org.runestar.client.updater.mapper.Class2
import org.runestar.client.updater.mapper.Field2
import org.runestar.client.updater.mapper.Instruction2
import org.runestar.client.updater.mapper.Method2
@DependsOn(AbstractSound::class)
class RawSound : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.superType == type<AbstractSound>() }
class samples : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == ByteArray::class.type }
}
class sampleRate : OrderMapper.InConstructor.Field(RawSound::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == Opcodes.PUTFIELD && it.fieldType == Type.INT_TYPE }
override val constructorPredicate = predicateOf<Method2> { it.arguments.size == 5 }
}
class start : OrderMapper.InConstructor.Field(RawSound::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == Opcodes.PUTFIELD && it.fieldType == Type.INT_TYPE }
override val constructorPredicate = predicateOf<Method2> { it.arguments.size == 5 }
}
class end : OrderMapper.InConstructor.Field(RawSound::class, 2) {
override val predicate = predicateOf<Instruction2> { it.opcode == Opcodes.PUTFIELD && it.fieldType == Type.INT_TYPE }
override val constructorPredicate = predicateOf<Method2> { it.arguments.size == 5 }
}
@MethodParameters("decimator")
class resample : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { true }
}
} | mit | 7f00edbe225505bb0b0cf5fb890a35b1 | 45.930233 | 125 | 0.748141 | 4.219665 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveEmptyPrimaryConstructorIntention.kt | 3 | 1620 | // 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.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention
import org.jetbrains.kotlin.idea.codeinsight.api.classic.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 | 41b9c65e51d40f100cb44658fbe0ea1c | 46.647059 | 120 | 0.804321 | 5.294118 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/view/lesson_demo/ui/dialog/LessonDemoCompleteBottomSheetDialogFragment.kt | 1 | 9687 | package org.stepik.android.view.lesson_demo.ui.dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.ViewModelProvider
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.google.firebase.remoteconfig.FirebaseRemoteConfig
import com.google.firebase.remoteconfig.ktx.get
import kotlinx.android.synthetic.main.bottom_sheet_dialog_lesson_demo_complete.*
import kotlinx.android.synthetic.main.error_no_connection_with_button_small.*
import org.stepic.droid.R
import org.stepic.droid.base.App
import org.stepic.droid.configuration.RemoteConfig
import org.stepic.droid.core.ScreenManager
import org.stepik.android.domain.course.analytic.CourseViewSource
import org.stepik.android.domain.course_payments.model.DeeplinkPromoCode
import org.stepik.android.domain.course_payments.model.DefaultPromoCode
import org.stepik.android.domain.course_purchase.analytic.CoursePurchaseSource
import org.stepik.android.domain.course_purchase.model.CoursePurchaseFlow
import org.stepik.android.model.Course
import org.stepik.android.presentation.course_purchase.model.CoursePurchaseData
import org.stepik.android.presentation.lesson_demo.LessonDemoFeature
import org.stepik.android.presentation.lesson_demo.LessonDemoViewModel
import org.stepik.android.presentation.wishlist.WishlistOperationFeature
import org.stepik.android.view.course.mapper.DisplayPriceMapper
import org.stepik.android.view.course.resolver.CoursePromoCodeResolver
import org.stepik.android.view.course.routing.CourseScreenTab
import org.stepik.android.view.course_purchase.delegate.WishlistViewDelegate
import org.stepik.android.view.course_purchase.ui.dialog.CoursePurchaseBottomSheetDialogFragment
import ru.nobird.app.presentation.redux.container.ReduxView
import ru.nobird.android.view.base.ui.delegate.ViewStateDelegate
import ru.nobird.android.view.base.ui.extension.argument
import ru.nobird.android.view.base.ui.extension.showIfNotExists
import ru.nobird.android.view.redux.ui.extension.reduxViewModel
import javax.inject.Inject
class LessonDemoCompleteBottomSheetDialogFragment :
BottomSheetDialogFragment(),
CoursePurchaseBottomSheetDialogFragment.Callback,
ReduxView<LessonDemoFeature.State, LessonDemoFeature.Action.ViewAction> {
companion object {
const val TAG = "LessonDemoCompleteBottomSheetDialog"
fun newInstance(course: Course): DialogFragment =
LessonDemoCompleteBottomSheetDialogFragment().apply {
this.course = course
}
}
private var course: Course by argument()
@Inject
lateinit var screenManager: ScreenManager
@Inject
internal lateinit var viewModelFactory: ViewModelProvider.Factory
@Inject
internal lateinit var displayPriceMapper: DisplayPriceMapper
@Inject
internal lateinit var coursePromoCodeResolver: CoursePromoCodeResolver
@Inject
internal lateinit var firebaseRemoteConfig: FirebaseRemoteConfig
private val lessonDemoViewModel: LessonDemoViewModel by reduxViewModel(this) { viewModelFactory }
private val viewStateDelegate = ViewStateDelegate<LessonDemoFeature.LessonDemoState>()
private lateinit var wishlistViewDelegate: WishlistViewDelegate
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
App.componentManager()
.courseComponent(course.id)
.lessonDemoPresentationComponentBuilder()
.course(course)
.build()
.inject(this)
setStyle(DialogFragment.STYLE_NO_TITLE, R.style.TopCornersRoundedBottomSheetDialog)
lessonDemoViewModel.onNewMessage(LessonDemoFeature.Message.InitMessage())
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.bottom_sheet_dialog_lesson_demo_complete, container, false)
override fun onStart() {
super.onStart()
(dialog as? BottomSheetDialog)?.behavior?.state = BottomSheetBehavior.STATE_EXPANDED
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initViewStateDelegate()
wishlistViewDelegate = WishlistViewDelegate(demoWishlistAction)
demoCompleteTitle.text = getString(R.string.demo_complete_title, course.title)
demoCompleteAction.setOnClickListener {
lessonDemoViewModel.onNewMessage(LessonDemoFeature.Message.BuyActionMessage)
}
demoWishlistAction.setOnClickListener {
lessonDemoViewModel.onNewMessage(
LessonDemoFeature.Message.WishlistMessage(
WishlistOperationFeature.Message.WishlistAddMessage(course, CourseViewSource.LessonDemoDialog)
)
)
}
tryAgain.setOnClickListener { lessonDemoViewModel.onNewMessage(LessonDemoFeature.Message.InitMessage(forceUpdate = true)) }
}
override fun onAction(action: LessonDemoFeature.Action.ViewAction) {
if (action is LessonDemoFeature.Action.ViewAction.BuyAction) {
val currentFlow = CoursePurchaseFlow.valueOfWithFallback(
firebaseRemoteConfig[RemoteConfig.PURCHASE_FLOW_ANDROID]
.asString()
.uppercase()
)
val isInAppActive =
currentFlow.isInAppActive()
if (isInAppActive && action.coursePurchaseData != null) {
CoursePurchaseBottomSheetDialogFragment
.newInstance(action.coursePurchaseData, CoursePurchaseSource.DEMO_LESSON_DIALOG_SOURCE, isNeedRestoreMessage = false)
.showIfNotExists(childFragmentManager, CoursePurchaseBottomSheetDialogFragment.TAG)
} else {
screenManager.showCoursePurchaseFromLessonDemoDialog(
requireContext(),
course.id,
CourseViewSource.LessonDemoDialog,
CourseScreenTab.INFO,
action.deeplinkPromoCode
)
}
}
}
override fun render(state: LessonDemoFeature.State) {
viewStateDelegate.switchState(state.lessonDemoState)
wishlistViewDelegate.render(state.wishlistOperationState, mustEnable = true)
if (state.lessonDemoState is LessonDemoFeature.LessonDemoState.Content) {
if (state.lessonDemoState.coursePurchaseData != null) {
setupIAP(state.lessonDemoState.coursePurchaseData)
} else {
setupWeb(state.lessonDemoState.deeplinkPromoCode)
}
}
}
override fun onDestroy() {
App.componentManager().releaseCourseComponent(course.id)
super.onDestroy()
}
private fun initViewStateDelegate() {
viewStateDelegate.addState<LessonDemoFeature.LessonDemoState.Idle>()
viewStateDelegate.addState<LessonDemoFeature.LessonDemoState.Loading>(demoCompleteProgressbar)
viewStateDelegate.addState<LessonDemoFeature.LessonDemoState.Error>(demoCompleteNetworkError)
viewStateDelegate.addState<LessonDemoFeature.LessonDemoState.Unavailable>(demoCompleteContent, demoCompleteTitle, demoPurchaseUnavailable, demoWishlistAction)
viewStateDelegate.addState<LessonDemoFeature.LessonDemoState.Content>(demoCompleteContent, demoCompleteTitle, demoCompleteInfo, demoCompleteDivider, demoCompleteAction, demoWishlistAction)
}
private fun setupWeb(deeplinkPromoCode: DeeplinkPromoCode) {
val courseDisplayPrice = course.displayPrice
val (_, currencyCode, promoPrice, hasPromo) = coursePromoCodeResolver.resolvePromoCodeInfo(
deeplinkPromoCode,
DefaultPromoCode(
course.defaultPromoCodeName ?: "",
course.defaultPromoCodePrice ?: "",
course.defaultPromoCodeDiscount ?: "",
course.defaultPromoCodeExpireDate
),
course
)
demoCompleteAction.text =
if (courseDisplayPrice != null) {
if (hasPromo) {
displayPriceMapper.mapToDiscountedDisplayPriceSpannedString(courseDisplayPrice, promoPrice, currencyCode)
} else {
getString(R.string.course_payments_purchase_in_web_with_price, courseDisplayPrice)
}
} else {
getString(R.string.course_payments_purchase_in_web)
}
}
private fun setupIAP(coursePurchaseData: CoursePurchaseData) {
val courseDisplayPrice = coursePurchaseData.course.displayPrice
demoCompleteAction.text =
if (courseDisplayPrice != null) {
if (coursePurchaseData.promoCodeSku.lightSku != null) {
displayPriceMapper.mapToDiscountedDisplayPriceSpannedString(coursePurchaseData.primarySku.price, coursePurchaseData.promoCodeSku.lightSku.price)
} else {
getString(R.string.course_payments_purchase_in_web_with_price, coursePurchaseData.primarySku.price)
}
} else {
getString(R.string.course_payments_purchase_in_web)
}
}
override fun continueLearning() {
screenManager.showCourseAfterPurchase(requireContext(), course, CourseViewSource.LessonDemoDialog, CourseScreenTab.INFO)
}
} | apache-2.0 | 85c59c8a703e9cc4b18969a62f279076 | 45.801932 | 196 | 0.726541 | 5.098421 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/remote/auth/interceptor/AuthInterceptor.kt | 1 | 8348 | package org.stepik.android.remote.auth.interceptor
import android.content.Context
import com.vk.api.sdk.VK
import okhttp3.Interceptor
import okhttp3.Response
import org.stepic.droid.analytic.Analytic
import org.stepic.droid.configuration.EndpointResolver
import org.stepic.droid.configuration.Config
import org.stepic.droid.core.ScreenManager
import org.stepic.droid.core.StepikLogoutManager
import org.stepic.droid.preferences.SharedPreferenceHelper
import org.stepic.droid.util.AppConstants
import org.stepic.droid.util.DateTimeHelper
import org.stepic.droid.util.addUserAgent
import org.stepik.android.remote.auth.exception.FailRefreshException
import org.stepik.android.remote.auth.model.OAuthResponse
import org.stepik.android.remote.auth.service.EmptyAuthService
import org.stepik.android.remote.auth.service.OAuthService
import org.stepik.android.remote.base.CookieHelper
import org.stepik.android.remote.base.UserAgentProvider
import org.stepik.android.view.injection.qualifiers.AuthLock
import org.stepik.android.view.injection.qualifiers.AuthService
import org.stepik.android.view.injection.qualifiers.SocialAuthService
import retrofit2.Call
import timber.log.Timber
import java.io.IOException
import java.util.concurrent.locks.ReentrantReadWriteLock
import javax.inject.Inject
class AuthInterceptor
@Inject
constructor(
@AuthLock
private val authLock: ReentrantReadWriteLock,
private val sharedPreference: SharedPreferenceHelper,
private val stepikLogoutManager: StepikLogoutManager,
private val screenManager: ScreenManager,
private val endpointResolver: EndpointResolver,
private val config: Config,
private val context: Context,
private val userAgentProvider: UserAgentProvider,
private val cookieHelper: CookieHelper,
private val emptyAuthService: EmptyAuthService,
private val analytic: Analytic,
@SocialAuthService
private val socialAuthService: OAuthService,
@AuthService
private val authService: OAuthService
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
var request = chain.addUserAgent(userAgentProvider.provideUserAgent())
try {
authLock.readLock().lock()
var response = sharedPreference.authResponseFromStore
if (response == null) {
// it is Anonymous, we can log it.
val cookies = cookieHelper.getCookiesForBaseUrl()
?: cookieHelper.fetchCookiesForBaseUrl() // if token is expired or doesn't exist -> manager return null
if (cookies.isNotEmpty()) {
val cookieHeader = cookieHelper.getCookieHeader(cookies)
val csrfTokenFromCookies = cookieHelper.getCsrfTokenFromCookies(cookies)
if (sharedPreference.profile == null) {
val stepicProfileResponse = emptyAuthService.getUserProfileWithCookie(
endpointResolver.getBaseUrl(),
cookieHeader,
csrfTokenFromCookies
).execute().body()
if (stepicProfileResponse != null) {
val profile = stepicProfileResponse.getProfile()
sharedPreference.storeProfile(profile)
}
}
request = request
.newBuilder()
.addHeader(AppConstants.cookieHeaderName, cookieHeader)
.addHeader(AppConstants.refererHeaderName, endpointResolver.getBaseUrl())
.addHeader(AppConstants.csrfTokenHeaderName, csrfTokenFromCookies)
.build()
}
} else if (isUpdateNeeded(response)) {
try {
authLock.readLock().unlock()
authLock.writeLock().lock()
Timber.d("writer 1")
response = sharedPreference.authResponseFromStore
if (isUpdateNeeded(response)) {
val oAuthResponse: retrofit2.Response<OAuthResponse>
try {
oAuthResponse = authWithRefreshToken(response!!.refreshToken).execute()
response = oAuthResponse.body()
} catch (e: IOException) {
return chain.proceed(request)
} catch (e: Exception) {
analytic.reportError(Analytic.Error.CANT_UPDATE_TOKEN, e)
return chain.proceed(request)
}
if (response == null || !oAuthResponse.isSuccessful) {
// it is worst case:
val message: String = response?.toString() ?: "response was null"
var extendedMessage = ""
if (oAuthResponse.isSuccessful) {
extendedMessage = "was success ${oAuthResponse.code()}"
} else {
try {
extendedMessage = "failed ${oAuthResponse.code()} ${oAuthResponse.errorBody()?.string()}"
if (oAuthResponse.code() == 401) {
stepikLogoutManager.logout {
// LoginManager.getInstance().logOut()
VK.logout()
screenManager.showLaunchScreen(context)
}
}
} catch (ex: Exception) {
analytic.reportError(Analytic.Error.FAIL_REFRESH_TOKEN_INLINE_GETTING, ex)
}
}
analytic.reportError(Analytic.Error.FAIL_REFRESH_TOKEN_ONLINE_EXTENDED,
FailRefreshException(
extendedMessage
)
)
analytic.reportError(Analytic.Error.FAIL_REFRESH_TOKEN_ONLINE,
FailRefreshException(
message
)
)
analytic.reportEvent(Analytic.Web.UPDATE_TOKEN_FAILED)
return chain.proceed(request)
}
sharedPreference.storeAuthInfo(response)
}
} finally {
authLock.readLock().lock()
Timber.d("writer 2")
authLock.writeLock().unlock()
}
}
if (response != null) {
request = request.newBuilder().addHeader(AppConstants.authorizationHeaderName, getAuthHeaderValueForLogged()).build()
}
return chain.proceed(request)
} finally {
authLock.readLock().unlock()
}
}
private fun isUpdateNeeded(response: OAuthResponse?): Boolean {
if (response == null) {
Timber.d("Token is null")
return false
}
val timestampStored = sharedPreference.accessTokenTimestamp
if (timestampStored == -1L) return true
val nowTemp = DateTimeHelper.nowUtc()
val delta = nowTemp - timestampStored
val expiresMillis = (response.expiresIn - 50) * 1000
return delta > expiresMillis // token expired --> need update
}
private fun getAuthHeaderValueForLogged(): String {
val resp = sharedPreference.authResponseFromStore
?: return "" // not happen, look "resp null" in metrica before 07.2016
val accessToken = resp.accessToken
val type = resp.tokenType
return "$type $accessToken"
}
private fun authWithRefreshToken(refreshToken: String): Call<OAuthResponse> =
(if (sharedPreference.isLastTokenSocial) socialAuthService else authService)
.updateToken(config.refreshGrantType, refreshToken)
} | apache-2.0 | ceb959e5f3e7bde7de47f4698d18bd5c | 45.127072 | 133 | 0.565884 | 5.737457 | false | false | false | false |
resilience4j/resilience4j | resilience4j-kotlin/src/main/kotlin/io/github/resilience4j/kotlin/bulkhead/BulkheadRegistry.kt | 2 | 4394 | /*
*
* Copyright 2020
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*
*/
@file:Suppress("FunctionName")
package io.github.resilience4j.kotlin.bulkhead
import io.github.resilience4j.bulkhead.BulkheadConfig
import io.github.resilience4j.bulkhead.BulkheadRegistry
/**
* Creates new custom [BulkheadRegistry].
*
* ```kotlin
* val bulkheadRegistry = BulkheadRegistry {
* withBulkheadConfig(defaultConfig)
* withTags(commonTags)
* }
* ```
*
* @param config methods of [BulkheadRegistry.Builder] that customize resulting `BulkheadRegistry`
*/
inline fun BulkheadRegistry(
config: BulkheadRegistry.Builder.() -> Unit
): BulkheadRegistry {
return BulkheadRegistry.custom().apply(config).build()
}
/**
* Configures a [BulkheadRegistry] with a custom default Bulkhead configuration.
*
* ```kotlin
* val bulkheadRegistry = BulkheadRegistry {
* withBulkheadConfig {
* maxConcurrentCalls(2)
* maxWaitDuration(Duration.ZERO)
* }
* }
* ```
*
* @param config methods of [BulkheadConfig.Builder] that customize the default `BulkheadConfig`
*/
inline fun BulkheadRegistry.Builder.withBulkheadConfig(
config: BulkheadConfig.Builder.() -> Unit
) {
withBulkheadConfig(BulkheadConfig(config))
}
/**
* Configures a [BulkheadRegistry] with a custom default Bulkhead configuration.
*
* ```kotlin
* val bulkheadRegistry = BulkheadRegistry {
* withBulkheadConfig(baseBulkheadConfig) {
* maxConcurrentCalls(2)
* maxWaitDuration(Duration.ZERO)
* }
* }
* ```
*
* @param baseConfig base `BulkheadConfig`
* @param config methods of [BulkheadConfig.Builder] that customize the default `BulkheadConfig`
*/
inline fun BulkheadRegistry.Builder.withBulkheadConfig(
baseConfig: BulkheadConfig,
config: BulkheadConfig.Builder.() -> Unit
) {
withBulkheadConfig(BulkheadConfig(baseConfig, config))
}
/**
* Configures a [BulkheadRegistry] with a custom Bulkhead configuration.
*
* ```kotlin
* val bulkheadRegistry = BulkheadRegistry {
* addBulkheadConfig("sharedConfig1") {
* maxConcurrentCalls(2)
* maxWaitDuration(Duration.ZERO)
* }
* }
* ```
*
* @param configName configName for a custom shared Bulkhead configuration
* @param config methods of [BulkheadConfig.Builder] that customize resulting `BulkheadConfig`
*/
inline fun BulkheadRegistry.Builder.addBulkheadConfig(
configName: String,
config: BulkheadConfig.Builder.() -> Unit
) {
addBulkheadConfig(configName, BulkheadConfig(config))
}
/**
* Configures a [BulkheadRegistry] with a custom Bulkhead configuration.
*
* ```kotlin
* val bulkheadRegistry = BulkheadRegistry {
* addBulkheadConfig("sharedConfig1", baseBulkheadConfig) {
* maxConcurrentCalls(2)
* maxWaitDuration(Duration.ZERO)
* }
* }
* ```
*
* @param configName configName for a custom shared Bulkhead configuration
* @param baseConfig base `BulkheadConfig`
* @param config methods of [BulkheadConfig.Builder] that customize resulting `BulkheadConfig`
*/
inline fun BulkheadRegistry.Builder.addBulkheadConfig(
configName: String,
baseConfig: BulkheadConfig,
config: BulkheadConfig.Builder.() -> Unit
) {
addBulkheadConfig(configName, BulkheadConfig(baseConfig, config))
}
/**
* Configures a [BulkheadRegistry] with Tags.
*
* Tags added to the registry will be added to every instance created by this registry.
*
* @param tags default tags to add to the registry.
*/
fun BulkheadRegistry.Builder.withTags(tags: Map<String, String>) {
withTags(tags)
}
/**
* Configures a [BulkheadRegistry] with Tags.
*
* Tags added to the registry will be added to every instance created by this registry.
*
* @param tags default tags to add to the registry.
*/
fun BulkheadRegistry.Builder.withTags(vararg tags: Pair<String, String>) {
withTags(HashMap(tags.toMap()))
}
| apache-2.0 | be7db4e8f43eb22b66716c40d7f3f3ae | 28.293333 | 100 | 0.720983 | 3.837555 | false | true | false | false |
aporter/coursera-android | ExamplesKotlin/FragmentDynamicLayoutWithActionBar/app/src/main/java/course/examples/fragments/actionbar/TitlesFragment.kt | 1 | 4276 | package course.examples.fragments.actionbar
import android.content.Context
import android.os.Bundle
import android.support.v4.app.ListFragment
import android.util.Log
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.Toast
//Several Activity and Fragment lifecycle methods are instrumented to emit LogCat output
//so you can follow the class' lifecycle
class TitlesFragment : ListFragment() {
companion object {
private const val TAG = "TitlesFragment"
}
private var mListener: ListSelectionListener? = null
private var mCurrIdx = ListView.INVALID_POSITION
fun unCheckSelection() {
if (listView.checkedItemCount > 0) {
listView.setItemChecked(listView.checkedItemPosition, false)
}
mCurrIdx = ListView.INVALID_POSITION
}
// Called when the user selects an item from the List
override fun onListItemClick(l: ListView, v: View, pos: Int, id: Long) {
if (mCurrIdx != pos) {
mCurrIdx = pos
// Indicates the selected item has been checked
l.setItemChecked(mCurrIdx, true)
// Inform the QuoteViewerActivity that the item in position pos has been selected
mListener?.onListSelection(mCurrIdx)
}
}
override fun onAttach(context: Context) {
super.onAttach(context)
// Set the ListSelectionListener for communicating with the QuoteViewerActivity
mListener = context as? ListSelectionListener
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// This Fragment will add items to the ActionBar
setHasOptionsMenu(true)
// Retain this Fragment across Activity Reconfigurations
retainInstance = true
}
override fun onActivityCreated(savedState: Bundle?) {
Log.i(TAG, "${javaClass.simpleName}: entered onActivityCreated()")
super.onActivityCreated(savedState)
// Set the list adapter for the ListView
// Discussed in more detail in the user interface classes lesson
listAdapter = ArrayAdapter(
activity as Context,
R.layout.title_item, resources.getStringArray(R.array.Titles)
)
// Set the list choice mode to allow only one selection at a time
listView.choiceMode = ListView.CHOICE_MODE_SINGLE
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
// Inflate the options Menu using title_menu.xml
inflater.inflate(R.menu.title_menu, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.title_menu_item -> {
// Show a Toast Message. Toast Messages are discussed in the lesson on user interface classes
Toast.makeText(
activity?.applicationContext,
"This action provided by the TitlesFragment",
Toast.LENGTH_SHORT
).show()
// return value true indicates that the menu click has been handled
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
override fun onStart() {
Log.i(TAG, "${javaClass.simpleName}: entered onStart()")
super.onStart()
}
override fun onResume() {
Log.i(TAG, "${javaClass.simpleName}: entered onResume()")
super.onResume()
}
override fun onPause() {
Log.i(TAG, "${javaClass.simpleName}: entered onPause()")
super.onPause()
}
override fun onStop() {
Log.i(TAG, "${javaClass.simpleName}: entered onStop()")
super.onStop()
}
override fun onDetach() {
Log.i(TAG, "${javaClass.simpleName}: entered onDetach()")
super.onDetach()
}
override fun onDestroy() {
Log.i(TAG, "${javaClass.simpleName}: entered onDestroy()")
super.onDestroy()
}
override fun onDestroyView() {
Log.i(TAG, "${javaClass.simpleName}: entered onDestroyView()")
super.onDestroyView()
}
} | mit | 9aa0b95ed02d5cbc2d49059a9a89ae21 | 29.55 | 109 | 0.644761 | 4.983683 | false | false | false | false |
paulinabls/hangman | app/src/test/kotlin/com/intive/hangman/engine/SpekGameTest.kt | 1 | 1483 | package com.intive.hangman.engine
import com.intive.hangman.TextUtils
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import org.junit.Assert
import org.junit.Assert.assertEquals
import kotlin.test.assertFalse
//@RunWith(JUnitPlatform::class)
class SpekGameTest : Spek({
describe("a game") {
given("newly created game") {
val hangman = Game(password = "microwave")
it("has 0 wrong answers") {
assertEquals(0, hangman.wrongAnswers)
}
it("has all letters dashed") {
assertEquals("_________", hangman.dashedPassword)
}
}
val hangman = Game(password = "microwave")
on("correct letter suggested") {
val contains = hangman.suggestLetter('A')
it("returns true") {
Assert.assertTrue(contains)
}
it("number of wrong answers did not increase") {
assertEquals(0, hangman.wrongAnswers)
}
}
on("any wrong letter suggested ") {
val wrongLettersRange = TextUtils.createAlphabetRangeNotIn("microwave")
for (c in wrongLettersRange) {
it("for $c returns false") {
assertFalse(hangman.suggestLetter(c))
}
}
}
}
}) | mit | d8ff2fce3d3cc8578036d144893bacea | 28.098039 | 83 | 0.582603 | 4.298551 | false | false | false | false |
leafclick/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/highlighter/GroovyColorSettingsPage.kt | 1 | 9045 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.highlighter
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.options.colors.AttributesDescriptor
import com.intellij.openapi.options.colors.ColorDescriptor
import com.intellij.openapi.options.colors.ColorSettingsPage
import icons.JetgroovyIcons
import org.jetbrains.annotations.NonNls
import org.jetbrains.plugins.groovy.highlighter.GroovySyntaxHighlighter.*
import javax.swing.Icon
class GroovyColorSettingsPage : ColorSettingsPage {
private companion object {
val attributes = mapOf(
"Annotations//Annotation attribute name" to ANNOTATION_ATTRIBUTE_NAME,
"Annotations//Annotation name" to ANNOTATION,
"Braces and Operators//Braces" to BRACES,
"Braces and Operators//Closure expression braces and arrow" to CLOSURE_ARROW_AND_BRACES,
"Braces and Operators//Lambda expression braces and arrow " to LAMBDA_ARROW_AND_BRACES,
"Braces and Operators//Brackets" to BRACKETS,
"Braces and Operators//Parentheses" to PARENTHESES,
"Braces and Operators//Operator sign" to OPERATION_SIGN,
"Comments//Line comment" to LINE_COMMENT,
"Comments//Block comment" to BLOCK_COMMENT,
"Comments//Groovydoc//Text" to DOC_COMMENT_CONTENT,
"Comments//Groovydoc//Tag" to DOC_COMMENT_TAG,
"Classes and Interfaces//Class" to CLASS_REFERENCE,
"Classes and Interfaces//Abstract class" to ABSTRACT_CLASS_NAME,
"Classes and Interfaces//Anonymous class" to ANONYMOUS_CLASS_NAME,
"Classes and Interfaces//Interface" to INTERFACE_NAME,
"Classes and Interfaces//Trait" to TRAIT_NAME,
"Classes and Interfaces//Enum" to ENUM_NAME,
"Classes and Interfaces//Type parameter" to TYPE_PARAMETER,
"Methods//Method declaration" to METHOD_DECLARATION,
"Methods//Constructor declaration" to CONSTRUCTOR_DECLARATION,
"Methods//Instance method call" to METHOD_CALL,
"Methods//Static method call" to STATIC_METHOD_ACCESS,
"Methods//Constructor call" to CONSTRUCTOR_CALL,
"Fields//Instance field" to INSTANCE_FIELD,
"Fields//Static field" to STATIC_FIELD,
"Variables and Parameters//Local variable" to LOCAL_VARIABLE,
"Variables and Parameters//Reassigned local variable" to REASSIGNED_LOCAL_VARIABLE,
"Variables and Parameters//Parameter" to PARAMETER,
"Variables and Parameters//Reassigned parameter" to REASSIGNED_PARAMETER,
"References//Instance property reference" to INSTANCE_PROPERTY_REFERENCE,
"References//Static property reference" to STATIC_PROPERTY_REFERENCE,
"References//Unresolved reference" to UNRESOLVED_ACCESS,
"Strings//String" to STRING,
"Strings//GString" to GSTRING,
"Strings//Valid string escape" to VALID_STRING_ESCAPE,
"Strings//Invalid string escape" to INVALID_STRING_ESCAPE,
"Keyword" to KEYWORD,
"Number" to NUMBER,
"Bad character" to BAD_CHARACTER,
"List/map to object conversion" to LITERAL_CONVERSION,
"Map key/Named argument" to MAP_KEY,
"Label" to LABEL
).map { AttributesDescriptor(it.key, it.value) }.toTypedArray()
val additionalTags = mapOf(
"annotation" to ANNOTATION,
"annotationAttribute" to ANNOTATION_ATTRIBUTE_NAME,
"groovydoc" to DOC_COMMENT_CONTENT,
"groovydocTag" to DOC_COMMENT_TAG,
"class" to CLASS_REFERENCE,
"abstractClass" to ABSTRACT_CLASS_NAME,
"anonymousClass" to ANONYMOUS_CLASS_NAME,
"interface" to INTERFACE_NAME,
"trait" to TRAIT_NAME,
"enum" to ENUM_NAME,
"typeParameter" to TYPE_PARAMETER,
"method" to METHOD_DECLARATION,
"constructor" to CONSTRUCTOR_DECLARATION,
"instanceMethodCall" to METHOD_CALL,
"staticMethodCall" to STATIC_METHOD_ACCESS,
"constructorCall" to CONSTRUCTOR_CALL,
"instanceField" to INSTANCE_FIELD,
"staticField" to STATIC_FIELD,
"localVariable" to LOCAL_VARIABLE,
"reassignedVariable" to REASSIGNED_LOCAL_VARIABLE,
"parameter" to PARAMETER,
"reassignedParameter" to REASSIGNED_PARAMETER,
"instanceProperty" to INSTANCE_PROPERTY_REFERENCE,
"staticProperty" to STATIC_PROPERTY_REFERENCE,
"unresolved" to UNRESOLVED_ACCESS,
"keyword" to KEYWORD,
"literalConstructor" to LITERAL_CONVERSION,
"mapKey" to MAP_KEY,
"label" to LABEL,
"validEscape" to VALID_STRING_ESCAPE,
"invalidEscape" to INVALID_STRING_ESCAPE,
"closureBraces" to CLOSURE_ARROW_AND_BRACES,
"lambdaBraces" to LAMBDA_ARROW_AND_BRACES
)
}
override fun getDisplayName(): String = "Groovy"
override fun getIcon(): Icon? = JetgroovyIcons.Groovy.Groovy_16x16
override fun getAttributeDescriptors(): Array<AttributesDescriptor> = attributes
override fun getColorDescriptors(): Array<out ColorDescriptor> = ColorDescriptor.EMPTY_ARRAY
override fun getHighlighter(): GroovySyntaxHighlighter = GroovySyntaxHighlighter()
override fun getAdditionalHighlightingTagToDescriptorMap(): Map<String, TextAttributesKey> = additionalTags
@NonNls
override fun getDemoText(): String = """<keyword>package</keyword> highlighting
###
<groovydoc>/**
* This is Groovydoc comment
* <groovydocTag>@see</groovydocTag> java.lang.String#equals
*/</groovydoc>
<annotation>@Annotation</annotation>(<annotationAttribute>parameter</annotationAttribute> = 'value')
<keyword>class</keyword> <class>C</class> {
<keyword>def</keyword> <instanceField>property</instanceField> = <keyword>new</keyword> <anonymousClass>I</anonymousClass>() {}
<keyword>static</keyword> <keyword>def</keyword> <staticField>staticProperty</staticField> = []
<constructor>C</constructor>() {}
<keyword>def</keyword> <<typeParameter>T</typeParameter>> <typeParameter>T</typeParameter> <method>instanceMethod</method>(T <parameter>parameter</parameter>, <reassignedParameter>reassignedParameter</reassignedParameter>) {
<reassignedParameter>reassignedParameter</reassignedParameter> = 1
//This is a line comment
<keyword>return</keyword> <parameter>parameter</parameter>
}
<keyword>def</keyword> <method>getStuff</method>() { 42 }
<keyword>static</keyword> <keyword>boolean</keyword> <method>isStaticStuff</method>() { true }
<keyword>static</keyword> <keyword>def</keyword> <method>staticMethod</method>(<keyword>int</keyword> <parameter>i</parameter>) {
/* This is a block comment */
<interface>Map</interface> <localVariable>map</localVariable> = [<mapKey>key1</mapKey>: 1, <mapKey>key2</mapKey>: 2, (22): 33]
<keyword>def</keyword> <localVariable>cl</localVariable> = <closureBraces>{</closureBraces> <parameter>a</parameter> <closureBraces>-></closureBraces> <parameter>a</parameter> <closureBraces>}</closureBraces>
<keyword>def</keyword> <localVariable>lambda</localVariable> = <parameter>b</parameter> <lambdaBraces>-></lambdaBraces> <lambdaBraces>{</lambdaBraces> <parameter>b</parameter> <lambdaBraces>}</lambdaBraces>
<class>File</class> <localVariable>f</localVariable> = <literalConstructor>[</literalConstructor>'path'<literalConstructor>]</literalConstructor>
<keyword>def</keyword> <reassignedVariable>a</reassignedVariable> = 'JetBrains'.<instanceMethodCall>matches</instanceMethodCall>(/Jw+Bw+/)
<label>label</label>:
<keyword>for</keyword> (<localVariable>entry</localVariable> <keyword>in</keyword> <localVariable>map</localVariable>) {
<keyword>if</keyword> (<localVariable>entry</localVariable>.value > 1 && <parameter>i</parameter> < 2) {
<reassignedVariable>a</reassignedVariable> = <unresolved>unresolvedReference</unresolved>
<keyword>continue</keyword> label
} <keyword>else</keyword> {
<reassignedVariable>a</reassignedVariable> = <localVariable>entry</localVariable>
}
}
<instanceMethodCall>print</instanceMethodCall> <localVariable>map</localVariable>.<mapKey>key1</mapKey>
}
}
<keyword>def</keyword> <localVariable>c</localVariable> = <keyword>new</keyword> <constructorCall>C</constructorCall>()
<localVariable>c</localVariable>.<instanceMethodCall>instanceMethod</instanceMethodCall>("Hello<validEscape>\n</validEscape>", 'world<invalidEscape>\x</invalidEscape>')
<instanceMethodCall>println</instanceMethodCall> <localVariable>c</localVariable>.<instanceProperty>stuff</instanceProperty>
<class>C</class>.<staticMethodCall>staticMethod</staticMethodCall>(<mapKey>namedArg</mapKey>: 1)
<class>C</class>.<staticProperty>staticStuff</staticProperty>
<keyword>abstract</keyword> <keyword>class</keyword> <abstractClass>AbstractClass</abstractClass> {}
<keyword>interface</keyword> <interface>I</interface> {}
<keyword>trait</keyword> <trait>T</trait> {}
<keyword>enum</keyword> <enum>E</enum> {}
@<keyword>interface</keyword> <annotation>Annotation</annotation> {
<class>String</class> <method>parameter</method>()
}
"""
}
| apache-2.0 | 480964b2a5ff1f064a98646b90310515 | 45.865285 | 226 | 0.731786 | 4.340211 | false | false | false | false |
HTWDD/HTWDresden | app/src/main/java/de/htwdd/htwdresden/ui/viewmodels/fragments/MealsViewModel.kt | 1 | 4179 | package de.htwdd.htwdresden.ui.viewmodels.fragments
import androidx.lifecycle.ViewModel
import de.htwdd.htwdresden.adapter.Meals
import de.htwdd.htwdresden.network.RestApi
import de.htwdd.htwdresden.ui.models.Meal
import de.htwdd.htwdresden.ui.models.MealHeaderItem
import de.htwdd.htwdresden.ui.models.MealItem
import de.htwdd.htwdresden.utils.extensions.datesOfCurrentWeek
import de.htwdd.htwdresden.utils.extensions.datesOfNextWeek
import de.htwdd.htwdresden.utils.extensions.format
import de.htwdd.htwdresden.utils.extensions.runInThread
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
class MealsViewModel: ViewModel() {
var type: String = "today"
@Suppress("UNCHECKED_CAST")
fun request(id: Int): Observable<Meals> { // different reuqest for week type
return when (type) {
"week" -> requestForWeek("$id").onErrorReturn { Meals() } // request meals for current week
"nextWeek" -> requestForWeek("$id", false).onErrorReturn { Meals() } // request meals for next week
else -> requestForDay("$id").onErrorReturn { Meals() } // request meals for today
}
}
private fun requestForDay(id: String): Observable<Meals> {
return RestApi
.canteenEndpoint
.getMeals(id, Date().format("yyyy-MM-dd")) // api call
.runInThread(Schedulers.io())
.map { it.map { jMeal -> Meal.from(jMeal) } } // json to model
.map { meals ->
val sortedKeys = mutableSetOf<String>()
val sortedValues = mutableSetOf<Meal>()
meals.groupBy { it.category }.apply {
keys.sorted().forEach { sortedKeys.add(it) }
values.forEach { v -> v.forEach { sortedValues.add(it) } }
}
sortedKeys to sortedValues // grouped elements
}
.map { pair ->
val result = Meals()
pair.first.forEach { key ->
result.add(MealHeaderItem(key, Date().format("dd. MMMM")))
result.addAll(pair.second.filter { it.category.contains(key) }.map { MealItem(it) })
}
result
}
}
@Suppress("UNCHECKED_CAST")
private fun requestForWeek(id: String, isCurrentWeek: Boolean = true): Observable<Meals> {
val weeks = if (isCurrentWeek) {
GregorianCalendar.getInstance(Locale.GERMAN).datesOfCurrentWeek // all dates for current week
} else {
GregorianCalendar.getInstance(Locale.GERMAN).datesOfNextWeek // all dates for next week
}
return Observable.combineLatest(
weeks // combine all requested dates
.map { it.format("yyyy-MM-dd") }
.map { RestApi.canteenEndpoint.getMeals(id, it).runInThread(Schedulers.io()) }
.map { it.map { jMeals -> jMeals.map { jMeal -> Meal.from(jMeal) } } }
) { it.toCollection(ArrayList()) as ArrayList<List<Meal>> }
.runInThread()
.map { meals ->
val hMap = HashMap<Date, List<Meal>>() // map into hasMap with k = date and v = list of meals
for (i in 0 until weeks.size) {
hMap[weeks[i]] = meals[i]
}
hMap.toSortedMap()
}
.map { hMap ->
val result = Meals()
for ((k, v) in hMap) {
result.add(MealHeaderItem(k.format("EEEE"), k.format("dd. MMMM")))
result.addAll(v.map { MealItem(it) })
}
result
}
}
} | mit | a1810937b9f6b9e14d1499dbb73f39c4 | 46.5 | 154 | 0.52716 | 4.653675 | false | false | false | false |
leafclick/intellij-community | platform/workspaceModel-ide-tests/testSrc/com/intellij/workspace/jps/ImlReplaceBySourceTest.kt | 1 | 4502 | package com.intellij.workspace.jps
import com.intellij.openapi.application.ex.PathManagerEx
import com.intellij.testFramework.ApplicationRule
import com.intellij.testFramework.rules.TempDirectory
import com.intellij.workspace.api.*
import com.intellij.workspace.ide.JpsFileEntitySource
import com.intellij.workspace.ide.JpsProjectStoragePlace
import org.junit.Assert
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import java.io.File
class ImlReplaceBySourceTest {
@Test
fun sampleProject() {
val projectDir = File(PathManagerEx.getCommunityHomePath(), "jps/model-serialization/testData/sampleProject")
replaceBySourceFullReplace(projectDir)
}
@Test
fun communityProject() {
val projectDir = File(PathManagerEx.getCommunityHomePath())
replaceBySourceFullReplace(projectDir)
}
@Suppress("UNCHECKED_CAST")
@Test
fun addSourceRootToModule() {
val moduleFile = temp.newFile("a.iml")
moduleFile.writeText("""
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://${'$'}MODULE_DIR${'$'}">
<sourceFolder url="file://${'$'}MODULE_DIR${'$'}/src" isTestSource="false" />
<sourceFolder url="file://${'$'}MODULE_DIR${'$'}/testSrc" isTestSource="true" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="kotlin-stdlib-jdk8" level="project" />
</component>
</module>
""".trimIndent())
val storagePlace = JpsProjectStoragePlace.DirectoryBased(temp.root.toVirtualFileUrl())
val builder = TypedEntityStorageBuilder.create()
JpsProjectEntitiesLoader.loadModule(moduleFile, storagePlace, builder)
moduleFile.writeText("""
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://${'$'}MODULE_DIR${'$'}">
<sourceFolder url="file://${'$'}MODULE_DIR${'$'}/src" isTestSource="false" />
<sourceFolder url="file://${'$'}MODULE_DIR${'$'}/src2" generated="true" />
<sourceFolder url="file://${'$'}MODULE_DIR${'$'}/testSrc" isTestSource="true" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
""".trimIndent())
val replaceWith = TypedEntityStorageBuilder.create()
val source = builder.entities(ModuleEntity::class.java).first().entitySource as JpsFileEntitySource.FileInDirectory
JpsProjectEntitiesLoader.loadModule(moduleFile, source, storagePlace, replaceWith)
val before = builder.toStorage()
builder.resetChanges()
builder.replaceBySource({ true }, replaceWith.toStorage())
val changes = builder.collectChanges(before).values.flatten()
Assert.assertEquals(3, changes.size)
Assert.assertEquals(3, (changes[0] as EntityChange.Replaced<ModuleEntity>).oldEntity.dependencies.size)
Assert.assertEquals(2, (changes[0] as EntityChange.Replaced<ModuleEntity>).newEntity.dependencies.size)
Assert.assertEquals(File(temp.root, "src2").toVirtualFileUrl().url, (changes[1] as EntityChange.Added<SourceRootEntity>).entity.url.url)
Assert.assertEquals(true, (changes[2] as EntityChange.Added<JavaSourceRootEntity>).entity.generated)
}
private fun replaceBySourceFullReplace(projectFile: File) {
val storageBuilder1 = TypedEntityStorageBuilder.create()
val data = JpsProjectEntitiesLoader.loadProject(projectFile.asStoragePlace(), storageBuilder1)
val storageBuilder2 = TypedEntityStorageBuilder.create()
val reader = CachingJpsFileContentReader(projectFile.asStoragePlace().baseDirectoryUrl)
data.loadAll(reader, storageBuilder2)
//println(storageBuilder1.toGraphViz())
//println(storageBuilder2.toGraphViz())
val before = storageBuilder1.toStorage()
storageBuilder1.resetChanges()
storageBuilder1.replaceBySource(sourceFilter = { true }, replaceWith = storageBuilder2.toStorage())
storageBuilder1.checkConsistency()
val changes = storageBuilder1.collectChanges(before)
Assert.assertTrue(changes.isEmpty())
}
@Rule
@JvmField
val temp = TempDirectory()
companion object {
@JvmField
@ClassRule
val appRule = ApplicationRule()
}
}
| apache-2.0 | da65e3140792e9cdd10d503f20a81cc6 | 38.147826 | 140 | 0.710351 | 4.694473 | false | true | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/reflection/genericSignature/functionLiteralGenericSignature.kt | 2 | 1720 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
import java.util.Date
fun assertGenericSuper(expected: String, function: Any?) {
val clazz = (function as java.lang.Object).getClass()!!
val genericSuper = clazz.getGenericInterfaces()[0]!!
if ("$genericSuper" != expected)
throw AssertionError("Fail, expected: $expected, actual: $genericSuper")
}
val unitFun = { }
val intFun = { 42 }
val stringParamFun = { x: String -> }
val listFun = { l: List<String> -> l }
val mutableListFun = fun (l: MutableList<Double>): MutableList<Int> = null!!
val funWithIn = fun (x: Comparable<String>) {}
val extensionFun = fun Any.() {}
val extensionWithArgFun = fun Long.(x: Any): Date = Date()
fun box(): String {
assertGenericSuper("kotlin.jvm.functions.Function0<kotlin.Unit>", unitFun)
assertGenericSuper("kotlin.jvm.functions.Function0<java.lang.Integer>", intFun)
assertGenericSuper("kotlin.jvm.functions.Function1<java.lang.String, kotlin.Unit>", stringParamFun)
assertGenericSuper("kotlin.jvm.functions.Function1<java.util.List<? extends java.lang.String>, java.util.List<? extends java.lang.String>>", listFun)
assertGenericSuper("kotlin.jvm.functions.Function1<java.util.List<java.lang.Double>, java.util.List<java.lang.Integer>>", mutableListFun)
assertGenericSuper("kotlin.jvm.functions.Function1<java.lang.Comparable<? super java.lang.String>, kotlin.Unit>", funWithIn)
assertGenericSuper("kotlin.jvm.functions.Function1<java.lang.Object, kotlin.Unit>", extensionFun)
assertGenericSuper("kotlin.jvm.functions.Function2<java.lang.Long, java.lang.Object, java.util.Date>", extensionWithArgFun)
return "OK"
}
| apache-2.0 | 00f743aa83840955f79559ed480ac9bd | 46.777778 | 153 | 0.734302 | 3.598326 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/reflection/properties/getDelegate/boundExtensionProperty.kt | 2 | 776 | // IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
import kotlin.reflect.KProperty
import kotlin.reflect.jvm.isAccessible
import kotlin.test.*
object Delegate {
var storage = ""
operator fun getValue(instance: Any?, property: KProperty<*>) = storage
operator fun setValue(instance: Any?, property: KProperty<*>, value: String) { storage = value }
}
class Foo
var Foo.result: String by Delegate
fun box(): String {
val foo = Foo()
foo.result = "Fail"
val d = (foo::result).apply { isAccessible = true }.getDelegate() as Delegate
foo.result = "OK"
assertEquals(d, (foo::result).apply { isAccessible = true }.getDelegate())
assertEquals(d, (Foo()::result).apply { isAccessible = true }.getDelegate())
return d.getValue(foo, Foo::result)
}
| apache-2.0 | faa6e4f945c03613110b39c612a89e01 | 28.846154 | 100 | 0.681701 | 3.919192 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/reflection/types/subtyping/typeProjection.kt | 2 | 1038 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
import kotlin.reflect.full.isSubtypeOf
import kotlin.test.assertTrue
import kotlin.test.assertFalse
class G<T>
fun number(): G<Number> = null!!
fun outNumber(): G<out Number> = null!!
fun inNumber(): G<in Number> = null!!
fun star(): G<*> = null!!
fun box(): String {
val n = ::number.returnType
val o = ::outNumber.returnType
val i = ::inNumber.returnType
val st = ::star.returnType
// G<Number> <: G<out Number>
assertTrue(n.isSubtypeOf(o))
assertFalse(o.isSubtypeOf(n))
// G<Number> <: G<in Number>
assertTrue(n.isSubtypeOf(i))
assertFalse(i.isSubtypeOf(n))
// G<Number> <: G<*>
assertTrue(n.isSubtypeOf(st))
assertFalse(st.isSubtypeOf(n))
// G<out Number> <: G<*>
assertTrue(o.isSubtypeOf(st))
assertFalse(st.isSubtypeOf(o))
// G<in Number> <: G<*>
assertTrue(i.isSubtypeOf(st))
assertFalse(st.isSubtypeOf(i))
return "OK"
}
| apache-2.0 | 6356e29b2c0fddc64a5f87b06c7935df | 22.590909 | 72 | 0.646435 | 3.46 | false | false | false | false |
blokadaorg/blokada | android5/app/src/main/java/model/ConnectivityModel.kt | 1 | 3664 | /*
* This file is part of Blokada.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Copyright © 2021 Blocka AB. All rights reserved.
*
* @author Karol Gusak ([email protected])
*/
package model
import android.content.Context
import com.squareup.moshi.JsonClass
import org.blokada.R
import repository.DnsDataSource
import ui.utils.now
@JsonClass(generateAdapter = true)
data class NetworkDescriptor(
val name: String?,
val type: NetworkType = NetworkType.FALLBACK
) {
companion object {
fun wifi(name: String?) = NetworkDescriptor(name, NetworkType.WIFI)
fun cell(name: String?) = NetworkDescriptor(name, NetworkType.CELLULAR)
fun fallback() = NetworkDescriptor(null, NetworkType.FALLBACK)
}
fun id() = "$type:$name"
fun isFallback() = type == NetworkType.FALLBACK
override fun toString(): String {
return "($name, type=$type)"
}
}
enum class NetworkType {
WIFI, CELLULAR, FALLBACK
}
@JsonClass(generateAdapter = true)
data class NetworkSpecificConfig(
val network: NetworkDescriptor,
val enabled: Boolean,
val encryptDns: Boolean,
val useNetworkDns: Boolean,
val dnsChoice: DnsId,
val useBlockaDnsInPlusMode: Boolean,
val forceLibreMode: Boolean,
val createdAt: Long = 0
) {
override fun toString(): String {
return summarize().joinToString(", ") {
if (it.second is Boolean) it.first
else "${it.first}:${it.second}"
}
}
fun summarizeLocalised(ctx: Context): String {
return summarize().mapNotNull {
when (it.first) {
"encryptDns" -> ctx.getString(R.string.networks_action_encrypt_dns)
"useNetworkDns" -> ctx.getString(R.string.networks_action_use_network_dns)
"dnsChoice" -> ctx.getString(
R.string.networks_action_use_dns,
DnsDataSource.byId(it.second as DnsId).label
)
"forceLibreMode" -> ctx.getString(R.string.networks_action_force_libre_mode)
else -> null
}
}.joinToString(", ")
}
fun summarize(): List<Pair<String, Any>> {
return listOf(
"encryptDns" to encryptDns,
"useNetworkDns" to useNetworkDns,
"dnsChoice" to dnsChoice,
"useBlockaDnsInPlusMode" to useBlockaDnsInPlusMode,
"forceLibreMode" to forceLibreMode,
).filter { it.second !is Boolean || it.second == true }
}
fun canBePurged(): Boolean {
return when {
network.isFallback() -> false
network.name == null -> false // "Any wifi network" / "Any mobile network"
createdAt + 1000 * 60 * 60 * 24 * 7 > now() -> false // Detected this week
enabled -> false
else -> {
val defaults = Defaults.defaultNetworkConfig()
when {
encryptDns != defaults.encryptDns -> false
useNetworkDns != defaults.useNetworkDns -> false
dnsChoice != defaults.dnsChoice -> false
useBlockaDnsInPlusMode != defaults.useBlockaDnsInPlusMode -> false
forceLibreMode != defaults.forceLibreMode -> false
else -> true
}
}
}
}
}
typealias NetworkId = String
@JsonClass(generateAdapter = true)
data class NetworkSpecificConfigs(
val configs: List<NetworkSpecificConfig>
)
| mpl-2.0 | 66af0483d0ce3320a48b5fc32c003762 | 30.577586 | 92 | 0.605788 | 4.239583 | false | false | false | false |
android/compose-samples | JetNews/app/src/main/java/com/example/jetnews/ui/interests/InterestsViewModel.kt | 1 | 4506 | /*
* 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.jetnews.ui.interests
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.example.jetnews.data.interests.InterestSection
import com.example.jetnews.data.interests.InterestsRepository
import com.example.jetnews.data.interests.TopicSelection
import com.example.jetnews.data.successOr
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
/**
* UI state for the Interests screen
*/
data class InterestsUiState(
val topics: List<InterestSection> = emptyList(),
val people: List<String> = emptyList(),
val publications: List<String> = emptyList(),
val loading: Boolean = false,
)
class InterestsViewModel(
private val interestsRepository: InterestsRepository
) : ViewModel() {
// UI state exposed to the UI
private val _uiState = MutableStateFlow(InterestsUiState(loading = true))
val uiState: StateFlow<InterestsUiState> = _uiState.asStateFlow()
val selectedTopics =
interestsRepository.observeTopicsSelected().stateIn(
viewModelScope,
SharingStarted.WhileSubscribed(5000),
emptySet()
)
val selectedPeople =
interestsRepository.observePeopleSelected().stateIn(
viewModelScope,
SharingStarted.WhileSubscribed(5000),
emptySet()
)
val selectedPublications =
interestsRepository.observePublicationSelected().stateIn(
viewModelScope,
SharingStarted.WhileSubscribed(5000),
emptySet()
)
init {
refreshAll()
}
fun toggleTopicSelection(topic: TopicSelection) {
viewModelScope.launch {
interestsRepository.toggleTopicSelection(topic)
}
}
fun togglePersonSelected(person: String) {
viewModelScope.launch {
interestsRepository.togglePersonSelected(person)
}
}
fun togglePublicationSelected(publication: String) {
viewModelScope.launch {
interestsRepository.togglePublicationSelected(publication)
}
}
/**
* Refresh topics, people, and publications
*/
private fun refreshAll() {
_uiState.update { it.copy(loading = true) }
viewModelScope.launch {
// Trigger repository requests in parallel
val topicsDeferred = async { interestsRepository.getTopics() }
val peopleDeferred = async { interestsRepository.getPeople() }
val publicationsDeferred = async { interestsRepository.getPublications() }
// Wait for all requests to finish
val topics = topicsDeferred.await().successOr(emptyList())
val people = peopleDeferred.await().successOr(emptyList())
val publications = publicationsDeferred.await().successOr(emptyList())
_uiState.update {
it.copy(
loading = false,
topics = topics,
people = people,
publications = publications
)
}
}
}
/**
* Factory for InterestsViewModel that takes PostsRepository as a dependency
*/
companion object {
fun provideFactory(
interestsRepository: InterestsRepository,
): ViewModelProvider.Factory = object : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return InterestsViewModel(interestsRepository) as T
}
}
}
}
| apache-2.0 | 42952ccb7d49a45828fdbef0d52c85b0 | 31.890511 | 86 | 0.671771 | 5.13797 | false | false | false | false |
mglukhikh/intellij-community | plugins/devkit/src/inspections/UElementAsPsiInspection.kt | 1 | 6386 | /*
* 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 org.jetbrains.idea.devkit.inspections
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.psi.*
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.TypeConversionUtil.isAssignable
import com.intellij.psi.util.TypeConversionUtil.isNullType
import com.intellij.util.SmartList
import org.jetbrains.idea.devkit.DevKitBundle
import org.jetbrains.uast.*
import org.jetbrains.uast.visitor.AbstractUastVisitor
class UElementAsPsiInspection : DevKitUastInspectionBase() {
override fun checkMethod(method: UMethod, manager: InspectionManager, isOnTheFly: Boolean): Array<ProblemDescriptor>? {
val sourcePsiElement = method.sourcePsiElement ?: return null
val uElementType = psiClassType(UElement::class.java.name, sourcePsiElement.resolveScope) ?: return null
val psiElementType = psiClassType(PsiElement::class.java.name, sourcePsiElement.resolveScope) ?: return null
val visitor = CodeVisitor(uElementType, psiElementType)
method.accept(visitor)
return visitor.reportedElements.map {
manager.createProblemDescriptor(
it,
DevKitBundle.message("inspections.usage.uelement.as.psi"),
emptyArray<LocalQuickFix>(), ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
isOnTheFly,
false)
}.toTypedArray()
}
private class CodeVisitor(private val uElementType: PsiClassType, private val psiElementType: PsiClassType) : AbstractUastVisitor() {
val reportedElements = SmartList<PsiElement>()
override fun visitCallExpression(node: UCallExpression): Boolean {
checkReceiver(node)
checkArguments(node)
return false;
}
private fun checkArguments(node: UCallExpression) {
for (valueArgument in node.valueArguments) {
if (!isUElementType(valueArgument.getExpressionType())) continue
val parameter = guessCorrespondingParameter(node, valueArgument) ?: continue
if (isPsiElementType(parameter.type)) {
valueArgument.sourcePsiElement?.let { reportedElements.add(it) }
}
}
}
/**
* A workaround for IDEA-184046
* tries to find parameter in declaration that corresponds to an argument:
* considers simple positional calls and Kotlin extension calls.
*/
private fun guessCorrespondingParameter(callExpression: UCallExpression, arg: UExpression): PsiParameter? {
val psiMethod = callExpression.resolve() ?: return null
val parameters = psiMethod.parameterList.parameters
if (callExpression is UCallExpressionEx)
return parameters.withIndex().find { (i, _) -> callExpression.getArgumentForParameter(i) == arg }?.value
// not everyone implements UCallExpressionEx, lets try to guess
val indexInArguments = callExpression.valueArguments.indexOf(arg)
if (parameters.size == callExpression.valueArguments.count()) {
return parameters.getOrNull(indexInArguments)
}
// probably it is a kotlin extension method
if (parameters.size - 1 == callExpression.valueArguments.count()) {
val parameter = parameters.firstOrNull() ?: return null
val receiverType = callExpression.receiverType ?: return null
if (!parameter.type.isAssignableFrom(receiverType)) return null
if (!parameters.drop(1).zip(callExpression.valueArguments)
.all { (param, arg) -> arg.getExpressionType()?.let { param.type.isAssignableFrom(it) } == true }) return null
return parameters.getOrNull(indexInArguments + 1)
}
//named parameters are not processed
return null
}
private fun checkReceiver(node: UCallExpression) {
if (!isUElementType(node.receiverType)) return
val psiMethod = node.resolve() ?: return
val containingClass = psiMethod.containingClass ?: return
if (containingClass.qualifiedName in ALLOWED_REDEFINITION) return
if (!isPsiElementClass(containingClass) && psiMethod.findSuperMethods().none { isPsiElementClass(it.containingClass) }) return
if (psiMethod.findSuperMethods().any { it.containingClass?.qualifiedName in ALLOWED_REDEFINITION }) return
node.sourcePsiElement?.let {
reportedElements.add(it)
}
}
override fun visitBinaryExpression(node: UBinaryExpression): Boolean {
if (node.operator != UastBinaryOperator.ASSIGN) return false
if (isUElementType(node.rightOperand.getExpressionType()) && isPsiElementType(node.leftOperand.getExpressionType())) {
node.rightOperand.sourcePsiElement?.let { reportedElements.add(it) }
}
return false;
}
override fun visitBinaryExpressionWithType(node: UBinaryExpressionWithType): Boolean {
if (isUElementType(node.operand.getExpressionType()) && isPsiElementType(node.typeReference?.type)) {
node.operand.sourcePsiElement?.let { reportedElements.add(it) }
}
return false
}
override fun visitVariable(node: UVariable): Boolean {
if (isUElementType(node.uastInitializer?.getExpressionType()) && isPsiElementType(node.type)) {
node.uastInitializer.sourcePsiElement?.let { reportedElements.add(it) }
}
return false
}
private fun isPsiElementType(type: PsiType?) =
type?.let { !isNullType(type) && isAssignable(psiElementType, it) && !isUElementType(it) } ?: false
private fun isPsiElementClass(cls: PsiClass?): Boolean {
if (cls == null) return false
return isPsiElementType(PsiType.getTypeByName(cls.qualifiedName, cls.project, cls.resolveScope))
}
private fun isUElementType(type: PsiType?) =
type?.let { !isNullType(type) && isAssignable(uElementType, it) } ?: false
}
private fun psiClassType(fqn: String, searchScope: GlobalSearchScope): PsiClassType? =
PsiType.getTypeByName(fqn, searchScope.project, searchScope).takeIf { it.resolve() != null }
private companion object {
val ALLOWED_REDEFINITION = setOf(
UClass::class.java.name,
UMethod::class.java.name,
UVariable::class.java.name,
UClassInitializer::class.java.name
)
}
} | apache-2.0 | 48a2e6e247a564396a667816b51c98e9 | 42.746575 | 140 | 0.727216 | 4.84522 | false | false | false | false |
cout970/Modeler | src/main/kotlin/com/cout970/modeler/core/model/TRTSTransformation.kt | 1 | 2980 | package com.cout970.modeler.core.model
import com.cout970.matrix.api.IMatrix4
import com.cout970.modeler.api.model.ITransformation
import com.cout970.modeler.util.*
import com.cout970.vector.api.IQuaternion
import com.cout970.vector.api.IVector3
import com.cout970.vector.extensions.Vector3
import com.cout970.vector.extensions.interpolate
import com.cout970.vector.extensions.plus
import com.cout970.vector.extensions.times
import org.joml.Matrix4d
/**
* Created by cout970 on 2017/05/14.
*/
data class TRTSTransformation(
val translation: IVector3 = Vector3.ORIGIN,
val rotation: IVector3 = Vector3.ORIGIN,
val pivot: IVector3 = Vector3.ORIGIN,
val scale: IVector3 = Vector3.ONE
) : ITransformation {
companion object {
val IDENTITY = TRTSTransformation(Vector3.ORIGIN, Vector3.ORIGIN, Vector3.ORIGIN, Vector3.ONE)
}
val quatRotation: IQuaternion get() = quatOfAngles(rotation)
// Gson pls
private constructor() : this(Vector3.ORIGIN, Vector3.ORIGIN, Vector3.ORIGIN, Vector3.ONE)
override val matrix: IMatrix4 by lazy {
Matrix4d().apply {
translate(translation.xd, translation.yd, translation.zd)
translate(pivot.xd, pivot.yd, pivot.zd)
rotate(quatOfAngles(rotation).toJOML())
translate(-pivot.xd, -pivot.yd, -pivot.zd)
scale(scale.xd, scale.yd, scale.zd)
}.toIMatrix()
}
fun merge(other: TRTSTransformation): TRTSTransformation {
return TRTSTransformation(
translation = quatOfAngles(other.rotation).transform(this.translation) + other.translation,
rotation = (quatOfAngles(other.rotation) * quatOfAngles(this.rotation)).toAxisRotations(),
pivot = other.pivot + this.pivot,
scale = this.scale * other.scale
)
}
fun lerp(other: TRTSTransformation, step: Float): TRTSTransformation {
return TRTSTransformation(
translation = this.translation.interpolate(other.translation, step.toDouble()),
rotation = quatOfAngles(this.rotation).lerp(quatOfAngles(other.rotation), step.toDouble()).toAxisRotations(),
pivot = this.pivot.interpolate(other.pivot, step.toDouble()),
scale = this.scale.interpolate(other.scale, step.toDouble())
)
}
fun toTRS(): TRSTransformation {
val base = TRSTransformation.fromRotationPivot(pivot, rotation)
return TRSTransformation(
translation = translation + base.translation,
rotation = base.rotation,
scale = scale
)
}
override fun plus(other: ITransformation): ITransformation {
return when (other) {
is TRSTransformation -> this.merge(other.toTRTS())
is TRTSTransformation -> this.merge(other)
else -> error("Unknown ITransformation type: $other, ${other::class.java.name}")
}
}
} | gpl-3.0 | 6ad8d7b63f0ac2baf940c6dbd548b57c | 36.2625 | 125 | 0.662752 | 4.03794 | false | false | false | false |
cout970/Modeler | src/main/kotlin/com/cout970/modeler/render/tool/camera/CameraHandler.kt | 1 | 3173 | package com.cout970.modeler.render.tool.camera
import com.cout970.glutilities.structure.Timer
import com.cout970.modeler.util.toRads
import com.cout970.vector.api.IVector2
import com.cout970.vector.api.IVector3
import com.cout970.vector.extensions.plus
import com.cout970.vector.extensions.vec2Of
import kotlin.math.*
/**
* Created by cout970 on 2017/03/26.
*/
class CameraHandler {
var camera = Camera.DEFAULT
var desiredZoom = camera.zoom
var newRotation: IVector2 = vec2Of(camera.angleX, camera.angleY)
var desiredRotation: IVector2 = vec2Of(camera.angleX, camera.angleY)
var lockPos = false
var lockRot = false
var lockScale = false
fun updateAnimation(timer: Timer) {
if (!lockScale) {
if (abs(desiredZoom - camera.zoom) > 0.001) {
camera = camera.copy(
zoom = camera.zoom + (desiredZoom - camera.zoom) * min(1.0, timer.delta * 5)
)
}
}
if (lockRot) return
if (abs(desiredRotation.xd - camera.angleX) > 0.0001 ||
abs(desiredRotation.yd - camera.angleY) > 0.0001) {
camera = camera.copy(
angleX = camera.angleX + (desiredRotation.xd - camera.angleX) * min(1.0, timer.delta * 10),
angleY = camera.angleY + (desiredRotation.yd - camera.angleY) * min(1.0, timer.delta * 10)
)
newRotation = vec2Of(camera.angleX, camera.angleY)
} else {
val distX = distance(camera.angleX, newRotation.xd)
val distY = distance(camera.angleY, newRotation.yd)
if (distX.absoluteValue > 0.00001 || distY.absoluteValue > 0.00001) {
val delta = min(1.0, timer.delta * 5)
val moveX = -distX * delta
val moveY = -distY * delta
camera = camera.copy(
angleX = normRad(camera.angleX + moveX),
angleY = normRad(camera.angleY + moveY)
)
desiredRotation = vec2Of(camera.angleX, camera.angleY)
}
}
}
private fun normRad(angle: Double): Double {
val res = angle % 360.toRads()
return if (res < (-180).toRads()) res + 360.toRads() else if (res > 180.toRads()) res - 360.toRads() else res
}
fun distance(src: Double, dst: Double): Double = atan2(sin(src - dst), cos(src - dst))
fun setPosition(pos: IVector3) {
if (lockPos) return
camera = camera.copy(position = pos)
}
fun translate(move: IVector3) {
if (lockPos) return
camera = camera.copy(position = camera.position + move)
}
fun setRotation(angleX: Double, angleY: Double) {
if (lockRot) return
newRotation = vec2Of(normRad(angleX), normRad(angleY))
}
fun rotate(angleX: Double, angleY: Double) {
if (lockRot) return
desiredRotation = vec2Of(camera.angleX + angleX, camera.angleY + angleY)
}
fun setZoom(zoom: Double) {
if (lockScale) return
desiredZoom = zoom
}
fun setOrtho(option: Boolean) {
camera = camera.copy(perspective = !option)
}
} | gpl-3.0 | e1303c91be121295acb00f300903aded | 31.060606 | 117 | 0.593445 | 3.676709 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinCallableDefinitionUsage.kt | 2 | 10944 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.changeSignature.usages
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.usageView.UsageInfo
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaMethodDescriptor
import org.jetbrains.kotlin.idea.codeInsight.shorten.addToShorteningWaitSet
import org.jetbrains.kotlin.idea.core.ShortenReferences.Options
import org.jetbrains.kotlin.idea.core.setVisibility
import org.jetbrains.kotlin.idea.core.toKeywordToken
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinChangeInfo
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinParameterInfo
import org.jetbrains.kotlin.idea.refactoring.changeSignature.getCallableSubstitutor
import org.jetbrains.kotlin.idea.refactoring.changeSignature.setValOrVar
import org.jetbrains.kotlin.idea.refactoring.dropOperatorKeywordIfNecessary
import org.jetbrains.kotlin.idea.refactoring.dropOverrideKeywordIfNecessary
import org.jetbrains.kotlin.idea.refactoring.replaceListPsiAndKeepDelimiters
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext
import org.jetbrains.kotlin.psi.psiUtil.getValueParameterList
import org.jetbrains.kotlin.psi.typeRefHelpers.setReceiverTypeReference
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeSubstitutor
import org.jetbrains.kotlin.types.substitutions.getTypeSubstitutor
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.utils.sure
class KotlinCallableDefinitionUsage<T : PsiElement>(
function: T,
val originalCallableDescriptor: CallableDescriptor,
baseFunction: KotlinCallableDefinitionUsage<PsiElement>?,
private val samCallType: KotlinType?,
private val canDropOverride: Boolean = true
) : KotlinUsageInfo<T>(function) {
val baseFunction: KotlinCallableDefinitionUsage<*> = baseFunction ?: this
val hasExpectedType: Boolean = checkIfHasExpectedType(originalCallableDescriptor, isInherited)
val currentCallableDescriptor: CallableDescriptor? by lazy {
when (val element = declaration) {
is KtFunction, is KtProperty, is KtParameter -> (element as KtDeclaration).unsafeResolveToDescriptor() as CallableDescriptor
is KtClass -> (element.unsafeResolveToDescriptor() as ClassDescriptor).unsubstitutedPrimaryConstructor
is PsiMethod -> element.getJavaMethodDescriptor()
else -> null
}
}
val typeSubstitutor: TypeSubstitutor? by lazy {
if (!isInherited) return@lazy null
if (samCallType == null) {
getCallableSubstitutor(this.baseFunction, this)
} else {
val currentBaseDescriptor = this.baseFunction.currentCallableDescriptor
val classDescriptor = currentBaseDescriptor?.containingDeclaration as? ClassDescriptor ?: return@lazy null
getTypeSubstitutor(classDescriptor.defaultType, samCallType)
}
}
private fun checkIfHasExpectedType(callableDescriptor: CallableDescriptor, isInherited: Boolean): Boolean {
if (!(callableDescriptor is AnonymousFunctionDescriptor && isInherited)) return false
val functionLiteral = DescriptorToSourceUtils.descriptorToDeclaration(callableDescriptor) as KtFunctionLiteral?
assert(functionLiteral != null) { "No declaration found for $callableDescriptor" }
val parent = functionLiteral!!.parent as? KtLambdaExpression ?: return false
return parent.analyze(BodyResolveMode.PARTIAL)[BindingContext.EXPECTED_EXPRESSION_TYPE, parent] != null
}
val declaration: PsiElement
get() = element!!
val isInherited: Boolean
get() = baseFunction !== this
override fun processUsage(changeInfo: KotlinChangeInfo, element: T, allUsages: Array<out UsageInfo>): Boolean {
if (element !is KtNamedDeclaration) return true
val psiFactory = KtPsiFactory(element.project)
if (changeInfo.isNameChanged) {
val identifier = (element as KtCallableDeclaration).nameIdentifier
identifier?.replace(psiFactory.createIdentifier(changeInfo.newName))
}
changeReturnTypeIfNeeded(changeInfo, element)
val parameterList = element.getValueParameterList()
if (changeInfo.isParameterSetOrOrderChanged) {
processParameterListWithStructuralChanges(changeInfo, element, parameterList, psiFactory)
} else if (parameterList != null) {
val offset = if (originalCallableDescriptor.extensionReceiverParameter != null) 1 else 0
for ((paramIndex, parameter) in parameterList.parameters.withIndex()) {
val parameterInfo = changeInfo.newParameters[paramIndex + offset]
changeParameter(paramIndex, parameter, parameterInfo)
}
parameterList.addToShorteningWaitSet(Options.DEFAULT)
}
if (element is KtCallableDeclaration && changeInfo.isReceiverTypeChanged()) {
val receiverTypeText = changeInfo.renderReceiverType(this)
val receiverTypeRef = if (receiverTypeText != null) psiFactory.createType(receiverTypeText) else null
val newReceiverTypeRef = element.setReceiverTypeReference(receiverTypeRef)
newReceiverTypeRef?.addToShorteningWaitSet(Options.DEFAULT)
}
if (changeInfo.isVisibilityChanged() && !KtPsiUtil.isLocal(element as KtDeclaration)) {
changeVisibility(changeInfo, element)
}
if (canDropOverride) {
dropOverrideKeywordIfNecessary(element)
}
dropOperatorKeywordIfNecessary(element)
return true
}
private fun changeReturnTypeIfNeeded(changeInfo: KotlinChangeInfo, element: PsiElement) {
if (element !is KtCallableDeclaration) return
if (element is KtConstructor<*>) return
val returnTypeIsNeeded = (element is KtFunction && element !is KtFunctionLiteral) || element is KtProperty || element is KtParameter
if (changeInfo.isReturnTypeChanged && returnTypeIsNeeded) {
element.typeReference = null
val returnTypeText = changeInfo.renderReturnType(this)
val returnType = changeInfo.newReturnTypeInfo.type
if (returnType == null || !returnType.isUnit()) {
element.setTypeReference(KtPsiFactory(element).createType(returnTypeText))!!.addToShorteningWaitSet(Options.DEFAULT)
}
}
}
private fun processParameterListWithStructuralChanges(
changeInfo: KotlinChangeInfo,
element: PsiElement,
originalParameterList: KtParameterList?,
psiFactory: KtPsiFactory
) {
var parameterList = originalParameterList
val parametersCount = changeInfo.getNonReceiverParametersCount()
val isLambda = element is KtFunctionLiteral
var canReplaceEntireList = false
var newParameterList: KtParameterList? = null
if (isLambda) {
if (parametersCount == 0) {
if (parameterList != null) {
parameterList.delete()
val arrow = (element as KtFunctionLiteral).arrow
arrow?.delete()
parameterList = null
}
} else {
newParameterList = psiFactory.createLambdaParameterList(changeInfo.getNewParametersSignatureWithoutParentheses(this))
canReplaceEntireList = true
}
} else if (!(element is KtProperty || element is KtParameter)) {
newParameterList = psiFactory.createParameterList(changeInfo.getNewParametersSignature(this))
}
if (newParameterList == null) return
if (parameterList != null) {
newParameterList = if (canReplaceEntireList) {
parameterList.replace(newParameterList) as KtParameterList
} else {
replaceListPsiAndKeepDelimiters(changeInfo, parameterList, newParameterList) { parameters }
}
} else {
if (element is KtClass) {
val constructor = element.createPrimaryConstructorIfAbsent()
val oldParameterList = constructor.valueParameterList.sure { "primary constructor from factory has parameter list" }
newParameterList = oldParameterList.replace(newParameterList) as KtParameterList
} else if (isLambda) {
val functionLiteral = element as KtFunctionLiteral
val anchor = functionLiteral.lBrace
newParameterList = element.addAfter(newParameterList, anchor) as KtParameterList
if (functionLiteral.arrow == null) {
val whitespaceAndArrow = psiFactory.createWhitespaceAndArrow()
element.addRangeAfter(whitespaceAndArrow.first, whitespaceAndArrow.second, newParameterList)
}
}
}
newParameterList.addToShorteningWaitSet(Options.DEFAULT)
}
private fun changeVisibility(changeInfo: KotlinChangeInfo, element: PsiElement) {
val newVisibilityToken = changeInfo.newVisibility.toKeywordToken()
when (element) {
is KtCallableDeclaration -> element.setVisibility(newVisibilityToken)
is KtClass -> element.createPrimaryConstructorIfAbsent().setVisibility(newVisibilityToken)
else -> throw AssertionError("Invalid element: " + element.getElementTextWithContext())
}
}
private fun changeParameter(parameterIndex: Int, parameter: KtParameter, parameterInfo: KotlinParameterInfo) {
parameter.setValOrVar(parameterInfo.valOrVar)
val psiFactory = KtPsiFactory(project)
if (parameterInfo.isTypeChanged && parameter.typeReference != null) {
val renderedType = parameterInfo.renderType(parameterIndex, this)
parameter.typeReference = psiFactory.createType(renderedType)
}
val inheritedName = parameterInfo.getInheritedName(this)
if (Name.isValidIdentifier(inheritedName)) {
val newIdentifier = psiFactory.createIdentifier(inheritedName)
parameter.nameIdentifier?.replace(newIdentifier)
}
}
}
| apache-2.0 | f21c191c26f06abd612897384f539e28 | 46.582609 | 158 | 0.719664 | 5.812002 | false | false | false | false |
Zhouzhouzhou/AndroidDemo | app/src/main/java/com/zhou/android/common/KtUtil.kt | 1 | 607 | package com.zhou.android.common
import android.app.Activity
import android.text.Editable
import android.widget.Toast
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
/**
* Created by mxz on 2019/10/31.
*/
fun Disposable.addToComposite(composite: CompositeDisposable) = composite.add(this)
fun Activity.toast(text: CharSequence, duration: Int = Toast.LENGTH_LONG) = Toast.makeText(this, text, duration).show()
fun String.text() = Editable.Factory.getInstance().newEditable(this)!!
fun String.editable() = Editable.Factory.getInstance().newEditable(this)!! | mit | dbfb5892b521788014fdbe2aa667a74a | 32.777778 | 119 | 0.792422 | 3.916129 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/jps/jps-plugin/src/org/jetbrains/kotlin/jps/build/KotlinCompileContext.kt | 1 | 12475 | // 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.jps.build
import org.jetbrains.jps.ModuleChunk
import org.jetbrains.jps.incremental.CompileContext
import org.jetbrains.jps.incremental.FSOperations
import org.jetbrains.jps.incremental.GlobalContextKey
import org.jetbrains.jps.incremental.fs.CompilationRound
import org.jetbrains.jps.incremental.messages.BuildMessage
import org.jetbrains.jps.incremental.messages.CompilerMessage
import org.jetbrains.kotlin.config.CompilerRunnerConstants.KOTLIN_COMPILER_NAME
import org.jetbrains.kotlin.incremental.LookupSymbol
import org.jetbrains.kotlin.incremental.storage.FileToPathConverter
import org.jetbrains.kotlin.jps.incremental.*
import org.jetbrains.kotlin.jps.targets.KotlinTargetsIndex
import org.jetbrains.kotlin.jps.targets.KotlinTargetsIndexBuilder
import org.jetbrains.kotlin.jps.targets.KotlinUnsupportedModuleBuildTarget
import java.io.File
import java.util.concurrent.atomic.AtomicBoolean
/**
* KotlinCompileContext is shared between all threads (i.e. it is [GlobalContextKey]).
*
* It is initialized lazily, and only before building of first chunk with kotlin code,
* and will be disposed on build finish.
*/
/*internal */val CompileContext.kotlin: KotlinCompileContext
get() {
val userData = getUserData(kotlinCompileContextKey)
if (userData != null) return userData
// here is error (KotlinCompilation available only at build phase)
// let's also check for concurrent initialization
val errorMessage = "KotlinCompileContext available only at build phase " +
"(between first KotlinBuilder.chunkBuildStarted and KotlinBuilder.buildFinished)"
synchronized(kotlinCompileContextKey) {
val newUsedData = getUserData(kotlinCompileContextKey)
if (newUsedData != null) {
error("Concurrent CompileContext.kotlin getter call and KotlinCompileContext initialization detected: $errorMessage")
}
}
error(errorMessage)
}
internal val kotlinCompileContextKey = GlobalContextKey<KotlinCompileContext>("kotlin")
class KotlinCompileContext(val jpsContext: CompileContext) {
val dataManager = jpsContext.projectDescriptor.dataManager
val dataPaths = dataManager.dataPaths
val testingLogger: TestingBuildLogger?
get() = jpsContext.testingContext?.buildLogger
val targetsIndex: KotlinTargetsIndex = KotlinTargetsIndexBuilder(this).build()
val targetsBinding
get() = targetsIndex.byJpsTarget
val lookupsCacheAttributesManager: CompositeLookupsCacheAttributesManager = makeLookupsCacheAttributesManager()
val shouldCheckCacheVersions = System.getProperty(KotlinBuilder.SKIP_CACHE_VERSION_CHECK_PROPERTY) == null
val hasKotlinMarker = HasKotlinMarker(dataManager)
val isInstrumentationEnabled: Boolean by lazy {
val value = System.getProperty("kotlin.jps.instrument.bytecode")?.toBoolean() ?: false
if (value) {
val message = "Experimental bytecode instrumentation for Kotlin classes is enabled"
jpsContext.processMessage(CompilerMessage(KOTLIN_COMPILER_NAME, BuildMessage.Kind.INFO, message))
}
value
}
val fileToPathConverter: FileToPathConverter =
JpsFileToPathConverter(jpsContext.projectDescriptor.project)
val lookupStorageManager = JpsLookupStorageManager(dataManager, fileToPathConverter)
/**
* Flag to prevent rebuilding twice.
*
* TODO: looks like it is not required since cache version checking are refactored
*/
val rebuildAfterCacheVersionChanged = RebuildAfterCacheVersionChangeMarker(dataManager)
var rebuildingAllKotlin = false
/**
* Note, [loadLookupsCacheStateDiff] should be initialized last as it requires initialized
* [targetsIndex], [hasKotlinMarker] and [rebuildAfterCacheVersionChanged] (see [markChunkForRebuildBeforeBuild])
*/
private val initialLookupsCacheStateDiff: CacheAttributesDiff<*> = loadLookupsCacheStateDiff()
private fun makeLookupsCacheAttributesManager(): CompositeLookupsCacheAttributesManager {
val expectedLookupsCacheComponents = mutableSetOf<String>()
targetsIndex.chunks.forEach { chunk ->
chunk.targets.forEach { target ->
if (target.isIncrementalCompilationEnabled) {
expectedLookupsCacheComponents.add(target.globalLookupCacheId)
}
}
}
val lookupsCacheRootPath = dataPaths.getTargetDataRoot(KotlinDataContainerTarget)
return CompositeLookupsCacheAttributesManager(lookupsCacheRootPath.toPath(), expectedLookupsCacheComponents)
}
private fun loadLookupsCacheStateDiff(): CacheAttributesDiff<CompositeLookupsCacheAttributes> {
val diff = lookupsCacheAttributesManager.loadDiff()
if (diff.status == CacheStatus.VALID) {
// try to perform a lookup
// request rebuild if storage is corrupted
try {
lookupStorageManager.withLookupStorage {
it.get(LookupSymbol("<#NAME#>", "<#SCOPE#>"))
}
} catch (e: Exception) {
// replace to jpsReportInternalBuilderError when IDEA-201297 will be implemented
jpsContext.processMessage(
CompilerMessage(
"Kotlin", BuildMessage.Kind.WARNING,
"Incremental caches are corrupted. All Kotlin code will be rebuilt."
)
)
KotlinBuilder.LOG.info(Error("Lookup storage is corrupted, probe failed: ${e.message}", e))
markAllKotlinForRebuild("Lookup storage is corrupted")
return diff.copy(actual = null)
}
}
return diff
}
fun hasKotlin() = targetsIndex.chunks.any { chunk ->
chunk.targets.any { target ->
hasKotlinMarker[target] == true
}
}
fun checkCacheVersions() {
when (initialLookupsCacheStateDiff.status) {
CacheStatus.INVALID -> {
// global cache needs to be rebuilt
testingLogger?.invalidOrUnusedCache(null, null, initialLookupsCacheStateDiff)
if (initialLookupsCacheStateDiff.actual != null) {
markAllKotlinForRebuild("Kotlin incremental cache settings or format was changed")
clearLookupCache()
} else {
markAllKotlinForRebuild("Kotlin incremental cache is missed or corrupted")
}
}
CacheStatus.VALID -> Unit
CacheStatus.SHOULD_BE_CLEARED -> {
jpsContext.testingContext?.buildLogger?.invalidOrUnusedCache(null, null, initialLookupsCacheStateDiff)
KotlinBuilder.LOG.info("Removing global cache as it is not required anymore: $initialLookupsCacheStateDiff")
clearAllCaches()
}
CacheStatus.CLEARED -> Unit
}
}
private val lookupAttributesSaved = AtomicBoolean(false)
/**
* Called on every successful compilation
*/
fun ensureLookupsCacheAttributesSaved() {
if (lookupAttributesSaved.compareAndSet(false, true)) {
initialLookupsCacheStateDiff.manager.writeVersion()
}
}
fun checkChunkCacheVersion(chunk: KotlinChunk) {
if (shouldCheckCacheVersions && !rebuildingAllKotlin) {
if (chunk.shouldRebuild()) markChunkForRebuildBeforeBuild(chunk)
}
}
private fun logMarkDirtyForTestingBeforeRound(file: File, shouldProcess: Boolean): Boolean {
if (shouldProcess) {
testingLogger?.markedAsDirtyBeforeRound(listOf(file))
}
return shouldProcess
}
private fun markAllKotlinForRebuild(reason: String) {
if (rebuildingAllKotlin) return
rebuildingAllKotlin = true
KotlinBuilder.LOG.info("Rebuilding all Kotlin: $reason")
targetsIndex.chunks.forEach {
markChunkForRebuildBeforeBuild(it)
}
lookupStorageManager.cleanLookupStorage(KotlinBuilder.LOG)
}
private fun markChunkForRebuildBeforeBuild(chunk: KotlinChunk) {
chunk.targets.forEach {
FSOperations.markDirty(jpsContext, CompilationRound.NEXT, it.jpsModuleBuildTarget) { file ->
logMarkDirtyForTestingBeforeRound(file, file.isKotlinSourceFile)
}
dataManager.getKotlinCache(it)?.clean()
hasKotlinMarker.clean(it)
rebuildAfterCacheVersionChanged[it] = true
}
}
private fun clearAllCaches() {
clearLookupCache()
KotlinBuilder.LOG.info("Clearing caches for all targets")
targetsIndex.chunks.forEach { chunk ->
chunk.targets.forEach {
dataManager.getKotlinCache(it)?.clean()
}
}
}
private fun clearLookupCache() {
KotlinBuilder.LOG.info("Clearing lookup cache")
lookupStorageManager.cleanLookupStorage(KotlinBuilder.LOG)
initialLookupsCacheStateDiff.manager.writeVersion()
}
fun cleanupCaches() {
// todo: remove lookups for targets with disabled IC (or split global lookups cache into several caches for each compiler)
targetsIndex.chunks.forEach { chunk ->
chunk.targets.forEach { target ->
if (target.initialLocalCacheAttributesDiff.status == CacheStatus.SHOULD_BE_CLEARED) {
KotlinBuilder.LOG.info(
"$target caches is cleared as not required anymore: ${target.initialLocalCacheAttributesDiff}"
)
testingLogger?.invalidOrUnusedCache(null, target, target.initialLocalCacheAttributesDiff)
target.initialLocalCacheAttributesDiff.manager.writeVersion(null)
dataManager.getKotlinCache(target)?.clean()
}
}
}
}
fun dispose() {
}
fun getChunk(rawChunk: ModuleChunk): KotlinChunk? {
val rawRepresentativeTarget = rawChunk.representativeTarget()
if (rawRepresentativeTarget !in targetsBinding) return null
return targetsIndex.chunksByJpsRepresentativeTarget[rawRepresentativeTarget]
?: error("Kotlin binding for chunk $this is not loaded at build start")
}
fun reportUnsupportedTargets() {
// group all KotlinUnsupportedModuleBuildTarget by kind
// only representativeTarget will be added
val byKind = mutableMapOf<String?, MutableList<KotlinUnsupportedModuleBuildTarget>>()
targetsIndex.chunks.forEach {
val target = it.representativeTarget
if (target is KotlinUnsupportedModuleBuildTarget) {
if (target.sourceFiles.isNotEmpty()) {
byKind.getOrPut(target.kind) { mutableListOf() }.add(target)
}
}
}
byKind.forEach { (kind, targets) ->
targets.sortBy { it.module.name }
val chunkNames = targets.map { it.chunk.presentableShortName }
val presentableChunksListString = chunkNames.joinToReadableString()
val msg =
if (kind == null) {
"$presentableChunksListString is not yet supported in IDEA internal build system. " +
"Please use Gradle to build them (enable 'Delegate IDE build/run actions to Gradle' in Settings)."
} else {
"$kind is not yet supported in IDEA internal build system. " +
"Please use Gradle to build $presentableChunksListString (enable 'Delegate IDE build/run actions to Gradle' in Settings)."
}
testingLogger?.addCustomMessage(msg)
jpsContext.processMessage(
CompilerMessage(
KOTLIN_COMPILER_NAME,
BuildMessage.Kind.WARNING,
msg
)
)
}
}
}
fun List<String>.joinToReadableString(): String = when {
size > 5 -> take(5).joinToString() + " and ${size - 5} more"
size > 1 -> dropLast(1).joinToString() + " and ${last()}"
size == 1 -> single()
else -> ""
} | apache-2.0 | 724b8a679d133ee99e471404de72889f | 39.245161 | 158 | 0.662766 | 5.030242 | false | false | false | false |
feelfreelinux/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/api/links/LinksRepository.kt | 1 | 12237 | package io.github.feelfreelinux.wykopmobilny.api.links
import io.github.feelfreelinux.wykopmobilny.api.UserTokenRefresher
import io.github.feelfreelinux.wykopmobilny.api.WykopImageFile
import io.github.feelfreelinux.wykopmobilny.api.errorhandler.ErrorHandlerTransformer
import io.github.feelfreelinux.wykopmobilny.api.filters.OWMContentFilter
import io.github.feelfreelinux.wykopmobilny.api.patrons.PatronsApi
import io.github.feelfreelinux.wykopmobilny.models.dataclass.Downvoter
import io.github.feelfreelinux.wykopmobilny.models.dataclass.Link
import io.github.feelfreelinux.wykopmobilny.models.dataclass.LinkComment
import io.github.feelfreelinux.wykopmobilny.models.dataclass.LinkVoteResponsePublishModel
import io.github.feelfreelinux.wykopmobilny.models.dataclass.Related
import io.github.feelfreelinux.wykopmobilny.models.dataclass.Upvoter
import io.github.feelfreelinux.wykopmobilny.models.mapper.apiv2.DownvoterMapper
import io.github.feelfreelinux.wykopmobilny.models.mapper.apiv2.LinkCommentMapper
import io.github.feelfreelinux.wykopmobilny.models.mapper.apiv2.LinkMapper
import io.github.feelfreelinux.wykopmobilny.models.mapper.apiv2.RelatedMapper
import io.github.feelfreelinux.wykopmobilny.models.mapper.apiv2.UpvoterMapper
import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models.DigResponse
import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models.DownvoterResponse
import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models.LinkCommentResponse
import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models.LinkResponse
import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models.LinkVoteResponse
import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models.RelatedResponse
import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models.UpvoterResponse
import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models.VoteResponse
import io.reactivex.Single
import io.reactivex.subjects.PublishSubject
import retrofit2.Retrofit
import toRequestBody
class LinksRepository(
val retrofit: Retrofit,
val userTokenRefresher: UserTokenRefresher,
val owmContentFilter: OWMContentFilter,
val patronsApi: PatronsApi
) : LinksApi {
private val linksApi by lazy { retrofit.create(LinksRetrofitApi::class.java) }
override val voteRemoveSubject = PublishSubject.create<LinkVoteResponsePublishModel>()
override val digSubject = PublishSubject.create<LinkVoteResponsePublishModel>()
override val burySubject = PublishSubject.create<LinkVoteResponsePublishModel>()
override fun getPromoted(page: Int): Single<List<Link>> =
linksApi.getPromoted(page)
.retryWhen(userTokenRefresher)
.flatMap { patronsApi.ensurePatrons(it) }
.compose<List<LinkResponse>>(ErrorHandlerTransformer())
.map { it.map { response -> LinkMapper.map(response, owmContentFilter) } }
override fun getUpcoming(page: Int, sortBy: String): Single<List<Link>> =
linksApi.getUpcoming(page, sortBy)
.retryWhen(userTokenRefresher)
.flatMap { patronsApi.ensurePatrons(it) }
.compose<List<LinkResponse>>(ErrorHandlerTransformer())
.map { it.map { response -> LinkMapper.map(response, owmContentFilter) } }
override fun getObserved(page: Int): Single<List<Link>> =
linksApi.getObserved(page)
.retryWhen(userTokenRefresher)
.flatMap { patronsApi.ensurePatrons(it) }
.compose<List<LinkResponse>>(ErrorHandlerTransformer())
.map { it.map { response -> LinkMapper.map(response, owmContentFilter) } }
override fun getLinkComments(linkId: Int, sortBy: String) =
linksApi.getLinkComments(linkId, sortBy)
.retryWhen(userTokenRefresher)
.flatMap { patronsApi.ensurePatrons(it) }
.compose<List<LinkCommentResponse>>(ErrorHandlerTransformer())
.map { it.map { response -> LinkCommentMapper.map(response, owmContentFilter) } }
.map { list ->
list.forEach { comment ->
if (comment.id == comment.parentId) {
comment.childCommentCount = list.filter { item -> comment.id == item.parentId }.size - 1
}
}
list
}
override fun getLink(linkId: Int): Single<Link> =
linksApi.getLink(linkId)
.retryWhen(userTokenRefresher)
.flatMap { patronsApi.ensurePatrons(it) }
.compose<LinkResponse>(ErrorHandlerTransformer())
.map { LinkMapper.map(it, owmContentFilter) }
override fun commentVoteUp(linkId: Int): Single<LinkVoteResponse> =
linksApi.commentVoteUp(linkId)
.flatMap { patronsApi.ensurePatrons(it) }
.retryWhen(userTokenRefresher)
.compose<LinkVoteResponse>(ErrorHandlerTransformer())
override fun commentVoteDown(linkId: Int): Single<LinkVoteResponse> =
linksApi.commentVoteDown(linkId)
.flatMap { patronsApi.ensurePatrons(it) }
.retryWhen(userTokenRefresher)
.compose<LinkVoteResponse>(ErrorHandlerTransformer())
override fun relatedVoteUp(relatedId: Int): Single<VoteResponse> =
linksApi.relatedVoteUp(relatedId)
.retryWhen(userTokenRefresher)
.compose<VoteResponse>(ErrorHandlerTransformer())
override fun relatedVoteDown(relatedId: Int): Single<VoteResponse> =
linksApi.relatedVoteDown(relatedId)
.flatMap { patronsApi.ensurePatrons(it) }
.retryWhen(userTokenRefresher)
.compose<VoteResponse>(ErrorHandlerTransformer())
override fun commentVoteCancel(linkId: Int): Single<LinkVoteResponse> =
linksApi.commentVoteCancel(linkId)
.flatMap { patronsApi.ensurePatrons(it) }
.retryWhen(userTokenRefresher)
.compose<LinkVoteResponse>(ErrorHandlerTransformer())
override fun voteUp(linkId: Int, notifyPublisher: Boolean): Single<DigResponse> =
linksApi.voteUp(linkId)
.flatMap { patronsApi.ensurePatrons(it) }
.retryWhen(userTokenRefresher)
.compose<DigResponse>(ErrorHandlerTransformer())
.doOnSuccess {
if (notifyPublisher) {
digSubject.onNext(LinkVoteResponsePublishModel(linkId, it))
}
}
override fun voteDown(
linkId: Int,
reason: Int,
notifyPublisher: Boolean
): Single<DigResponse> =
linksApi.voteDown(linkId, reason)
.retryWhen(userTokenRefresher)
.flatMap { patronsApi.ensurePatrons(it) }
.compose<DigResponse>(ErrorHandlerTransformer())
.doOnSuccess {
if (notifyPublisher) {
burySubject.onNext(LinkVoteResponsePublishModel(linkId, it))
}
}
override fun voteRemove(linkId: Int, notifyPublisher: Boolean): Single<DigResponse> =
linksApi.voteRemove(linkId)
.retryWhen(userTokenRefresher)
.flatMap { patronsApi.ensurePatrons(it) }
.compose<DigResponse>(ErrorHandlerTransformer())
.doOnSuccess {
if (notifyPublisher) {
voteRemoveSubject.onNext(LinkVoteResponsePublishModel(linkId, it))
}
}
override fun commentAdd(
body: String,
embed: String?,
plus18: Boolean,
linkId: Int
): Single<LinkComment> =
linksApi.addComment(body, linkId, embed, plus18)
.retryWhen(userTokenRefresher)
.compose<LinkCommentResponse>(ErrorHandlerTransformer())
.map { LinkCommentMapper.map(it, owmContentFilter) }
override fun relatedAdd(
title: String,
url: String,
plus18: Boolean,
linkId: Int
): Single<Related> =
linksApi.addRelated(title, linkId, url, plus18)
.retryWhen(userTokenRefresher)
.compose<RelatedResponse>(ErrorHandlerTransformer())
.map { RelatedMapper.map(it) }
override fun commentAdd(
body: String,
plus18: Boolean,
inputStream: WykopImageFile,
linkId: Int
): Single<LinkComment> =
linksApi.addComment(body.toRequestBody(), plus18.toRequestBody(), linkId, inputStream.getFileMultipart())
.retryWhen(userTokenRefresher)
.compose<LinkCommentResponse>(ErrorHandlerTransformer())
.map { LinkCommentMapper.map(it, owmContentFilter) }
override fun commentAdd(
body: String,
embed: String?,
plus18: Boolean,
linkId: Int,
linkComment: Int
): Single<LinkComment> =
linksApi.addComment(body, linkId, linkComment, embed, plus18)
.retryWhen(userTokenRefresher)
.compose<LinkCommentResponse>(ErrorHandlerTransformer())
.map { LinkCommentMapper.map(it, owmContentFilter) }
override fun commentAdd(
body: String,
plus18: Boolean,
inputStream: WykopImageFile,
linkId: Int,
linkComment: Int
): Single<LinkComment> =
linksApi.addComment(body.toRequestBody(), plus18.toRequestBody(), linkId, linkComment, inputStream.getFileMultipart())
.retryWhen(userTokenRefresher)
.compose<LinkCommentResponse>(ErrorHandlerTransformer())
.map { LinkCommentMapper.map(it, owmContentFilter) }
override fun commentEdit(body: String, linkId: Int): Single<LinkComment> {
return linksApi.editComment(body, linkId)
.retryWhen(userTokenRefresher)
.compose<LinkCommentResponse>(ErrorHandlerTransformer())
.map { LinkCommentMapper.map(it, owmContentFilter) }
}
override fun commentDelete(commentId: Int): Single<LinkComment> =
linksApi.deleteComment(commentId)
.retryWhen(userTokenRefresher)
.compose<LinkCommentResponse>(ErrorHandlerTransformer())
.map { LinkCommentMapper.map(it, owmContentFilter) }
override fun getDownvoters(linkId: Int): Single<List<Downvoter>> =
linksApi.getDownvoters(linkId)
.retryWhen(userTokenRefresher)
.compose<List<DownvoterResponse>>(ErrorHandlerTransformer())
.map { it.map { response -> DownvoterMapper.map(response) } }
override fun getUpvoters(linkId: Int): Single<List<Upvoter>> =
linksApi.getUpvoters(linkId)
.retryWhen(userTokenRefresher)
.compose<List<UpvoterResponse>>(ErrorHandlerTransformer())
.map { it.map { response -> UpvoterMapper.map(response) } }
override fun getRelated(linkId: Int): Single<List<Related>> =
linksApi.getRelated(linkId)
.retryWhen(userTokenRefresher)
.compose<List<RelatedResponse>>(ErrorHandlerTransformer())
.map { it.map { response -> RelatedMapper.map(response) } }
override fun markFavorite(linkId: Int): Single<Boolean> =
linksApi.markFavorite(linkId)
.retryWhen(userTokenRefresher)
.compose<List<Boolean>>(ErrorHandlerTransformer())
.map { it.first() }
}
| mit | 96f987b4a1ca46e626cde254f18f2a72 | 47.948 | 130 | 0.628422 | 5.08815 | false | false | false | false |
siosio/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/changes/GHPRDiffRequestChainProducer.kt | 1 | 6818 | // 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.ui.changes
import com.intellij.diff.chains.AsyncDiffRequestChain
import com.intellij.diff.chains.DiffRequestChain
import com.intellij.diff.chains.DiffRequestProducer
import com.intellij.diff.comparison.ComparisonManagerImpl
import com.intellij.diff.comparison.ComparisonUtil
import com.intellij.diff.comparison.iterables.DiffIterableUtil
import com.intellij.diff.tools.util.text.LineOffsetsUtil
import com.intellij.diff.util.DiffUserDataKeys
import com.intellij.diff.util.DiffUserDataKeysEx
import com.intellij.icons.AllIcons
import com.intellij.ide.actions.NonEmptyActionGroup
import com.intellij.openapi.ListSelection
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.diff.impl.GenericDataProvider
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.util.ProgressIndicatorUtils
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.actions.diff.ChangeDiffRequestProducer
import com.intellij.openapi.vcs.history.VcsDiffUtil
import org.jetbrains.plugins.github.api.data.GHUser
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.pullrequest.action.GHPRActionKeys
import org.jetbrains.plugins.github.pullrequest.comment.GHPRDiffReviewSupport
import org.jetbrains.plugins.github.pullrequest.comment.GHPRDiffReviewSupportImpl
import org.jetbrains.plugins.github.pullrequest.comment.action.GHPRDiffReviewResolvedThreadsToggleAction
import org.jetbrains.plugins.github.pullrequest.comment.action.GHPRDiffReviewThreadsReloadAction
import org.jetbrains.plugins.github.pullrequest.comment.action.GHPRDiffReviewThreadsToggleAction
import org.jetbrains.plugins.github.pullrequest.data.GHPRChangesProvider
import org.jetbrains.plugins.github.pullrequest.data.provider.GHPRDataProvider
import org.jetbrains.plugins.github.ui.avatars.GHAvatarIconsProvider
import org.jetbrains.plugins.github.util.DiffRequestChainProducer
import org.jetbrains.plugins.github.util.GHToolbarLabelAction
import java.util.concurrent.CompletableFuture
class GHPRDiffRequestChainProducer(private val project: Project,
private val dataProvider: GHPRDataProvider,
private val avatarIconsProvider: GHAvatarIconsProvider,
private val currentUser: GHUser)
: DiffRequestChainProducer {
override fun getRequestChain(changes: ListSelection<Change>): DiffRequestChain {
val changesData = dataProvider.changesData
val changesProviderFuture = changesData.loadChanges()
//TODO: check if revisions are already fetched or load via API (could be much quicker in some cases)
val fetchFuture = CompletableFuture.allOf(changesData.fetchBaseBranch(), changesData.fetchHeadBranch())
return object : AsyncDiffRequestChain() {
override fun loadRequestProducers(): ListSelection<out DiffRequestProducer> {
return changes.map { change ->
val changeDataKeys = loadRequestDataKeys(ProgressManager.getInstance().progressIndicator, change,
changesProviderFuture, fetchFuture)
ChangeDiffRequestProducer.create(project, change, changeDataKeys)
}
}
}
}
private fun loadRequestDataKeys(indicator: ProgressIndicator,
change: Change,
changesProviderFuture: CompletableFuture<GHPRChangesProvider>,
fetchFuture: CompletableFuture<Void>): Map<Key<out Any>, Any?> {
val changesProvider = ProgressIndicatorUtils.awaitWithCheckCanceled(changesProviderFuture, indicator)
ProgressIndicatorUtils.awaitWithCheckCanceled(fetchFuture, indicator)
val requestDataKeys = mutableMapOf<Key<out Any>, Any?>()
VcsDiffUtil.putFilePathsIntoChangeContext(change, requestDataKeys)
val diffComputer = getDiffComputer(changesProvider, change)
if (diffComputer != null) {
requestDataKeys[DiffUserDataKeysEx.CUSTOM_DIFF_COMPUTER] = diffComputer
}
val reviewSupport = getReviewSupport(changesProvider, change)
if (reviewSupport != null) {
requestDataKeys[GHPRDiffReviewSupport.KEY] = reviewSupport
requestDataKeys[DiffUserDataKeys.DATA_PROVIDER] = GenericDataProvider().apply {
putData(GHPRActionKeys.PULL_REQUEST_DATA_PROVIDER, dataProvider)
putData(GHPRDiffReviewSupport.DATA_KEY, reviewSupport)
}
val viewOptionsGroup = NonEmptyActionGroup().apply {
isPopup = true
templatePresentation.text = GithubBundle.message("pull.request.diff.view.options")
templatePresentation.icon = AllIcons.Actions.Show
add(GHPRDiffReviewThreadsToggleAction())
add(GHPRDiffReviewResolvedThreadsToggleAction())
}
requestDataKeys[DiffUserDataKeys.CONTEXT_ACTIONS] = listOf(
GHToolbarLabelAction(GithubBundle.message("pull.request.diff.review.label")),
viewOptionsGroup,
GHPRDiffReviewThreadsReloadAction(),
ActionManager.getInstance().getAction("Github.PullRequest.Review.Submit"))
}
return requestDataKeys
}
private fun getReviewSupport(changesProvider: GHPRChangesProvider, change: Change): GHPRDiffReviewSupport? {
val diffData = changesProvider.findChangeDiffData(change) ?: return null
return GHPRDiffReviewSupportImpl(project, dataProvider.reviewData, diffData, avatarIconsProvider, currentUser)
}
private fun getDiffComputer(changesProvider: GHPRChangesProvider, change: Change): DiffUserDataKeysEx.DiffComputer? {
val diffRanges = changesProvider.findChangeDiffData(change)?.diffRangesWithoutContext ?: return null
return DiffUserDataKeysEx.DiffComputer { text1, text2, policy, innerChanges, indicator ->
val comparisonManager = ComparisonManagerImpl.getInstanceImpl()
val lineOffsets1 = LineOffsetsUtil.create(text1)
val lineOffsets2 = LineOffsetsUtil.create(text2)
if (!ComparisonUtil.isValidRanges(text1, text2, lineOffsets1, lineOffsets2, diffRanges)) {
error("Invalid diff line ranges for change $change")
}
val iterable = DiffIterableUtil.create(diffRanges, lineOffsets1.lineCount, lineOffsets2.lineCount)
DiffIterableUtil.iterateAll(iterable).map {
comparisonManager.compareLinesInner(it.first, text1, text2, lineOffsets1, lineOffsets2, policy, innerChanges,
indicator)
}.flatten()
}
}
}
| apache-2.0 | 55aa33fe7d888bace1f4bbcdd423ca97 | 51.852713 | 140 | 0.769727 | 4.976642 | false | false | false | false |
jwren/intellij-community | java/java-tests/testSrc/com/intellij/util/indexing/MultiProjectIndexTest.kt | 1 | 5784 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.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 | af25063cab5c1838ec1ccb5e32b69ac4 | 39.173611 | 137 | 0.760373 | 4.744873 | false | true | false | false |
androidx/androidx | compose/compiler/compiler-hosted/integration-tests/src/test/java/androidx/compose/compiler/plugins/kotlin/AbstractLoweringTests.kt | 3 | 4254 | /*
* 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.compiler.plugins.kotlin
import androidx.compose.runtime.Composer
import androidx.compose.runtime.snapshots.Snapshot
import org.intellij.lang.annotations.Language
import org.robolectric.RuntimeEnvironment
import java.net.URLClassLoader
abstract class AbstractLoweringTests : AbstractCodegenTest() {
fun codegen(text: String, dumpClasses: Boolean = false) {
codegenNoImports(
"""
import android.content.Context
import android.widget.*
import androidx.compose.runtime.*
$COMPOSE_VIEW_STUBS_IMPORTS
$text
$COMPOSE_VIEW_STUBS
""",
dumpClasses
)
}
protected fun execute(block: () -> Unit) {
val scheduler = RuntimeEnvironment.getMasterScheduler()
scheduler.pause()
block()
Snapshot.sendApplyNotifications()
scheduler.advanceToLastPostedRunnable()
}
fun codegenNoImports(text: String, dumpClasses: Boolean = false) {
val className = "Test_${uniqueNumber++}"
val fileName = "$className.kt"
classLoader(text, fileName, dumpClasses)
}
fun compose(
@Language("kotlin")
supportingCode: String,
@Language("kotlin")
composeCode: String,
valuesFactory: () -> Map<String, Any> = { emptyMap() },
dumpClasses: Boolean = false
): RobolectricComposeTester {
val className = "TestFCS_${uniqueNumber++}"
val fileName = "$className.kt"
val candidateValues = valuesFactory()
@Suppress("NO_REFLECTION_IN_CLASS_PATH")
val parameterList = candidateValues.map {
if (it.key.contains(':')) {
it.key
} else "${it.key}: ${it.value::class.qualifiedName}"
}.joinToString()
val parameterTypes = candidateValues.map {
it.value::class.javaPrimitiveType ?: it.value::class.javaObjectType
}.toTypedArray()
val compiledClasses = classLoader(
"""
import android.widget.*
import androidx.compose.runtime.*
$COMPOSE_VIEW_STUBS_IMPORTS
$supportingCode
class $className {
@Composable
fun test($parameterList) {
$composeCode
}
}
$COMPOSE_VIEW_STUBS
""",
fileName, dumpClasses
)
val allClassFiles = compiledClasses.allGeneratedFiles.filter {
it.relativePath.endsWith(".class")
}
val loader = URLClassLoader(emptyArray(), this.javaClass.classLoader)
val instanceClass = run {
var instanceClass: Class<*>? = null
var loadedOne = false
for (outFile in allClassFiles) {
val bytes = outFile.asByteArray()
val loadedClass = loadClass(loader, null, bytes)
if (loadedClass.name == className) instanceClass = loadedClass
loadedOne = true
}
if (!loadedOne) error("No classes loaded")
instanceClass ?: error("Could not find class $className in loaded classes")
}
val instanceOfClass = instanceClass.getDeclaredConstructor().newInstance()
val testMethod = instanceClass.getMethod(
"test",
*parameterTypes,
Composer::class.java,
Int::class.java
)
return compose { composer, _ ->
val values = valuesFactory()
val arguments = values.map { it.value }.toTypedArray()
testMethod.invoke(instanceOfClass, *arguments, composer, 1)
}
}
} | apache-2.0 | 85c5e0319e30189f85b9e8a5a46ab309 | 30.058394 | 87 | 0.614951 | 5.010601 | false | true | false | false |
androidx/androidx | compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/Text.kt | 3 | 14954 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material3
import androidx.compose.foundation.text.BasicText
import androidx.compose.foundation.text.InlineTextContent
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.structuralEqualityPolicy
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.takeOrElse
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.Paragraph
import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.TextUnit
/**
* High level element that displays text and provides semantics / accessibility information.
*
* The default [style] uses the [LocalTextStyle] provided by the [MaterialTheme] / components. If
* you are setting your own style, you may want to consider first retrieving [LocalTextStyle],
* and using [TextStyle.copy] to keep any theme defined attributes, only modifying the specific
* attributes you want to override.
*
* For ease of use, commonly used parameters from [TextStyle] are also present here. The order of
* precedence is as follows:
* - If a parameter is explicitly set here (i.e, it is _not_ `null` or [TextUnit.Unspecified]),
* then this parameter will always be used.
* - If a parameter is _not_ set, (`null` or [TextUnit.Unspecified]), then the corresponding value
* from [style] will be used instead.
*
* Additionally, for [color], if [color] is not set, and [style] does not have a color, then
* [LocalContentColor] will be used.
*
* @param text the text to be displayed
* @param modifier the [Modifier] to be applied to this layout node
* @param color [Color] to apply to the text. If [Color.Unspecified], and [style] has no color set,
* this will be [LocalContentColor].
* @param fontSize the size of glyphs to use when painting the text. See [TextStyle.fontSize].
* @param fontStyle the typeface variant to use when drawing the letters (e.g., italic).
* See [TextStyle.fontStyle].
* @param fontWeight the typeface thickness to use when painting the text (e.g., [FontWeight.Bold]).
* @param fontFamily the font family to be used when rendering the text. See [TextStyle.fontFamily].
* @param letterSpacing the amount of space to add between each letter.
* See [TextStyle.letterSpacing].
* @param textDecoration the decorations to paint on the text (e.g., an underline).
* See [TextStyle.textDecoration].
* @param textAlign the alignment of the text within the lines of the paragraph.
* See [TextStyle.textAlign].
* @param lineHeight line height for the [Paragraph] in [TextUnit] unit, e.g. SP or EM.
* See [TextStyle.lineHeight].
* @param overflow how visual overflow should be handled.
* @param softWrap whether the text should break at soft line breaks. If false, the glyphs in the
* text will be positioned as if there was unlimited horizontal space. If [softWrap] is false,
* [overflow] and TextAlign may have unexpected effects.
* @param maxLines An optional maximum number of lines for the text to span, wrapping if
* necessary. If the text exceeds the given number of lines, it will be truncated according to
* [overflow] and [softWrap]. It is required that 1 <= [minLines] <= [maxLines].
* @param minLines The minimum height in terms of minimum number of visible lines. It is required
* that 1 <= [minLines] <= [maxLines].
* @param onTextLayout callback that is executed when a new text layout is calculated. A
* [TextLayoutResult] object that callback provides contains paragraph information, size of the
* text, baselines and other details. The callback can be used to add additional decoration or
* functionality to the text. For example, to draw selection around the text.
* @param style style configuration for the text such as color, font, line height etc.
*/
@Composable
fun Text(
text: String,
modifier: Modifier = Modifier,
color: Color = Color.Unspecified,
fontSize: TextUnit = TextUnit.Unspecified,
fontStyle: FontStyle? = null,
fontWeight: FontWeight? = null,
fontFamily: FontFamily? = null,
letterSpacing: TextUnit = TextUnit.Unspecified,
textDecoration: TextDecoration? = null,
textAlign: TextAlign? = null,
lineHeight: TextUnit = TextUnit.Unspecified,
overflow: TextOverflow = TextOverflow.Clip,
softWrap: Boolean = true,
maxLines: Int = Int.MAX_VALUE,
minLines: Int = 1,
onTextLayout: (TextLayoutResult) -> Unit = {},
style: TextStyle = LocalTextStyle.current
) {
val textColor = color.takeOrElse {
style.color.takeOrElse {
LocalContentColor.current
}
}
// NOTE(text-perf-review): It might be worthwhile writing a bespoke merge implementation that
// will avoid reallocating if all of the options here are the defaults
val mergedStyle = style.merge(
TextStyle(
color = textColor,
fontSize = fontSize,
fontWeight = fontWeight,
textAlign = textAlign,
lineHeight = lineHeight,
fontFamily = fontFamily,
textDecoration = textDecoration,
fontStyle = fontStyle,
letterSpacing = letterSpacing
)
)
BasicText(
text,
modifier,
mergedStyle,
onTextLayout,
overflow,
softWrap,
maxLines,
minLines
)
}
@Deprecated(
"Maintained for binary compatibility. Use version with minLines instead",
level = DeprecationLevel.HIDDEN
)
@Composable
fun Text(
text: String,
modifier: Modifier = Modifier,
color: Color = Color.Unspecified,
fontSize: TextUnit = TextUnit.Unspecified,
fontStyle: FontStyle? = null,
fontWeight: FontWeight? = null,
fontFamily: FontFamily? = null,
letterSpacing: TextUnit = TextUnit.Unspecified,
textDecoration: TextDecoration? = null,
textAlign: TextAlign? = null,
lineHeight: TextUnit = TextUnit.Unspecified,
overflow: TextOverflow = TextOverflow.Clip,
softWrap: Boolean = true,
maxLines: Int = Int.MAX_VALUE,
onTextLayout: (TextLayoutResult) -> Unit = {},
style: TextStyle = LocalTextStyle.current
) {
Text(
text,
modifier,
color,
fontSize,
fontStyle,
fontWeight,
fontFamily,
letterSpacing,
textDecoration,
textAlign,
lineHeight,
overflow,
softWrap,
maxLines,
1,
onTextLayout,
style
)
}
/**
* High level element that displays text and provides semantics / accessibility information.
*
* The default [style] uses the [LocalTextStyle] provided by the [MaterialTheme] / components. If
* you are setting your own style, you may want to consider first retrieving [LocalTextStyle],
* and using [TextStyle.copy] to keep any theme defined attributes, only modifying the specific
* attributes you want to override.
*
* For ease of use, commonly used parameters from [TextStyle] are also present here. The order of
* precedence is as follows:
* - If a parameter is explicitly set here (i.e, it is _not_ `null` or [TextUnit.Unspecified]),
* then this parameter will always be used.
* - If a parameter is _not_ set, (`null` or [TextUnit.Unspecified]), then the corresponding value
* from [style] will be used instead.
*
* Additionally, for [color], if [color] is not set, and [style] does not have a color, then
* [LocalContentColor] will be used.
*
* @param text the text to be displayed
* @param modifier the [Modifier] to be applied to this layout node
* @param color [Color] to apply to the text. If [Color.Unspecified], and [style] has no color set,
* this will be [LocalContentColor].
* @param fontSize the size of glyphs to use when painting the text. See [TextStyle.fontSize].
* @param fontStyle the typeface variant to use when drawing the letters (e.g., italic).
* See [TextStyle.fontStyle].
* @param fontWeight the typeface thickness to use when painting the text (e.g., [FontWeight.Bold]).
* @param fontFamily the font family to be used when rendering the text. See [TextStyle.fontFamily].
* @param letterSpacing the amount of space to add between each letter.
* See [TextStyle.letterSpacing].
* @param textDecoration the decorations to paint on the text (e.g., an underline).
* See [TextStyle.textDecoration].
* @param textAlign the alignment of the text within the lines of the paragraph.
* See [TextStyle.textAlign].
* @param lineHeight line height for the [Paragraph] in [TextUnit] unit, e.g. SP or EM.
* See [TextStyle.lineHeight].
* @param overflow how visual overflow should be handled.
* @param softWrap whether the text should break at soft line breaks. If false, the glyphs in the
* text will be positioned as if there was unlimited horizontal space. If [softWrap] is false,
* [overflow] and TextAlign may have unexpected effects.
* @param maxLines An optional maximum number of lines for the text to span, wrapping if
* necessary. If the text exceeds the given number of lines, it will be truncated according to
* [overflow] and [softWrap]. It is required that 1 <= [minLines] <= [maxLines].
* @param minLines The minimum height in terms of minimum number of visible lines. It is required
* that 1 <= [minLines] <= [maxLines].
* @param inlineContent a map storing composables that replaces certain ranges of the text, used to
* insert composables into text layout. See [InlineTextContent].
* @param onTextLayout callback that is executed when a new text layout is calculated. A
* [TextLayoutResult] object that callback provides contains paragraph information, size of the
* text, baselines and other details. The callback can be used to add additional decoration or
* functionality to the text. For example, to draw selection around the text.
* @param style style configuration for the text such as color, font, line height etc.
*/
@Composable
fun Text(
text: AnnotatedString,
modifier: Modifier = Modifier,
color: Color = Color.Unspecified,
fontSize: TextUnit = TextUnit.Unspecified,
fontStyle: FontStyle? = null,
fontWeight: FontWeight? = null,
fontFamily: FontFamily? = null,
letterSpacing: TextUnit = TextUnit.Unspecified,
textDecoration: TextDecoration? = null,
textAlign: TextAlign? = null,
lineHeight: TextUnit = TextUnit.Unspecified,
overflow: TextOverflow = TextOverflow.Clip,
softWrap: Boolean = true,
maxLines: Int = Int.MAX_VALUE,
minLines: Int = 1,
inlineContent: Map<String, InlineTextContent> = mapOf(),
onTextLayout: (TextLayoutResult) -> Unit = {},
style: TextStyle = LocalTextStyle.current
) {
val textColor = color.takeOrElse {
style.color.takeOrElse {
LocalContentColor.current
}
}
// NOTE(text-perf-review): It might be worthwhile writing a bespoke merge implementation that
// will avoid reallocating if all of the options here are the defaults
val mergedStyle = style.merge(
TextStyle(
color = textColor,
fontSize = fontSize,
fontWeight = fontWeight,
textAlign = textAlign,
lineHeight = lineHeight,
fontFamily = fontFamily,
textDecoration = textDecoration,
fontStyle = fontStyle,
letterSpacing = letterSpacing
)
)
BasicText(
text = text,
modifier = modifier,
style = mergedStyle,
onTextLayout = onTextLayout,
overflow = overflow,
softWrap = softWrap,
maxLines = maxLines,
minLines = minLines,
inlineContent = inlineContent
)
}
@Deprecated(
"Maintained for binary compatibility. Use version with minLines instead",
level = DeprecationLevel.HIDDEN
)
@Composable
fun Text(
text: AnnotatedString,
modifier: Modifier = Modifier,
color: Color = Color.Unspecified,
fontSize: TextUnit = TextUnit.Unspecified,
fontStyle: FontStyle? = null,
fontWeight: FontWeight? = null,
fontFamily: FontFamily? = null,
letterSpacing: TextUnit = TextUnit.Unspecified,
textDecoration: TextDecoration? = null,
textAlign: TextAlign? = null,
lineHeight: TextUnit = TextUnit.Unspecified,
overflow: TextOverflow = TextOverflow.Clip,
softWrap: Boolean = true,
maxLines: Int = Int.MAX_VALUE,
inlineContent: Map<String, InlineTextContent> = mapOf(),
onTextLayout: (TextLayoutResult) -> Unit = {},
style: TextStyle = LocalTextStyle.current
) {
Text(
text,
modifier,
color,
fontSize,
fontStyle,
fontWeight,
fontFamily,
letterSpacing,
textDecoration,
textAlign,
lineHeight,
overflow,
softWrap,
maxLines,
1,
inlineContent,
onTextLayout,
style
)
}
/**
* CompositionLocal containing the preferred [TextStyle] that will be used by [Text] components by
* default. To set the value for this CompositionLocal, see [ProvideTextStyle] which will merge any
* missing [TextStyle] properties with the existing [TextStyle] set in this CompositionLocal.
*
* @see ProvideTextStyle
*/
val LocalTextStyle = compositionLocalOf(structuralEqualityPolicy()) { TextStyle.Default }
// TODO(b/156598010): remove this and replace with fold definition on the backing CompositionLocal
/**
* This function is used to set the current value of [LocalTextStyle], merging the given style
* with the current style values for any missing attributes. Any [Text] components included in
* this component's [content] will be styled with this style unless styled explicitly.
*
* @see LocalTextStyle
*/
@Composable
fun ProvideTextStyle(value: TextStyle, content: @Composable () -> Unit) {
val mergedStyle = LocalTextStyle.current.merge(value)
CompositionLocalProvider(LocalTextStyle provides mergedStyle, content = content)
}
| apache-2.0 | 88401837125747a1713614f0bd995b36 | 40.538889 | 100 | 0.71098 | 4.602647 | false | false | false | false |
djkovrik/YapTalker | app/src/main/java/com/sedsoftware/yaptalker/presentation/extensions/ContextExt.kt | 1 | 853 | package com.sedsoftware.yaptalker.presentation.extensions
import android.content.Context
import androidx.annotation.AttrRes
import androidx.annotation.ColorRes
import androidx.annotation.PluralsRes
import androidx.annotation.StringRes
import androidx.core.content.ContextCompat
import android.util.TypedValue
val Context.currentDensity: Int
get() = resources.displayMetrics.density.toInt()
fun Context.color(@ColorRes colorId: Int) =
ContextCompat.getColor(this, colorId)
fun Context.string(@StringRes resId: Int): String =
resources.getString(resId)
fun Context.quantityString(@PluralsRes resId: Int, value: Int): String =
resources.getQuantityString(resId, value)
fun Context.colorFromAttr(@AttrRes res: Int): Int {
val typedValue = TypedValue()
theme.resolveAttribute(res, typedValue, true)
return typedValue.data
}
| apache-2.0 | ac64dde3547cbd4453c3882c7c894a4a | 30.592593 | 72 | 0.794842 | 4.374359 | false | false | false | false |
androidx/androidx | graphics/graphics-core/src/androidTest/java/androidx/graphics/opengl/egl/EGLTestActivity.kt | 3 | 4365 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.graphics.opengl.egl
import android.animation.ValueAnimator
import android.app.Activity
import android.opengl.EGL14
import android.opengl.EGLConfig
import android.opengl.EGLSurface
import android.opengl.GLES20
import android.os.Bundle
import android.view.Surface
import android.view.SurfaceView
import android.view.TextureView
import android.widget.LinearLayout
import androidx.graphics.opengl.GLRenderer
import androidx.graphics.opengl.GLRenderer.RenderTarget
import java.util.concurrent.atomic.AtomicInteger
const val TAG: String = "EGLTestActivity"
@Suppress("AcronymName")
class EGLTestActivity : Activity() {
private val mGLRenderer = GLRenderer()
private val mParam = AtomicInteger()
private val mRenderer1 = object : GLRenderer.RenderCallback {
override fun onSurfaceCreated(
spec: EGLSpec,
config: EGLConfig,
surface: Surface,
width: Int,
height: Int
): EGLSurface {
val attrs = EGLConfigAttributes {
EGL14.EGL_RENDER_BUFFER to EGL14.EGL_SINGLE_BUFFER
}
return spec.eglCreateWindowSurface(config, surface, attrs)
}
override fun onDrawFrame(eglManager: EGLManager) {
val red = mParam.toFloat() / 100f
GLES20.glClearColor(red, 0.0f, 0.0f, 1.0f)
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT)
}
}
private val mRenderer2 = object : GLRenderer.RenderCallback {
override fun onDrawFrame(eglManager: EGLManager) {
val blue = mParam.toFloat() / 100f
GLES20.glClearColor(0.0f, 0.0f, blue, 1.0f)
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT)
}
}
private lateinit var mSurfaceView: SurfaceView
private lateinit var mTextureView: TextureView
private lateinit var mRenderTarget1: RenderTarget
private lateinit var mRenderTarget2: RenderTarget
private var mAnimator: ValueAnimator? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mGLRenderer.start()
val container = LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
weightSum = 2f
}
mSurfaceView = SurfaceView(this)
mTextureView = TextureView(this)
val params = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0).apply {
weight = 1f
}
mRenderTarget1 = mGLRenderer.attach(mSurfaceView, mRenderer1)
mRenderTarget2 = mGLRenderer.attach(mTextureView, mRenderer2)
container.addView(mSurfaceView, params)
container.addView(mTextureView, params)
setContentView(container)
mAnimator = ValueAnimator.ofFloat(0.0f, 1.0f).apply {
duration = 3000
repeatCount = ValueAnimator.INFINITE
repeatMode = ValueAnimator.REVERSE
addUpdateListener {
mParam.set(((it.animatedValue as Float) * 100).toInt())
mRenderTarget1.requestRender()
mRenderTarget2.requestRender()
}
start()
}
}
override fun onResume() {
super.onResume()
if (!mRenderTarget1.isAttached()) {
mRenderTarget1 = mGLRenderer.attach(mSurfaceView, mRenderer1)
}
if (!mRenderTarget2.isAttached()) {
mRenderTarget2 = mGLRenderer.attach(mTextureView, mRenderer2)
}
}
override fun onPause() {
super.onPause()
mRenderTarget1.detach(true)
mRenderTarget2.detach(true)
}
override fun onDestroy() {
super.onDestroy()
mAnimator?.cancel()
mGLRenderer.stop(true)
}
} | apache-2.0 | d6f423ddf9369e5cabe172bffdaf4e99 | 31.340741 | 97 | 0.664147 | 4.609293 | false | false | false | false |
GunoH/intellij-community | platform/warmup/src/com/intellij/warmup/ProjectIndexesWarmup.kt | 4 | 5389 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.warmup
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.EDT
import com.intellij.openapi.application.ModernApplicationStarter
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.vfs.newvfs.RefreshQueueImpl
import com.intellij.platform.util.ArgsParser
import com.intellij.util.SystemProperties
import com.intellij.warmup.util.*
import kotlinx.coroutines.*
import kotlinx.coroutines.future.asDeferred
import kotlin.math.max
import kotlin.system.exitProcess
internal class ProjectIndexesWarmup : ModernApplicationStarter() {
override val commandName: String
get() = "warmup"
override fun premain(args: List<String>) {
if (System.getProperty("caches.indexerThreadsCount") == null) {
System.setProperty("caches.indexerThreadsCount", max(1, Runtime.getRuntime().availableProcessors() - 1).toString())
}
//IDEA-241709
System.setProperty("ide.browser.jcef.enabled", false.toString())
//disable vcs log
System.setProperty("vcs.log.index.git", false.toString())
//disable slow edt access assertions
System.setProperty("ide.slow.operations.assertion", false.toString())
SystemProperties.setProperty("compile.parallel", true.toString())
// to avoid sync progress task execution as it works in test mode
SystemProperties.setProperty("intellij.progress.task.ignoreHeadless", true.toString())
}
override suspend fun start(args: List<String>) {
val commandArgs = try {
val parser = ArgsParser(args)
val commandArgs = OpenProjectArgsImpl(parser)
parser.tryReadAll()
commandArgs
}
catch (t: Throwable) {
val argsParser = ArgsParser(listOf())
runCatching { OpenProjectArgsImpl(argsParser) }
ConsoleLog.error(
"""Failed to parse commandline: ${t.message}
Usage:
options:
${argsParser.usage(includeHidden = true)}""")
exitProcess(2)
}
val buildMode = System.getenv()["IJ_WARMUP_BUILD"]
val builders = System.getenv()["IJ_WARMUP_BUILD_BUILDERS"]?.split(";")?.toHashSet()
val project = withLoggingProgresses {
waitIndexInitialization()
val project = try {
importOrOpenProject(commandArgs, it)
}
catch(t: Throwable) {
ConsoleLog.error("Failed to load project", t)
return@withLoggingProgresses null
}
waitForCachesSupports(project)
if (buildMode != null) {
val rebuild = buildMode == "REBUILD"
waitForBuilders(project, rebuild, builders)
}
project
} ?: return
waitUntilProgressTasksAreFinishedOrFail()
waitForRefreshQueue()
withLoggingProgresses {
withContext(Dispatchers.EDT) {
ProjectManager.getInstance().closeAndDispose(project)
}
}
ConsoleLog.info("IDE Warm-up finished. Exiting the application...")
withContext(Dispatchers.EDT) {
ApplicationManager.getApplication().exit(false, true, false)
}
}
}
private suspend fun waitForCachesSupports(project: Project) {
val projectIndexesWarmupSupports = ProjectIndexesWarmupSupport.EP_NAME.getExtensions(project)
ConsoleLog.info("Waiting for all ProjectIndexesWarmupSupport[${projectIndexesWarmupSupports.size}]...")
val futures = projectIndexesWarmupSupports.mapNotNull { support ->
try {
support.warmAdditionalIndexes().asDeferred()
}
catch (t: Throwable) {
ConsoleLog.error("Failed to warm additional indexes $support", t)
null
}
}
try {
withLoggingProgresses {
futures.awaitAll()
}
}
catch (t: Throwable) {
ConsoleLog.error("An exception occurred while awaiting indexes warmup", t)
}
ConsoleLog.info("All ProjectIndexesWarmupSupport.waitForCaches completed")
}
private suspend fun waitForBuilders(project: Project, rebuild: Boolean, builders: Set<String>?) {
fun isBuilderEnabled(id: String): Boolean = if (builders.isNullOrEmpty()) true else builders.contains(id)
val projectBuildWarmupSupports = ProjectBuildWarmupSupport.EP_NAME.getExtensions(project).filter { builder ->
isBuilderEnabled(builder.getBuilderId())
}
ConsoleLog.info("Starting additional project builders[${projectBuildWarmupSupports.size}] (rebuild=$rebuild)...")
try {
withLoggingProgresses {
coroutineScope {
for (builder in projectBuildWarmupSupports) {
launch {
try {
ConsoleLog.info("Starting builder $builder for id ${builder.getBuilderId()}")
builder.buildProject(rebuild)
}
catch (e: CancellationException) {
throw e
}
catch (e: Throwable) {
ConsoleLog.error("Failed to call builder $builder", e)
}
}
}
}
}
}
catch (e: CancellationException) {
throw e
}
catch (t: Throwable) {
ConsoleLog.error("An exception occurred while awaiting builders", t)
}
ConsoleLog.info("All warmup builders completed")
}
private suspend fun waitForRefreshQueue() {
runTaskAndLogTime("RefreshQueue") {
while (RefreshQueueImpl.isRefreshInProgress()) {
ConsoleLog.info("RefreshQueue is in progress... ")
delay(500)
}
}
} | apache-2.0 | 6473ef632784d85dcad4cb2fbf9bf6b0 | 32.067485 | 121 | 0.698831 | 4.517184 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinUnusedImportInspection.kt | 2 | 11736 | // 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.inspections
import com.intellij.codeInsight.actions.OptimizeImportsProcessor
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.codeInsight.daemon.QuickFixBundle
import com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerEx
import com.intellij.codeInsight.daemon.impl.DaemonListeners
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.codeInspection.*
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.command.undo.UndoManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.PsiEditorUtil
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.util.DocumentUtil
import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter
import org.jetbrains.kotlin.idea.base.projectStructure.matches
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.codeInsight.KotlinCodeInsightWorkspaceSettings
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.core.targetDescriptors
import org.jetbrains.kotlin.idea.imports.KotlinImportOptimizer
import org.jetbrains.kotlin.idea.imports.OptimizedImportsBuilder
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.references.KtInvokeFunctionReference
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.siblings
import org.jetbrains.kotlin.resolve.ImportPath
class KotlinUnusedImportInspection : AbstractKotlinInspection() {
class ImportData(val unusedImports: List<KtImportDirective>, val optimizerData: OptimizedImportsBuilder.InputData)
companion object {
fun analyzeImports(file: KtFile): ImportData? {
if (file is KtCodeFragment) return null
if (!RootKindFilter.projectSources.copy(includeScriptsOutsideSourceRoots = true).matches(file)) return null
if (file.importDirectives.isEmpty()) return null
val optimizerData = KotlinImportOptimizer.collectDescriptorsToImport(file)
val directives = file.importDirectives
val explicitlyImportedFqNames = directives
.asSequence()
.mapNotNull { it.importPath }
.filter { !it.isAllUnder && !it.hasAlias() }
.map { it.fqName }
.toSet()
val fqNames = optimizerData.namesToImport
val parentFqNames = HashSet<FqName>()
for ((_, fqName) in optimizerData.descriptorsToImport) {
// we don't add parents of explicitly imported fq-names because such imports are not needed
if (fqName in explicitlyImportedFqNames) continue
val parentFqName = fqName.parent()
if (!parentFqName.isRoot) {
parentFqNames.add(parentFqName)
}
}
val invokeFunctionCallFqNames = optimizerData.references.mapNotNull {
val reference = (it.element as? KtCallExpression)?.mainReference as? KtInvokeFunctionReference ?: return@mapNotNull null
(reference.resolve() as? KtNamedFunction)?.descriptor?.importableFqName
}
val importPaths = HashSet<ImportPath>(directives.size)
val unusedImports = ArrayList<KtImportDirective>()
val resolutionFacade = file.getResolutionFacade()
for (directive in directives) {
val importPath = directive.importPath ?: continue
val isUsed = when {
importPath.importedName in optimizerData.unresolvedNames -> true
!importPaths.add(importPath) -> false
importPath.isAllUnder -> optimizerData.unresolvedNames.isNotEmpty() || importPath.fqName in parentFqNames
importPath.fqName in fqNames -> importPath.importedName?.let { it in fqNames.getValue(importPath.fqName) } ?: false
importPath.fqName in invokeFunctionCallFqNames -> true
// case for type alias
else -> directive.targetDescriptors(resolutionFacade).firstOrNull()?.let { it.importableFqName in fqNames } ?: false
}
if (!isUsed) {
unusedImports += directive
}
}
return ImportData(unusedImports, optimizerData)
}
}
override fun checkFile(file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean): Array<out ProblemDescriptor>? {
if (file !is KtFile) return null
val data = analyzeImports(file) ?: return null
val problems = data.unusedImports.map {
val fixes = arrayListOf<LocalQuickFix>()
fixes.add(KotlinOptimizeImportsQuickFix(file))
if (!KotlinCodeInsightWorkspaceSettings.getInstance(file.project).optimizeImportsOnTheFly) {
fixes.add(EnableOptimizeImportsOnTheFlyFix(file))
}
manager.createProblemDescriptor(
it,
KotlinBundle.message("unused.import.directive"),
isOnTheFly,
fixes.toTypedArray(),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING
)
}
if (isOnTheFly && !isUnitTestMode()) {
scheduleOptimizeImportsOnTheFly(file, data.optimizerData)
}
return problems.toTypedArray()
}
private fun scheduleOptimizeImportsOnTheFly(file: KtFile, data: OptimizedImportsBuilder.InputData) {
if (!KotlinCodeInsightWorkspaceSettings.getInstance(file.project).optimizeImportsOnTheFly) return
val optimizedImports = KotlinImportOptimizer.prepareOptimizedImports(file, data) ?: return // return if already optimized
val project = file.project
val modificationCount = PsiModificationTracker.getInstance(project).modificationCount
scheduleOptimizeOnDaemonFinished(file) {
val editor = PsiEditorUtil.findEditor(file)
val currentModificationCount = PsiModificationTracker.getInstance(project).modificationCount
if (editor != null && currentModificationCount == modificationCount && timeToOptimizeImportsOnTheFly(file, editor, project)) {
optimizeImportsOnTheFly(file, optimizedImports, editor, project)
}
}
}
private fun scheduleOptimizeOnDaemonFinished(file: KtFile, action: () -> Unit) {
val daemonDisposable = Disposer.newDisposable()
// schedule optimise action after all applyInformation() calls
val myProject = file.project
myProject.getMessageBus().connect(daemonDisposable)
.subscribe<DaemonCodeAnalyzer.DaemonListener>(
DaemonCodeAnalyzer.DAEMON_EVENT_TOPIC,
object : DaemonCodeAnalyzer.DaemonListener {
override fun daemonFinished(incomingFileEditors: Collection<FileEditor?>) {
Disposer.dispose(daemonDisposable)
if ((DaemonCodeAnalyzer.getInstance(myProject) as DaemonCodeAnalyzerEx).isErrorAnalyzingFinished(file)) {
// later because should invoke when highlighting is finished (OptimizeImportsFix relies on that)
AppUIExecutor.onUiThread().later().expireWith(myProject).withDocumentsCommitted(myProject).execute {
if (file.isValid() && file.isWritable()) {
action.invoke()
}
}
} else {
scheduleOptimizeOnDaemonFinished(file, action)
}
}
})
}
private fun timeToOptimizeImportsOnTheFly(file: KtFile, editor: Editor, project: Project): Boolean {
if (project.isDisposed || !file.isValid || editor.isDisposed || !file.isWritable) return false
// do not optimize imports on the fly during undo/redo
val undoManager = UndoManager.getInstance(project)
if (undoManager.isUndoInProgress || undoManager.isRedoInProgress) return false
// if we stand inside import statements, do not optimize
val importList = file.importList ?: return false
val leftSpace = importList.siblings(forward = false, withItself = false).firstOrNull() as? PsiWhiteSpace
val rightSpace = importList.siblings(forward = true, withItself = false).firstOrNull() as? PsiWhiteSpace
val left = leftSpace ?: importList
val right = rightSpace ?: importList
val importsRange = TextRange(left.textRange.startOffset, right.textRange.endOffset)
if (importsRange.containsOffset(editor.caretModel.offset)) return false
val codeAnalyzer = DaemonCodeAnalyzerEx.getInstanceEx(project)
if (!codeAnalyzer.isHighlightingAvailable(file)) return false
if (!codeAnalyzer.isErrorAnalyzingFinished(file)) return false
val document = editor.document
var hasErrors = false
DaemonCodeAnalyzerEx.processHighlights(document, project, HighlightSeverity.ERROR, 0, document.textLength) { highlightInfo ->
if (!importsRange.containsRange(highlightInfo.startOffset, highlightInfo.endOffset)) {
hasErrors = true
false
} else {
true
}
}
if (hasErrors) return false
return DaemonListeners.canChangeFileSilently(file, true/* assume inspections are run on files in content only */)
}
private fun optimizeImportsOnTheFly(file: KtFile, optimizedImports: List<ImportPath>, editor: Editor, project: Project) {
val documentManager = PsiDocumentManager.getInstance(file.project)
val doc = documentManager.getDocument(file) ?: editor.document
documentManager.commitDocument(doc)
DocumentUtil.writeInRunUndoTransparentAction {
KotlinImportOptimizer.replaceImports(file, optimizedImports)
PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(doc)
}
}
private class EnableOptimizeImportsOnTheFlyFix(file: KtFile) : LocalQuickFixOnPsiElement(file), LowPriorityAction {
override fun getText(): String = QuickFixBundle.message("enable.optimize.imports.on.the.fly")
override fun getFamilyName() = name
override fun invoke(project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement) {
KotlinCodeInsightWorkspaceSettings.getInstance(project).optimizeImportsOnTheFly = true
OptimizeImportsProcessor(
project,
file
).run() // we optimize imports manually because on-the-fly import optimization won't work while the caret is in imports
}
}
}
| apache-2.0 | 1bc63e3e6b6e04ce1a505203f1640e63 | 49.805195 | 138 | 0.689162 | 5.554188 | false | false | false | false |
GunoH/intellij-community | platform/execution-impl/src/com/intellij/execution/runToolbar/RunToolbarExtraSlotPane.kt | 2 | 7007 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.execution.runToolbar
import com.intellij.execution.runToolbar.data.RWActiveListener
import com.intellij.execution.runToolbar.data.RWSlotListener
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.ide.ui.ToolbarSettings
import com.intellij.lang.LangBundle
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.impl.segmentedActionBar.SegmentedActionToolbarComponent
import com.intellij.openapi.options.ShowSettingsUtil
import com.intellij.openapi.project.Project
import com.intellij.ui.ComponentUtil
import com.intellij.ui.Gray
import com.intellij.ui.JBColor
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.ui.components.panels.VerticalLayout
import com.intellij.util.ui.JBUI
import net.miginfocom.swing.MigLayout
import java.awt.Dimension
import java.awt.Font
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.SwingUtilities
class RunToolbarExtraSlotPane(val project: Project, val baseWidth: () -> Int?): RWActiveListener {
private val manager = RunToolbarSlotManager.getInstance(project)
private val slotPane = JPanel(VerticalLayout(JBUI.scale(3))).apply {
isOpaque = false
border = JBUI.Borders.empty()
}
private val components = mutableListOf<SlotComponent>()
private val managerListener = object : RWSlotListener {
override fun slotAdded() {
addSingleSlot()
}
override fun slotRemoved(index: Int) {
if (index >= 0 && index < components.size) {
removeSingleComponent(components[index])
}
else {
rebuild()
}
}
override fun rebuildPopup() {
rebuild()
}
}
init {
manager.activeListener.addListener(this)
}
fun clear() {
manager.activeListener.removeListener(this)
}
override fun enabled() {
manager.slotListeners.addListener(managerListener)
}
override fun disabled() {
manager.slotListeners.removeListener(managerListener)
}
private var added = false
private val newSlotDetails = object : JLabel(LangBundle.message("run.toolbar.add.slot.details")){
override fun getFont(): Font {
return JBUI.Fonts.toolbarFont()
}
}.apply {
border = JBUI.Borders.empty()
isEnabled = false
}
private val pane = object : JPanel(VerticalLayout(JBUI.scale(2))) {
override fun addNotify() {
build()
added = true
super.addNotify()
SwingUtilities.invokeLater {
pack()
}
}
override fun removeNotify() {
added = false
super.removeNotify()
}
}.apply {
border = JBUI.Borders.empty(3, 0, 0, 3)
background = JBColor.namedColor("Panel.background", Gray.xCD)
add(slotPane)
val bottomPane = object : JPanel(MigLayout("fillx, ins 0, novisualpadding, gap 0, hidemode 2, wrap 3", "[][]push[]")) {
override fun getPreferredSize(): Dimension {
val preferredSize = super.getPreferredSize()
baseWidth()?.let {
preferredSize.width = it
}
return preferredSize
}
}.apply {
isOpaque = false
border = JBUI.Borders.empty(5, 0, 7, 5)
add(JLabel(AllIcons.Toolbar.AddSlot).apply {
val d = preferredSize
d.width = RunWidgetWidthHelper.getInstance(project).arrow
preferredSize = d
addMouseListener(object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent) {
manager.addAndSaveSlot()
}
})
})
add(LinkLabel<Unit>(LangBundle.message("run.toolbar.add.slot"), null).apply {
setListener(
{_, _ ->
manager.addAndSaveSlot()
}, null)
})
add(JLabel(AllIcons.General.GearPlain).apply {
addMouseListener(object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent) {
ShowSettingsUtil.getInstance().showSettingsDialog(project, RunToolbarSettingsConfigurable::class.java)
}
})
isVisible = ToolbarSettings.getInstance().isAvailable && RunToolbarProcess.isSettingsAvailable
})
add(newSlotDetails, "skip")
}
add(bottomPane)
}
internal fun getView(): JComponent = pane
private fun rebuild() {
build()
pack()
}
private fun build() {
val count = manager.slotsCount()
slotPane.removeAll()
components.clear()
repeat(count) { addNewSlot() }
}
private fun addSingleSlot() {
addNewSlot()
pack()
}
private fun removeSingleComponent(component: SlotComponent) {
removeComponent(component)
pack()
}
private fun addNewSlot() {
val slot = createComponent()
slot.minus.addMouseListener(object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent) {
getData(slot)?.let {
manager.removeSlot(it.id)
}
}
})
components.add(slot)
slotPane.add(slot.view)
}
fun pack() {
newSlotDetails.isVisible = manager.slotsCount() == 0
slotPane.revalidate()
pane.revalidate()
slotPane.repaint()
pane.repaint()
ComponentUtil.getWindow(pane)?.let {
if (it.isShowing) {
it.pack()
}
}
}
private fun removeComponent(component: SlotComponent) {
slotPane.remove(component.view)
components.remove(component)
}
private fun getData(component: SlotComponent): SlotDate? {
val index = components.indexOf(component)
if(index < 0) return null
return manager.getData(index)
}
private fun createComponent(): SlotComponent {
val group = DefaultActionGroup()
val bar = FixWidthSegmentedActionToolbarComponent(ActionPlaces.MAIN_TOOLBAR, group)
val component = SlotComponent(bar, JLabel(AllIcons.Toolbar.RemoveSlot).apply {
val d = preferredSize
d.width = RunWidgetWidthHelper.getInstance(project).arrow
preferredSize = d
})
bar.targetComponent = bar
DataManager.registerDataProvider(bar, DataProvider {
key ->
if(RunToolbarData.RUN_TOOLBAR_DATA_KEY.`is`(key)) {
getData(component)
}
else if(RunToolbarProcessData.RW_SLOT.`is`(key)) {
getData(component)?.id
} else
null
})
val runToolbarActionsGroup = ActionManager.getInstance().getAction(
"RunToolbarActionsGroup") as DefaultActionGroup
for (action in runToolbarActionsGroup.getChildren(null)) {
if (action is ActionGroup && !action.isPopup) {
group.addAll(*action.getChildren(null))
}
else {
group.addAction(action)
}
}
return component
}
internal data class SlotComponent(val bar: SegmentedActionToolbarComponent, val minus: JComponent) {
val view = JPanel(MigLayout("ins 0, gap 0, novisualpadding")).apply {
add(minus)
add(bar)
}
}
} | apache-2.0 | 10b9db29a51efe3ab0e4eee03487743c | 26.162791 | 123 | 0.674897 | 4.448889 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/UseFullyQualifiedCallFix.kt | 4 | 2485 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.intentions.AddFullQualifierIntention
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtCallableReferenceExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
import org.jetbrains.kotlin.psi.KtValueArgument
class UseFullyQualifiedCallFix(
val fqName: FqName,
referenceExpression: KtNameReferenceExpression
) : KotlinQuickFixAction<KtNameReferenceExpression>(referenceExpression) {
override fun getFamilyName() = KotlinBundle.message("fix.use.fully.qualified.call")
override fun getText() = familyName
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val result = AddFullQualifierIntention.applyTo(element, fqName)
ShortenReferences.DEFAULT.process(result)
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): UseFullyQualifiedCallFix? {
val warning = Errors.COMPATIBILITY_WARNING.cast(diagnostic)
val element = warning.psiElement
val descriptor = warning.a
val fqName = descriptor.importableFqName ?: return null
val referenceExpression = if (element is KtValueArgument) {
val expression = element.getArgumentExpression() as? KtCallableReferenceExpression
expression?.callableReference
} else {
element
}
val nameReferenceExpression = referenceExpression as? KtNameReferenceExpression ?: return null
if (!AddFullQualifierIntention.isApplicableTo(nameReferenceExpression, descriptor)) return null
return UseFullyQualifiedCallFix(fqName, nameReferenceExpression)
}
}
}
| apache-2.0 | 45b6e9b52850275ac62e1f53641ec268 | 47.72549 | 158 | 0.759759 | 5.242616 | false | false | false | false |
GunoH/intellij-community | platform/extensions/src/com/intellij/openapi/extensions/ExtensionPointUtil.kt | 2 | 2038 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.extensions
import com.intellij.openapi.Disposable
import com.intellij.openapi.util.Disposer
fun <T : Any> ExtensionPointName<T>.withEachExtensionSafe(action: (T, Disposable) -> Unit) = withEachExtensionSafe(null, action)
fun <T : Any> ExtensionPointName<T>.withEachExtensionSafe(parentDisposable: Disposable?, action: (T, Disposable) -> Unit) {
forEachExtensionSafe(parentDisposable, action)
whenExtensionAdded(parentDisposable, action)
}
fun <T : Any> ExtensionPointName<T>.createExtensionDisposable(extension: T) = createExtensionDisposable(extension, null)
fun <T : Any> ExtensionPointName<T>.createExtensionDisposable(extension: T, parentDisposable: Disposable?): Disposable {
val extensionDisposable = ExtensionPointUtil.createExtensionDisposable(extension, this)
if (parentDisposable != null) {
Disposer.register(parentDisposable, extensionDisposable)
}
return extensionDisposable
}
fun <T : Any> ExtensionPointName<T>.forEachExtensionSafe(action: (T, Disposable) -> Unit) = forEachExtensionSafe(null, action)
fun <T : Any> ExtensionPointName<T>.forEachExtensionSafe(parentDisposable: Disposable?, action: (T, Disposable) -> Unit) {
forEachExtensionSafe { extension ->
val extensionDisposable = createExtensionDisposable(extension, parentDisposable)
action(extension, extensionDisposable)
}
}
fun <T : Any> ExtensionPointName<T>.whenExtensionAdded(action: (T, Disposable) -> Unit) = whenExtensionAdded(null, action)
fun <T : Any> ExtensionPointName<T>.whenExtensionAdded(parentDisposable: Disposable?, action: (T, Disposable) -> Unit) {
addExtensionPointListener(object : ExtensionPointListener<T> {
override fun extensionAdded(extension: T, pluginDescriptor: PluginDescriptor) {
val extensionDisposable = createExtensionDisposable(extension, parentDisposable)
action(extension, extensionDisposable)
}
}, parentDisposable)
}
| apache-2.0 | 27b7aafb4b0a9601920f5fdefb66bef0 | 52.631579 | 128 | 0.783611 | 4.459519 | false | false | false | false |
kivensolo/UiUsingListView | module-Home/src/main/java/com/zeke/home/fragments/SimplePageContentFragment.kt | 1 | 2768 | package com.zeke.home.fragments
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.kingz.module.common.IView
import com.kingz.module.common.base.BaseFragment
import com.kingz.module.common.bean.MediaParams
import com.kingz.module.common.router.Router
import com.kingz.module.common.router.RouterConfig
import com.kingz.module.home.R
import com.zeke.home.entity.Live
import com.zeke.kangaroo.adapter.CommonRecyclerAdapter
/**
* author:KingZ
* date:2019/12/29
* description:首页/点播/每个tab页
*/
class SimplePageContentFragment : BaseFragment(), IView, View.OnClickListener {
private var mRecycleView: RecyclerView? =null
var mRV: RVAdapter = RVAdapter()
override val isShown: Boolean
get() = false
override fun getLayoutId(): Int {
return R.layout.single_recyclerview
}
override fun onViewCreated() {
//TODO 为啥这个recycleView有(174,48,60,99)的padding????
mRecycleView = rootView?.findViewById(R.id.content_recycler)
mRecycleView?.apply {
setHasFixedSize(true)
layoutManager = GridLayoutManager(activity!!, 2)
adapter = mRV
}
}
override fun onDestroyView() {
mRecycleView = null
super.onDestroyView()
}
override fun showLoading() {
}
override fun hideLoading() {
}
override fun showError() {
}
override fun showEmpty() {
}
override fun showMessage(tips: String) {
}
override fun onClick(v: View) {
}
inner class RVAdapter : CommonRecyclerAdapter<Live>(){
init {
// Initializer Block
//为Primary Constructor服务
}
override fun getItemLayout(type: Int): Int {
return R.layout.live_channel_item
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
super.onBindViewHolder(holder, position)
val data = getItem(position)
val textView = holder.getView<TextView>(R.id.channel_id)
textView.text = (data as Live).name
if((position / 2) % 2 != 0){ // 偶数行
textView.setBackgroundResource(R.color.bkg_gary)
}
holder.setOnClickListener {
Router.startActivity(RouterConfig.PAGE_PLAYER, Bundle().apply {
putParcelable(MediaParams.PARAMS_KEY ,MediaParams().apply{
videoName = data.name
videoUrl = data.live
videoType = "live"
})
})
}
}
}
}
| gpl-2.0 | 4d43def6a6d86240a84f4e76c6843e07 | 25.970297 | 79 | 0.622981 | 4.517413 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/alraune/operations/AlCtl_PSQL.kt | 1 | 915 | package alraune.operations
import alraune.*
class AlCtl_Psql : AlCtlCommandWithNamedConfigs<AlCtl_Psql.Config>(Config::class) {
class Config(
val psqlExecutable: String,
val db: DatabaseParams)
override fun configs() = privateConfigs()
override fun danceConfigured() {
runProcessAndWait(listOf(
"cmd.exe", "/c", "chcp", "1251"
// "cmd.exe", "/c", "chcp", "65001"
)).bitchIfBadExit()
runProcessAndWait(
cmdPieces = listOf(
config.psqlExecutable,
"-U", config.db.user,
"-h", config.db.host,
"-p", config.db.port.toString(),
config.db.name
),
fillEnvironment = {
it["PGPASSWORD"] = config.db.password
it["PGCLIENTENCODING"] = "WIN1251"
}
).bitchIfBadExit()
}
}
| apache-2.0 | ad989a992b6cd02df1ef3c1ca0e8775a | 24.416667 | 83 | 0.521311 | 4.140271 | false | true | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceNotNullAssertionWithElvisReturnInspection.kt | 3 | 4361 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.intentions.getParentLambdaLabelName
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypes
import org.jetbrains.kotlin.psi.psiUtil.getTopmostParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.isNullable
import org.jetbrains.kotlin.types.typeUtil.isUnit
class ReplaceNotNullAssertionWithElvisReturnInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = postfixExpressionVisitor(fun(postfix) {
if (postfix.baseExpression == null) return
val operationReference = postfix.operationReference
if (operationReference.getReferencedNameElementType() != KtTokens.EXCLEXCL) return
if ((postfix.getTopmostParentOfType<KtParenthesizedExpression>() ?: postfix).parent is KtReturnExpression) return
val parent = postfix.getParentOfTypes(true, KtLambdaExpression::class.java, KtNamedFunction::class.java)
if (parent !is KtNamedFunction && parent !is KtLambdaExpression) return
val context = postfix.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS)
val (isNullable, returnLabelName) = when (parent) {
is KtNamedFunction -> {
val returnType = parent.descriptor(context)?.returnType ?: return
val isNullable = returnType.isNullable()
if (!returnType.isUnit() && !isNullable) return
isNullable to null
}
is KtLambdaExpression -> {
val functionLiteral = parent.functionLiteral
val returnType = functionLiteral.descriptor(context)?.returnType ?: return
if (!returnType.isUnit()) return
val lambdaLabelName = functionLiteral.bodyBlockExpression?.getParentLambdaLabelName() ?: return
false to lambdaLabelName
}
else -> return
}
if (context.diagnostics.forElement(operationReference).any { it.factory == Errors.UNNECESSARY_NOT_NULL_ASSERTION }) return
holder.registerProblem(
postfix.operationReference,
KotlinBundle.message("replace.with.return"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
ReplaceWithElvisReturnFix(isNullable, returnLabelName)
)
})
private fun KtFunction.descriptor(context: BindingContext): FunctionDescriptor? {
return context[BindingContext.DECLARATION_TO_DESCRIPTOR, this] as? FunctionDescriptor
}
private class ReplaceWithElvisReturnFix(
private val returnNull: Boolean,
private val returnLabelName: String?
) : LocalQuickFix, LowPriorityAction {
override fun getName() = KotlinBundle.message("replace.with.elvis.return.fix.text", if (returnNull) " null" else "")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val postfix = descriptor.psiElement.parent as? KtPostfixExpression ?: return
val base = postfix.baseExpression ?: return
val psiFactory = KtPsiFactory(postfix)
postfix.replaced(
psiFactory.createExpressionByPattern(
"$0 ?: return$1$2",
base,
returnLabelName?.let { "@$it" } ?: "",
if (returnNull) " null" else ""
)
)
}
}
} | apache-2.0 | 2a2ad6bb5bc624557cb809a10387faa0 | 48.568182 | 158 | 0.708094 | 5.417391 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/quickfix/TypeAccessibilityCheckerImpl.kt | 1 | 7348 | // 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.quickfix
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor
import org.jetbrains.kotlin.idea.caches.project.isTestModule
import org.jetbrains.kotlin.idea.caches.project.toDescriptor
import org.jetbrains.kotlin.idea.refactoring.fqName.fqName
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.idea.stubindex.KotlinFullClassNameIndex
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtTypeParameter
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.isInlineClass
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeProjection
import org.jetbrains.kotlin.types.isError
import org.jetbrains.kotlin.types.typeUtil.isNullableAny
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class TypeAccessibilityCheckerImpl(
override val project: Project,
override val targetModule: Module,
override var existingTypeNames: Set<String> = emptySet()
) : TypeAccessibilityChecker {
private val scope by lazy { GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(targetModule, targetModule.isTestModule) }
private var builtInsModule: ModuleDescriptor? = targetModule.toDescriptor()
get() = if (field?.isValid != false) field
else {
field = targetModule.toDescriptor()
field
}
override fun incorrectTypes(declaration: KtNamedDeclaration): Collection<FqName?> = declaration.descriptor?.let {
incorrectTypesInDescriptor(it, false)
} ?: listOf(null)
override fun incorrectTypes(descriptor: DeclarationDescriptor): Collection<FqName?> = incorrectTypesInDescriptor(descriptor, false)
override fun incorrectTypes(type: KotlinType): Collection<FqName?> = incorrectTypesInSequence(type.collectAllTypes(), false)
override fun checkAccessibility(declaration: KtNamedDeclaration): Boolean =
declaration.descriptor?.let { checkAccessibility(it) } == true
override fun checkAccessibility(descriptor: DeclarationDescriptor): Boolean = incorrectTypesInDescriptor(descriptor, true).isEmpty()
override fun checkAccessibility(type: KotlinType): Boolean = incorrectTypesInSequence(type.collectAllTypes(), true).isEmpty()
override fun <R> runInContext(fqNames: Set<String>, block: TypeAccessibilityChecker.() -> R): R {
val oldValue = existingTypeNames
existingTypeNames = fqNames
return block().also { existingTypeNames = oldValue }
}
private fun incorrectTypesInSequence(
sequence: Sequence<FqName?>,
lazy: Boolean = true
): List<FqName?> {
val uniqueSequence = sequence.distinct().filter { !it.canFindClassInModule() }
return when {
uniqueSequence.none() -> emptyList()
lazy -> listOf(uniqueSequence.first())
else -> uniqueSequence.toList()
}
}
private fun incorrectTypesInDescriptor(descriptor: DeclarationDescriptor, lazy: Boolean) =
runInContext(descriptor.additionalClasses(existingTypeNames)) {
incorrectTypesInSequence(descriptor.collectAllTypes(), lazy)
}
private fun FqName?.canFindClassInModule(): Boolean {
val name = this?.asString() ?: return false
return name in existingTypeNames
|| KotlinFullClassNameIndex.getInstance()[name, project, scope].isNotEmpty()
|| builtInsModule?.resolveClassByFqName(this, NoLookupLocation.FROM_BUILTINS) != null
}
}
private tailrec fun DeclarationDescriptor.additionalClasses(existingClasses: Set<String> = emptySet()): Set<String> =
when (this) {
is ClassifierDescriptorWithTypeParameters -> {
val myParameters = existingClasses + declaredTypeParameters.map { it.fqNameOrNull()?.asString() ?: return emptySet() }
val containingDeclaration = containingDeclaration
if (isInner) containingDeclaration.additionalClasses(myParameters) else myParameters
}
is CallableDescriptor -> containingDeclaration.additionalClasses(
existingClasses = existingClasses + typeParameters.map { it.fqNameOrNull()?.asString() ?: return emptySet() }
)
else ->
existingClasses
}
private fun DeclarationDescriptor.collectAllTypes(): Sequence<FqName?> {
val annotations = annotations.asSequence().map(AnnotationDescriptor::type).flatMap(KotlinType::collectAllTypes)
return annotations + when (this) {
is ClassConstructorDescriptor -> valueParameters.asSequence().flatMap(DeclarationDescriptor::collectAllTypes)
is ClassDescriptor -> {
val primaryConstructorTypes = if (isInlineClass())
unsubstitutedPrimaryConstructor?.collectAllTypes().orEmpty()
else
emptySequence()
primaryConstructorTypes +
declaredTypeParameters.asSequence().flatMap(DeclarationDescriptor::collectAllTypes) +
sequenceOf(fqNameOrNull())
}
is CallableDescriptor -> {
val returnType = returnType ?: return sequenceOf(null)
returnType.collectAllTypes() +
explicitParameters.flatMap(DeclarationDescriptor::collectAllTypes) +
typeParameters.asSequence().flatMap(DeclarationDescriptor::collectAllTypes)
}
is TypeParameterDescriptor -> {
val upperBounds = upperBounds
val singleUpperBound = upperBounds.singleOrNull()
when {
// case for unresolved type
singleUpperBound?.isNullableAny() == true -> {
val extendBoundText = findPsi()?.safeAs<KtTypeParameter>()?.extendsBound?.text
if (extendBoundText == null || extendBoundText == "Any?") sequenceOf(singleUpperBound.fqName)
else sequenceOf(null)
}
upperBounds.isEmpty() -> sequenceOf(fqNameOrNull())
else -> upperBounds.asSequence().flatMap(KotlinType::collectAllTypes)
}
}
else -> emptySequence()
}
}
private fun KotlinType.collectAllTypes(): Sequence<FqName?> =
if (isError) {
sequenceOf(null)
} else {
sequenceOf(fqName) +
arguments.asSequence().map(TypeProjection::getType).flatMap(KotlinType::collectAllTypes) +
annotations.asSequence().map(AnnotationDescriptor::type).flatMap(KotlinType::collectAllTypes)
}
private val CallableDescriptor.explicitParameters: Sequence<ParameterDescriptor>
get() = valueParameters.asSequence() + dispatchReceiverParameter?.let {
sequenceOf(it)
}.orEmpty() + extensionReceiverParameter?.let {
sequenceOf(it)
}.orEmpty()
| apache-2.0 | 52c4693cda2e40c8bc41601019f1394c | 45.506329 | 158 | 0.7089 | 5.566667 | false | false | false | false |
blan4/MangaReader | app/src/main/java/org/seniorsigan/mangareader/ui/fragments/BookmarkListFragment.kt | 1 | 2690 | package org.seniorsigan.mangareader.ui.fragments
import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import org.jetbrains.anko.find
import org.jetbrains.anko.support.v4.onRefresh
import org.jetbrains.anko.support.v4.onUiThread
import org.seniorsigan.mangareader.App
import org.seniorsigan.mangareader.R
import org.seniorsigan.mangareader.adapters.ArrayListAdapter
import org.seniorsigan.mangareader.adapters.MangaViewHolder
import org.seniorsigan.mangareader.models.MangaItem
class BookmarkListFragment : Fragment() {
private lateinit var refresh: SwipeRefreshLayout
private lateinit var listView: RecyclerView
private lateinit var progressBar: ProgressBar
private val adapter = ArrayListAdapter(MangaViewHolder::class.java, R.layout.manga_item)
lateinit var onItemClickListener: OnItemClickListener
override fun onAttach(context: Context?) {
super.onAttach(context)
try {
onItemClickListener = activity as OnItemClickListener
} catch (e: ClassCastException) {
throw ClassCastException("$activity must implement OnItemClickListener");
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val rootView = inflater.inflate(R.layout.fragment_manga_list, container, false)
with(rootView, {
refresh = find<SwipeRefreshLayout>(R.id.refresh_manga_list)
listView = find<RecyclerView>(R.id.rv_manga_list)
progressBar = find<ProgressBar>(R.id.progressBar)
})
listView.layoutManager = GridLayoutManager(context, 2)
adapter.onItemClickListener = { manga -> onItemClickListener.onItemClick(manga) }
listView.adapter = adapter
return rootView
}
override fun onStart() {
super.onStart()
refresh.onRefresh {
renderList()
}
renderList()
}
fun renderList() {
App.bookmarkManager.search({ list ->
if (activity == null) return@search
onUiThread {
adapter.update(list)
refresh.isRefreshing = false
progressBar.visibility = View.GONE
}
})
}
interface OnItemClickListener {
fun onItemClick(item: MangaItem)
}
}
| mit | 1de53f4de4d32a731449d29e25a70ef2 | 33.935065 | 116 | 0.711524 | 4.944853 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/favicon_grabber/src/main/kotlin/ch/rmy/favicongrabber/FaviconGrabber.kt | 1 | 1465 | package ch.rmy.favicongrabber
import ch.rmy.favicongrabber.grabbers.Grabber
import ch.rmy.favicongrabber.grabbers.ICOGrabber
import ch.rmy.favicongrabber.grabbers.ManifestGrabber
import ch.rmy.favicongrabber.grabbers.PageMetaGrabber
import ch.rmy.favicongrabber.models.IconResult
import ch.rmy.favicongrabber.utils.HttpUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.withContext
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.OkHttpClient
import java.io.File
class FaviconGrabber(
private val client: OkHttpClient,
private val targetDirectory: File,
private val userAgent: String,
) {
suspend fun grab(url: String, preferredSize: Int): List<IconResult> {
val pageUrl = url.toHttpUrlOrNull()
?: return emptyList()
val pageCache = mutableMapOf<HttpUrl, String?>()
val httpUtil = HttpUtil(client, targetDirectory, pageCache, userAgent)
val grabbers = getGrabbers(httpUtil)
return withContext(Dispatchers.IO) {
grabbers.flatMap { grabber ->
ensureActive()
grabber.grabIconsFrom(pageUrl, preferredSize)
}
}
}
private fun getGrabbers(
httpUtil: HttpUtil,
): List<Grabber> =
listOf(
ManifestGrabber(httpUtil),
PageMetaGrabber(httpUtil),
ICOGrabber(httpUtil),
)
}
| mit | 844696190d47cc3a13296cbc7c7747b6 | 30.847826 | 78 | 0.707167 | 4.271137 | false | false | false | false |
hsz/idea-gitignore | src/main/kotlin/mobi/hsz/idea/gitignore/IgnoreManager.kt | 1 | 11270 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package mobi.hsz.idea.gitignore
import com.intellij.ProjectTopics
import com.intellij.ide.projectView.ProjectView
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.components.service
import com.intellij.openapi.fileTypes.ExactFileNameMatcher
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.DumbService.DumbModeListener
import com.intellij.openapi.project.NoAccessDuringPsiEvents
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.FileStatusManager
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.VcsListener
import com.intellij.openapi.vcs.VcsRoot
import com.intellij.openapi.vcs.changes.ChangeListListener
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileListener
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.util.Time
import com.intellij.util.messages.MessageBusConnection
import com.intellij.util.messages.Topic
import com.jetbrains.rd.util.concurrentMapOf
import mobi.hsz.idea.gitignore.file.type.IgnoreFileType
import mobi.hsz.idea.gitignore.indexing.IgnoreEntryOccurrence
import mobi.hsz.idea.gitignore.indexing.IgnoreFilesIndex
import mobi.hsz.idea.gitignore.lang.IgnoreLanguage
import mobi.hsz.idea.gitignore.services.IgnoreMatcher
import mobi.hsz.idea.gitignore.settings.IgnoreSettings
import mobi.hsz.idea.gitignore.util.CachedConcurrentMap
import mobi.hsz.idea.gitignore.util.Debounced
import mobi.hsz.idea.gitignore.util.ExpiringMap
import mobi.hsz.idea.gitignore.util.Glob
import mobi.hsz.idea.gitignore.util.Utils
/**
* [IgnoreManager] handles ignore files indexing and status caching.
*/
@Suppress("MagicNumber")
class IgnoreManager(private val project: Project) : DumbAware, Disposable {
private val matcher = project.service<IgnoreMatcher>()
private val settings = service<IgnoreSettings>()
private val projectLevelVcsManager = ProjectLevelVcsManager.getInstance(project)
private val changeListManager = project.service<ChangeListManager>()
private val debouncedStatusesChanged = object : Debounced<Any?>(1000) {
override fun task(argument: Any?) {
expiringStatusCache.clear()
FileStatusManager.getInstance(project).fileStatusesChanged()
}
}.also {
Disposer.register(this, it)
}
private val commonRunnableListeners = CommonRunnableListeners(debouncedStatusesChanged)
private var messageBus = project.messageBus.connect(this)
private val cachedIgnoreFilesIndex =
CachedConcurrentMap.create<IgnoreFileType, List<IgnoreEntryOccurrence>> { key -> IgnoreFilesIndex.getEntries(project, key) }
private val expiringStatusCache = ExpiringMap<VirtualFile, Boolean>(Time.SECOND)
private val debouncedExitDumbMode = object : Debounced<Boolean?>(3000) {
override fun task(argument: Boolean?) {
cachedIgnoreFilesIndex.clear()
for ((key, value) in FILE_TYPES_ASSOCIATION_QUEUE) {
associateFileType(key, value)
}
debouncedStatusesChanged.run()
}
}
private var working = false
private val vcsRoots = mutableListOf<VcsRoot>()
/**
* Checks if ignored files watching is enabled.
*
* @return enabled
*/
private val isEnabled
get() = settings.ignoredFileStatus
/** [VirtualFileListener] instance to check if file's content was changed. */
private val bulkFileListener = object : BulkFileListener {
override fun before(events: MutableList<out VFileEvent>) {
events.forEach {
handleEvent(it)
}
}
private fun handleEvent(event: VFileEvent) {
val fileType = event.file?.fileType
if (fileType is IgnoreFileType) {
cachedIgnoreFilesIndex.remove(fileType)
expiringStatusCache.clear()
debouncedStatusesChanged.run()
}
}
}
/** [IgnoreSettings] listener to watch changes in the plugin's settings. */
private val settingsListener = IgnoreSettings.Listener { key, value ->
when (key) {
IgnoreSettings.KEY.IGNORED_FILE_STATUS -> toggle(value as Boolean)
IgnoreSettings.KEY.HIDE_IGNORED_FILES -> ProjectView.getInstance(project).refresh()
else -> {}
}
}
init {
toggle(isEnabled)
}
/**
* Checks if file is ignored.
*
* @param file current file
* @return file is ignored
*/
@Suppress("ComplexCondition", "ComplexMethod", "NestedBlockDepth", "ReturnCount")
fun isFileIgnored(file: VirtualFile): Boolean {
expiringStatusCache[file]?.let {
return it
}
if (ApplicationManager.getApplication().isDisposed || project.isDisposed ||
DumbService.isDumb(project) || !isEnabled || !Utils.isInProject(file, project) ||
NoAccessDuringPsiEvents.isInsideEventProcessing()
) {
return false
}
var ignored = changeListManager.isIgnoredFile(file)
var matched = false
var valuesCount = 0
for (fileType in FILE_TYPES) {
ProgressManager.checkCanceled()
if (IgnoreBundle.ENABLED_LANGUAGES[fileType] != true) {
continue
}
val values = cachedIgnoreFilesIndex[fileType] ?: emptyList()
valuesCount += values.size
@Suppress("LoopWithTooManyJumpStatements")
for (value in values) {
ProgressManager.checkCanceled()
val entryFile = value.file
var relativePath = if (entryFile == null) {
continue
} else {
Utils.getRelativePath(entryFile.parent, file)
} ?: continue
relativePath = StringUtil.trimEnd(StringUtil.trimStart(relativePath, "/"), "/")
if (StringUtil.isEmpty(relativePath)) {
continue
}
if (file.isDirectory) {
relativePath += "/"
}
value.items.forEach {
val pattern = Glob.getPattern(it.first!!)
if (matcher.match(pattern, relativePath)) {
ignored = !it.second
matched = true
}
}
}
}
if (valuesCount > 0 && !ignored && !matched) {
file.parent.let { directory ->
vcsRoots.forEach { vcsRoot ->
ProgressManager.checkCanceled()
if (directory == vcsRoot.path) {
return expiringStatusCache.set(file, false)
}
}
return expiringStatusCache.set(file, isFileIgnored(directory))
}
}
return expiringStatusCache.set(file, ignored)
}
/** Enable manager. */
private fun enable() {
if (working) {
return
}
settings.addListener(settingsListener)
messageBus.subscribe(
VirtualFileManager.VFS_CHANGES,
bulkFileListener
)
messageBus.subscribe(
ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED,
VcsListener {
vcsRoots.clear()
vcsRoots.addAll(projectLevelVcsManager.allVcsRoots)
}
)
messageBus.subscribe(
DumbService.DUMB_MODE,
object : DumbModeListener {
override fun enteredDumbMode() = Unit
override fun exitDumbMode() {
debouncedExitDumbMode.run()
}
}
)
messageBus.subscribe(
ChangeListListener.TOPIC,
object : ChangeListListener {
override fun changeListUpdateDone() {
if (settings.hideIgnoredFiles) {
ProjectView.getInstance(project).refresh()
}
}
}
)
messageBus.subscribe(ProjectTopics.PROJECT_ROOTS, commonRunnableListeners)
messageBus.subscribe(RefreshStatusesListener.REFRESH_STATUSES, commonRunnableListeners)
messageBus.subscribe(ProjectTopics.MODULES, commonRunnableListeners)
working = true
}
/** Disable manager. */
private fun disable() {
settings.removeListener(settingsListener)
working = false
}
override fun dispose() {
disable()
cachedIgnoreFilesIndex.clear()
}
/**
* Runs [.enable] or [.disable] depending on the passed value.
*
* @param enable or disable
*/
private fun toggle(enable: Boolean) {
if (enable) {
enable()
} else {
disable()
}
}
fun interface RefreshStatusesListener {
fun refresh()
companion object {
/** Topic to refresh files statuses using [MessageBusConnection]. */
val REFRESH_STATUSES = Topic("Refresh files statuses", RefreshStatusesListener::class.java)
}
}
companion object {
/** List of all available [IgnoreFileType]. */
private val FILE_TYPES = IgnoreBundle.LANGUAGES.map(IgnoreLanguage::fileType)
/** List of filenames that require to be associated with specific [IgnoreFileType]. */
val FILE_TYPES_ASSOCIATION_QUEUE = concurrentMapOf<String, IgnoreFileType>()
/**
* Associates given file with proper [IgnoreFileType].
*
* @param fileName to associate
* @param fileType file type to bind with pattern
*/
fun associateFileType(fileName: String, fileType: IgnoreFileType) {
val application = ApplicationManager.getApplication()
if (application.isDispatchThread) {
val fileTypeManager = FileTypeManager.getInstance()
application.invokeLater(
{
application.runWriteAction {
fileTypeManager.associate(fileType, ExactFileNameMatcher(fileName))
FILE_TYPES_ASSOCIATION_QUEUE.remove(fileName)
}
},
ModalityState.NON_MODAL
)
} else if (!FILE_TYPES_ASSOCIATION_QUEUE.containsKey(fileName)) {
FILE_TYPES_ASSOCIATION_QUEUE[fileName] = fileType
}
}
}
}
| mit | c39191c6675d13515f67c7c4f6b143e0 | 36.317881 | 140 | 0.632209 | 5.125057 | false | false | false | false |
shabtaisharon/ds3_java_browser | dsb-gui/src/main/java/com/spectralogic/dsbrowser/gui/services/jobService/JobService.kt | 1 | 2391 | /*
* ****************************************************************************
* Copyright 2014-2018 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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.spectralogic.dsbrowser.gui.services.jobService
import com.github.thomasnield.rxkotlinfx.toObservable
import io.reactivex.Completable
import io.reactivex.Observable
import javafx.beans.property.*
import java.util.function.Supplier
abstract class JobService : JobFacade {
protected val title: StringProperty = SimpleStringProperty("")
private val titleObservable: Observable<String> = title.toObservable()
protected val message: StringProperty = SimpleStringProperty("")
private val messageObservable: Observable<String> = message.toObservable()
protected val totalJob: LongProperty = SimpleLongProperty(0L)
private val totalObservable: Observable<Number> = totalJob.toObservable()
protected val visible: SimpleBooleanProperty = SimpleBooleanProperty(true)
private val visibilityObservable: Observable<Boolean> = visible.toObservable()
protected val sent: LongProperty = SimpleLongProperty(0L)
private val sentObservable: Observable<Number> = sent.toObservable()
override fun titleObservable(): Observable<String> = titleObservable
override fun messageObservable(): Observable<String> = messageObservable
override fun visabilityObservable(): Observable<Boolean> = visibilityObservable
override fun jobSizeObservable(): Observable<Number> = totalObservable
override fun sentObservable(): Observable<Number> = sentObservable
override fun totalJobSizeAsProperty(): LongProperty = totalJob
override fun visibleProperty(): SimpleBooleanProperty = visible
abstract override fun finishedCompletable(cancelled: Supplier<Boolean>): Completable
} | apache-2.0 | 951ebc06b64acfec3b757f1c807b207f | 48.833333 | 90 | 0.72271 | 5.278146 | false | false | false | false |
aurae/PermissionsDispatcher | processor/src/main/kotlin/permissions/dispatcher/processor/impl/kotlin/KotlinActivityProcessorUnit.kt | 1 | 1313 | package permissions.dispatcher.processor.impl.kotlin
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.FunSpec
import permissions.dispatcher.processor.util.*
import javax.lang.model.type.TypeMirror
/**
* [permissions.dispatcher.processor.KtProcessorUnit] implementation for Activity classes.
*/
class KotlinActivityProcessorUnit : KotlinBaseProcessorUnit() {
private val ACTIVITY_COMPAT = ClassName.bestGuess("android.support.v4.app.ActivityCompat")
override fun getTargetType(): TypeMirror = typeMirrorOf("android.app.Activity")
override fun getActivityName(): String = "this"
override fun addShouldShowRequestPermissionRationaleCondition(builder: FunSpec.Builder, permissionField: String, isPositiveCondition: Boolean) {
val condition = if (isPositiveCondition) "" else "!"
val activity = getActivityName()
builder.beginControlFlow("if (%N%T.shouldShowRequestPermissionRationale(%N, *%N))", condition, PERMISSION_UTILS, activity, permissionField)
}
override fun addRequestPermissionsStatement(builder: FunSpec.Builder, targetParam: String, permissionField: String, requestCodeField: String) {
builder.addStatement("%T.requestPermissions(%N, %N, %N)", ACTIVITY_COMPAT, targetParam, permissionField, requestCodeField)
}
}
| apache-2.0 | fe381692dc60c7ef7abee602c9dd3e39 | 45.892857 | 148 | 0.776085 | 4.899254 | false | false | false | false |
google/intellij-gn-plugin | src/main/java/com/google/idea/gn/completion/IdentifierCompletionProvider.kt | 1 | 2839 | // Copyright (c) 2020 Google LLC All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package com.google.idea.gn.completion
import com.google.idea.gn.GnKeys
import com.google.idea.gn.psi.*
import com.google.idea.gn.psi.Function
import com.google.idea.gn.psi.builtin.Import
import com.google.idea.gn.psi.builtin.Template
import com.google.idea.gn.psi.scope.FileScope
import com.google.idea.gn.psi.scope.Scope
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionProvider
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.PsiElement
import com.intellij.psi.util.parentOfTypes
import com.intellij.psi.util.parents
import com.intellij.util.ProcessingContext
class IdentifierCompletionProvider : CompletionProvider<CompletionParameters>() {
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, _result: CompletionResultSet) {
val result = IdentifierCompletionResultSet(_result)
val position = parameters.position
val file = position.containingFile
if (file !is GnFile) {
return
}
val stopAt = position.parentOfTypes(GnStatement::class,
GnBlock::class, GnFile::class) ?: file
val capturingVisitor = object : Visitor.VisitorDelegate() {
var finalScope: Scope? = null
override fun resolveCall(call: GnCall, function: Function?): Visitor.CallAction =
when {
// Template and import calls must be executed so they show up in the scope.
function is Template || function is Import -> Visitor.CallAction.EXECUTE
position.parents(true).contains(call) -> Visitor.CallAction.VISIT_BLOCK
else -> Visitor.CallAction.SKIP
}
override fun afterVisit(element: PsiElement, scope: Scope): Boolean {
if (element == stopAt) {
finalScope = scope
return true
}
return false
}
}
file.accept(Visitor(FileScope(), capturingVisitor))
val scope = capturingVisitor.finalScope ?: file.scope
val inFunction = position.parentOfTypes(GnCall::class)
?.getUserData(GnKeys.CALL_RESOLVED_FUNCTION)
scope.gatherCompletionIdentifiers {
ProgressManager.checkCanceled()
if (it == inFunction) {
it.gatherChildren { child ->
result.addIdentifier(child)
}
}
// Don't suggest target functions within a target function.
if (inFunction?.identifierType != CompletionIdentifier.IdentifierType.TARGET_FUNCTION
|| it.identifierType != CompletionIdentifier.IdentifierType.TARGET_FUNCTION) {
result.addIdentifier(it)
}
}
}
}
| bsd-3-clause | 994e61f73f7aa0aeab7cbbac8e34e37e | 34.049383 | 123 | 0.718211 | 4.535144 | false | false | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/ui/notes/OnSwipeListener.kt | 1 | 4072 | package com.orgzly.android.ui.notes
import android.view.GestureDetector.SimpleOnGestureListener
import android.view.MotionEvent
import kotlin.math.atan2
/**
* https://stackoverflow.com/questions/13095494/how-to-detect-swipe-direction-between-left-right-and-up-down
*/
open class OnSwipeListener : SimpleOnGestureListener() {
override fun onFling(
e1: MotionEvent,
e2: MotionEvent,
velocityX: Float,
velocityY: Float
): Boolean {
// Grab two events located on the plane at e1=(x1, y1) and e2=(x2, y2)
// Let e1 be the initial event
// e2 can be located at 4 different positions, consider the following diagram
// (Assume that lines are separated by 90 degrees.)
//
//
// \ A /
// \ /
// D e1 B
// / \
// / C \
//
// So if (x2,y2) falls in region:
// A => it's an UP swipe
// B => it's a RIGHT swipe
// C => it's a DOWN swipe
// D => it's a LEFT swipe
val x1 = e1.x
val y1 = e1.y
val x2 = e2.x
val y2 = e2.y
val direction = getDirection(x1, y1, x2, y2)
return onSwipe(direction, e1, e2)
}
/** Override this method. The Direction enum will tell you how the user swiped. */
open fun onSwipe(direction: Direction, e1: MotionEvent, e2: MotionEvent): Boolean {
return false
}
/**
* Given two points in the plane p1=(x1, x2) and p2=(y1, y1), this method
* returns the direction that an arrow pointing from p1 to p2 would have.
* @param x1 the x position of the first point
* @param y1 the y position of the first point
* @param x2 the x position of the second point
* @param y2 the y position of the second point
* @return the direction
*/
private fun getDirection(x1: Float, y1: Float, x2: Float, y2: Float): Direction {
val angle = getAngle(x1, y1, x2, y2)
return Direction.fromAngle(angle)
}
/**
*
* Finds the angle between two points in the plane (x1,y1) and (x2, y2)
* The angle is measured with 0/360 being the X-axis to the right, angles
* increase counter clockwise.
*
* @param x1 the x position of the first point
* @param y1 the y position of the first point
* @param x2 the x position of the second point
* @param y2 the y position of the second point
* @return the angle between two points
*/
fun getAngle(x1: Float, y1: Float, x2: Float, y2: Float): Double {
val rad = atan2((y1 - y2).toDouble(), (x2 - x1).toDouble()) + Math.PI
return (rad * 180 / Math.PI + 180) % 360
}
enum class Direction {
UP,
DOWN,
LEFT,
RIGHT;
companion object {
/**
* Returns a direction given an angle.
* Directions are defined as follows:
*
* Up: [45, 135]
* Right: [0,45] and [315, 360]
* Down: [225, 315]
* Left: [135, 225]
*
* @param angle an angle from 0 to 360 - e
* @return the direction of an angle
*/
fun fromAngle(angle: Double): Direction {
return if (inRange(angle, 45f, 135f)) {
UP
} else if (inRange(angle, 0f, 45f) || inRange(angle, 315f, 360f)) {
RIGHT
} else if (inRange(angle, 225f, 315f)) {
DOWN
} else {
LEFT
}
}
/**
* @param angle an angle
* @param init the initial bound
* @param end the final bound
* @return returns true if the given angle is in the interval [init, end).
*/
private fun inRange(angle: Double, init: Float, end: Float): Boolean {
return angle >= init && angle < end
}
}
}
} | gpl-3.0 | 4f74cb5e492a33aa8c1950f5d99d906b | 31.846774 | 108 | 0.528242 | 3.964946 | false | false | false | false |
oversecio/oversec_crypto | crypto/src/main/java/io/oversec/one/crypto/images/xcoder/blackandwhite/BitmapInputStream.kt | 1 | 1500 | package io.oversec.one.crypto.images.xcoder.blackandwhite
import android.graphics.Bitmap
import android.graphics.Color
import java.io.IOException
import java.io.InputStream
class BitmapInputStream internal constructor(
private val mBm: Bitmap,
val pixels: Int
) : InputStream() {
private val mW: Int
private val mH: Int
private var mPixelOffset: Int = 0
init {
mW = mBm.width
mH = mBm.height
}
@Throws(IOException::class)
override fun read(): Int {
var y = mPixelOffset / ( mW / pixels)
var x = mPixelOffset - y * ( mW / pixels)
var res = 0
for (k in 0..7) {
if (x >= mW || y >= mH) {
return -1
}
var score = 0;
for (xx in 0..pixels-1) {
for (yy in 0..pixels-1) {
val c = mBm.getPixel(x*pixels+xx, y*pixels+yy)
if (Color.red(c) > 128) {
score++
}
if (Color.blue(c) > 128) {
score++
}
if (Color.green(c) > 128) {
score++
}
}
}
if (score > (pixels*pixels)) {
res += 1 shl 7 - k
}
x++
if (x >= (mW/pixels)) {
x = 0
y++
}
}
mPixelOffset += 8
return res
}
} | gpl-3.0 | afa6ff0a3223d729565654c523089ef9 | 23.606557 | 66 | 0.419333 | 4.087193 | false | false | false | false |
misakuo/svgtoandroid | src/com/moxun/s2v/kt/VectorDrawableFixinator.kt | 1 | 1000 | package com.moxun.s2v.kt
/**
* @author eymar
* @link https://github.com/eymar/DrVectorAndroid
*/
object VectorDrawableFixinator {
private val regexMap = mapOf(
"\n" to " ",
"(-)(\\.\\d)" to " -0$2",
" (\\.\\d)" to " 0$1",
"([a-z]|[A-Z])(\\.\\d)" to "$1 0$2"
)
@JvmStatic
fun getContentWithFixedFloatingPoints(value: String): String {
var result = value as CharSequence
// some paths may contain commas. Replace commas with spaces
result = result.replace(",".toRegex(), " ")
val prepareRegex = "(\\.\\d+)(\\.\\d)".toRegex()
while (result.contains(prepareRegex)) { // adds spaces
result = result.replace(prepareRegex, "$1 $2")
}
regexMap.forEach {
result = result.replace(it.key.toRegex(), it.value)
}
val finalRegex = "\\s{2,}".toRegex()
result = result.replace(finalRegex, " ")
return result.toString()
}
} | mit | 6569d432cd321159b47f49676dc8ac25 | 24.025 | 68 | 0.53 | 3.787879 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/search/service/mutator/MutatedGeneSpecification.kt | 1 | 8566 | package org.evomaster.core.search.service.mutator
import org.evomaster.core.database.DbAction
import org.evomaster.core.search.Action
import org.evomaster.core.search.Individual
import org.evomaster.core.search.gene.Gene
/**
* created by manzh on 2019-09-10
*
* @property mutatedGenes records what genes are mutated
* @property mutatedDbGenes records what db genes are mutated
* @property addedGenes (structure mutation) records what genes are added using structure mutator
* @property removedGene (structure mutation) records what genes are removed using structure mutator
* @property mutatedPosition records where mutated/added/removed genes are located. but regarding different individual,
* the position may be parsed in different way. For instance, the position may indicate the position of resource calls,
* not rest action.
* @property mutatedDbActionPosition records where mutated/added/removed dbgenes are located.
*/
data class MutatedGeneSpecification (
val mutatedGenes : MutableList<MutatedGene> = mutableListOf(),
val mutatedDbGenes : MutableList<MutatedGene> = mutableListOf(),
val mutatedInitGenes : MutableList<MutatedGene> = mutableListOf(),
//SQL handling
val addedInitializationGenes : MutableList<Gene> = mutableListOf(),
val addedExistingDataInitialization: MutableList<Action> = mutableListOf(),
val addedInitializationGroup: MutableList<List<Action>> = mutableListOf(),
//SQL resource handling
val addedDbActions : MutableList<List<DbAction>> = mutableListOf(),
val removedDbActions : MutableList<Pair<DbAction, Int>> = mutableListOf(),
// external service actions
val addedExternalServiceActions : MutableList<Action> = mutableListOf()
){
var mutatedIndividual: Individual? = null
private set
fun setMutatedIndividual(individual: Individual){
if (mutatedIndividual!= null)
throw IllegalArgumentException("it does not allow setting mutated individual more than one time")
mutatedIndividual = individual
}
fun addMutatedGene(isDb : Boolean, isInit : Boolean, valueBeforeMutation : String, gene : Gene, position : Int?, localId: String?, resourcePosition: Int? = null){
(if (isInit)
mutatedInitGenes
else if (isDb){
mutatedDbGenes
}else{
mutatedGenes
}).add(MutatedGene(valueBeforeMutation, gene, actionPosition=position, localId=localId, resourcePosition = resourcePosition))
}
//FIXME: need documentation for these parameters
/**
* @param action represents the action to be added/removed
* @param position represents the location of the fixed indexed action in the individual, note that the location is in terms of the fixedMainAction group
* @param localId represents the local id of the action, and it is used for dynamic main action
* @param removed represents the mutation type, either add or remove
* @param resourcePosition represents the index of resource if the action belongs to such structure
*/
fun addRemovedOrAddedByAction(action: Action, position: Int?, localId: String?, removed : Boolean, resourcePosition: Int?){
mutatedGenes.addAll(
action.seeTopGenes().map { MutatedGene(null, it, position, localId = localId,
if (removed) MutatedType.REMOVE else MutatedType.ADD, resourcePosition = resourcePosition) }
)
if (action.seeTopGenes().isEmpty()){
mutatedGenes.add(MutatedGene(null, null, position,localId = localId,
if (removed) MutatedType.REMOVE else MutatedType.ADD, resourcePosition = resourcePosition))
}
}
fun swapAction(resourcePosition: Int, from: List<Int>, to: List<Int>){
mutatedGenes.add(
MutatedGene(previousValue = null, gene = null, actionPosition =null, type = MutatedType.SWAP, localId = null,
resourcePosition = resourcePosition, from = from, to = to)
)
}
fun isActionMutated(actionIndex : Int?, actionLocalId: String?, isInit: Boolean) : Boolean{
if (isInit)
return mutatedInitGenes.any { it.type == MutatedType.MODIFY && it.actionPosition == actionIndex }
return (mutatedGenes.plus(mutatedDbGenes)).any { it.type == MutatedType.MODIFY && (
it.actionPosition == actionIndex || it.localId == actionLocalId
) }
}
fun getRemoved(isRest : Boolean) =
(if (isRest) mutatedGenes else (mutatedInitGenes.plus(mutatedDbGenes))).filter { it.type == MutatedType.REMOVE}
fun getAdded(isRest : Boolean) = (if (isRest) mutatedGenes else (mutatedInitGenes.plus(mutatedDbGenes))).filter { it.type == MutatedType.ADD}
fun getMutated(isRest : Boolean) = (if (isRest) mutatedGenes else (mutatedInitGenes.plus(mutatedDbGenes))).filter { it.type == MutatedType.MODIFY}
fun getSwap() = mutatedGenes.filter { it.type == MutatedType.SWAP }
fun mutatedGeneInfo() = mutatedGenes.map { it.gene }
fun mutatedInitGeneInfo() = mutatedInitGenes.map { it.gene }
fun mutatedDbGeneInfo() = mutatedDbGenes.map { it.gene }
fun numOfMutatedGeneInfo() = mutatedGenes.size + mutatedDbGenes.size+ mutatedInitGenes.size
fun didAddInitializationGenes() = addedInitializationGenes.isNotEmpty() || addedExistingDataInitialization.isNotEmpty()
data class MutatedGene(
/**
* previous value of the mutated gene if it has
*/
val previousValue : String? = null,
/**
* the mutated gene
*/
val gene: Gene?,
/**
* where the gene is located at
* we employ an index of action for initialization and fixedMainAction
*/
val actionPosition: Int?,
/**
* for dynimiac main action, we employ local id of the action to target the action
* which contains the mutated gene
*/
val localId : String?,
/**
* the type of mutation representing what the mutation was performed
*/
val type : MutatedType = MutatedType.MODIFY,
/**
* the index of resource if the gene belongs to such structure
*/
val resourcePosition: Int? = actionPosition,
/**
* when swap mutation is applied, it is used to record the `from` positions
*
* Note that this mutator is only applicable to fixed main action
*/
val from : List<Int>? = null,
/**
* when swap mutation is applied, it is used to record the `to` positions
*
* Note that this mutator is only applicable to fixed main action
*/
val to : List<Int>? = null
)
enum class MutatedType{
ADD,
REMOVE,
MODIFY,
SWAP
}
// add, remove, swap, add_sql, remove_sql
fun didStructureMutation() = mutatedGenes.any { it.type != MutatedType.MODIFY }
|| (mutatedInitGenes.plus(mutatedDbGenes)).any { it.type != MutatedType.MODIFY }
|| addedDbActions.isNotEmpty() || removedDbActions.isNotEmpty()
fun isMutated(gene: Gene) = (mutatedInitGenes.plus(mutatedDbGenes)).any { it.gene == gene }
|| mutatedGenes.any { it.gene == gene }
|| addedDbActions.flatten().any { it.seeTopGenes().contains(gene) }
|| removedDbActions.map { it.first }.any { it.seeTopGenes().contains(gene) }
fun mutatedActionOrInit() = setOf((mutatedGenes.plus(mutatedDbGenes)).isEmpty(), mutatedInitGenes.isNotEmpty())
/**
* repair mutated db genes based on [individual] after db repair
*/
fun repairInitAndDbSpecification(individual: Individual) : Boolean{
val init = individual.seeInitializingActions()
var anyRemove = mutatedInitGenes.removeIf {
it.type == MutatedType.MODIFY && it.actionPosition != null && it.actionPosition >= init.size
}
val noInit = individual.seeFixedMainActions()
anyRemove = mutatedDbGenes.removeIf {
it.type == MutatedType.MODIFY && (if (it.actionPosition != null)
it.actionPosition >= noInit.size
else if (it.localId != null)
noInit.none { a-> a.getLocalId() == it.localId }
else
throw IllegalArgumentException("to represent mutated gene info, position or local id of an action which contains the gene must be specified"))
} || anyRemove
return anyRemove
}
} | lgpl-3.0 | 01c96f17ca4131125b1d8f479351505b | 43.853403 | 166 | 0.664254 | 4.735213 | false | false | false | false |
SveTob/rabbit-puppy | src/test/java/com/meltwater/puppy/rest/RabbitRestClientTest.kt | 1 | 5119 | package com.meltwater.puppy.rest
import com.google.common.collect.ImmutableMap.of
import com.google.gson.Gson
import com.insightfullogic.lambdabehave.JunitSuiteRunner
import com.insightfullogic.lambdabehave.Suite.describe
import com.meltwater.puppy.config.ExchangeData
import com.meltwater.puppy.config.ExchangeType
import com.meltwater.puppy.config.PermissionsData
import com.meltwater.puppy.config.VHostData
import org.hamcrest.Matchers.greaterThanOrEqualTo
import org.junit.runner.RunWith
import java.io.IOException
import java.util.*
import javax.ws.rs.client.Entity
import javax.ws.rs.core.MediaType
@RunWith(JunitSuiteRunner::class)
class RabbitRestClientTest {
init {
val properties = object : Properties() {
init {
try {
load(ClassLoader.getSystemResourceAsStream("test.properties"))
} catch (e: IOException) {
e.printStackTrace()
}
}
}
val gson = Gson()
val brokerAddress = properties.getProperty("rabbit.broker.address")
val brokerUser = properties.getProperty("rabbit.broker.user")
val brokerPass = properties.getProperty("rabbit.broker.pass")
val req = RestRequestBuilder(brokerAddress, Pair(brokerUser, brokerPass)).withHeader("content-type", "application/json")
describe("a RabbitMQ REST client with valid auth credentials") { it ->
val rabbitRestClient = RabbitRestClient(brokerAddress, brokerUser, brokerPass)
it.isSetupWith {
req.request(PATH_VHOSTS_SINGLE, of("vhost", "test")).put(Entity.entity(gson.toJson(VHostData()), MediaType.APPLICATION_JSON_TYPE))
req.request(PATH_PERMISSIONS_SINGLE, of("vhost", "test", "user", "guest")).put(Entity.entity(gson.toJson(PermissionsData()), MediaType.APPLICATION_JSON_TYPE))
req.request(PATH_EXCHANGES_SINGLE, of("vhost", "test", "exchange", "test.ex")).put(Entity.entity(gson.toJson(ExchangeData()), MediaType.APPLICATION_JSON_TYPE))
}
it.isConcludedWith {
req.request(PATH_VHOSTS_SINGLE, of("vhost", "test")).delete()
req.request(PATH_VHOSTS_SINGLE, of("vhost", "test1")).delete()
req.request(PATH_VHOSTS_SINGLE, of("vhost", "test2")).delete()
req.request(PATH_VHOSTS_SINGLE, of("vhost", "test/test")).delete()
}
it.uses("test1", VHostData(false)).and("test2", VHostData(true)).toShow("creates vhost: %s") { expect, vhost, data ->
rabbitRestClient.createVirtualHost(vhost, data)
val map = gson.fromJson<Map<Any, Any>>(getString(req, PATH_VHOSTS_SINGLE, of("vhost", vhost)), Map::class.java)
expect.that(map["tracing"]).`is`(data.tracing)
}
it.should("gets existing vhosts") { expect ->
val virtualHosts = rabbitRestClient.getVirtualHosts()
expect.that(virtualHosts.keys).hasSize(greaterThanOrEqualTo(1)).hasItem("/")
expect.that(virtualHosts["/"])
.isNotNull
.instanceOf(VHostData::class.java)
}
it.uses("ex1", "test", exchangeOfType(ExchangeType.fanout))
.and("ex2", "test", exchangeOfType(ExchangeType.direct))
.and("ex3", "test", exchangeOfType(ExchangeType.headers))
.and("ex4", "test", ExchangeData(ExchangeType.topic, false, true, true, of("foo", "bar")))
.toShow("creates exchange: %s") { expect, exchange, vhost, data ->
rabbitRestClient.createExchange(vhost, exchange, data, brokerUser, brokerUser)
val response = gson.fromJson(getString(req, PATH_EXCHANGES_SINGLE, of(
"vhost", vhost,
"exchange", exchange)),
ExchangeData::class.java)
expect.that(response).`is`(data)
}
it.should("gets existing exchange") { expect ->
val exchange = rabbitRestClient.getExchange("/", "amq.direct", brokerUser, brokerPass)
expect.that(exchange.isPresent)
.`is`(true)
.and(exchange.get())
.isNotNull
}
it.should("does not get non-existing exchange") { expect ->
val exchange = rabbitRestClient.getExchange("/", "amq.NOPE", brokerUser, brokerPass)
expect.that(exchange.isPresent)
.`is`(false)
}
// TODO test get/create users, permissions, queues, bindings
}
}
private fun exchangeOfType(type: ExchangeType): ExchangeData {
val exchangeData = ExchangeData()
exchangeData.type = type
return exchangeData
}
private fun getString(requestBuilder: RestRequestBuilder, path: String, params: Map<String, String>): String {
return requestBuilder.request(path, params).get().readEntity(String::class.java)
}
} | mit | f71a9c5bcf61bbacd33a0466fb365375 | 43.521739 | 175 | 0.607345 | 4.341815 | false | true | false | false |
proxer/ProxerLibAndroid | library/src/test/kotlin/me/proxer/library/internal/interceptor/RateLimitInterceptorTest.kt | 1 | 5068 | package me.proxer.library.internal.interceptor
import me.proxer.library.ProxerApi
import me.proxer.library.ProxerException
import me.proxer.library.ProxerException.ServerErrorType
import me.proxer.library.ProxerTest
import me.proxer.library.enums.Language
import me.proxer.library.fromResource
import me.proxer.library.runRequest
import okhttp3.Cache
import okhttp3.mockwebserver.MockResponse
import org.amshove.kluent.AnyException
import org.amshove.kluent.invoking
import org.amshove.kluent.shouldBe
import org.amshove.kluent.shouldNotBeNull
import org.amshove.kluent.shouldNotThrow
import org.amshove.kluent.shouldThrow
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.RepeatedTest
import org.junit.jupiter.api.Test
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
class RateLimitInterceptorTest : ProxerTest() {
private val rateLimitApi = ProxerApi.Builder("mock-key")
.enableRateLimitProtection()
.client(client.newBuilder().cache(Cache(createTempDir(), 1_024L * 1_024L)).build())
.build()
@Test
fun testSingleRequest() {
server.runRequest("chapter.json") {
rateLimitApi.manga.chapter("123", 123, Language.ENGLISH).build().execute()
}
}
@Test
fun testRateLimitError() {
// Limit 10.
repeat(8) {
server.runRequest("chapter.json") {
rateLimitApi.manga.chapter("123", 123, Language.ENGLISH).build().execute()
}
}
val result = invoking {
server.runRequest("chapter.json") {
rateLimitApi.manga.chapter("123", 123, Language.ENGLISH).build().execute()
}
} shouldThrow ProxerException::class
result.exception.errorType shouldBe ProxerException.ErrorType.SERVER
result.exception.serverErrorType shouldBe ServerErrorType.RATE_LIMIT
}
@Test
fun testCachedResponse() {
val response = MockResponse()
.setBody(fromResource("chapter.json"))
.setHeader("Cache-Control", "public, max-age=31536000")
// Limit 10.
repeat(8) {
server.enqueue(response)
rateLimitApi.manga.chapter("123", 123, Language.ENGLISH).build().execute()
}
invoking {
server.enqueue(response)
rateLimitApi.manga.chapter("123", 123, Language.ENGLISH).build().execute()
} shouldNotThrow AnyException
}
@Test
@RepeatedTest(50)
fun testParallelRequests() {
// Limit 10.
repeat(7) {
server.runRequest("chapter.json") {
rateLimitApi.manga.chapter("123", 123, Language.ENGLISH).build().execute()
}
}
server.enqueue(MockResponse().setBody(fromResource("chapter.json")))
server.enqueue(MockResponse().setBody(fromResource("chapter.json")))
val lock = CountDownLatch(2)
var error: ProxerException? = null
rateLimitApi.manga.chapter("123", 123, Language.ENGLISH).build().enqueue(
{ lock.countDown() },
{
error = it
lock.countDown()
}
)
rateLimitApi.manga.chapter("123", 123, Language.ENGLISH).build().enqueue(
{ lock.countDown() },
{
error = it
lock.countDown()
}
)
lock.await(3_000L, TimeUnit.MILLISECONDS)
error.shouldNotBeNull()
error!!.serverErrorType shouldBe ServerErrorType.RATE_LIMIT
}
@Test
@Disabled // Does not work because of real urls being passed in and mock urls in cache.
fun testLimitButCached() {
// Limit 10.
repeat(7) {
server.runRequest("chapter.json") {
rateLimitApi.manga.chapter("123", 123, Language.ENGLISH).build().execute()
}
}
val response = MockResponse()
.setBody(fromResource("chapter.json"))
.setHeader("Cache-Control", "public, max-age=31536000")
server.enqueue(response)
rateLimitApi.manga.chapter("123", 123, Language.ENGLISH).build().execute()
invoking {
server.enqueue(response)
rateLimitApi.manga.chapter("123", 123, Language.ENGLISH).build().execute()
} shouldNotThrow AnyException
}
@Test
@Disabled
fun testResetStateAfterTimeLimit() {
// Limit 30.
repeat(28) {
server.runRequest("chat_messages.json") {
rateLimitApi.chat.messages("123").build().execute()
}
}
val result = invoking {
server.runRequest("chat_messages.json") {
rateLimitApi.chat.messages("123").build().execute()
}
} shouldThrow ProxerException::class
result.exception.serverErrorType shouldBe ServerErrorType.RATE_LIMIT
Thread.sleep(30_000)
server.runRequest("chat_messages.json") {
rateLimitApi.chat.messages("123").build().execute()
}
}
}
| gpl-3.0 | ffc9af3475116a38388f2936740b2bb4 | 30.675 | 91 | 0.621152 | 4.557554 | false | true | false | false |
AlmasB/FXGL | fxgl/src/test/kotlin/com/almasb/fxgl/app/GameSettingsTest.kt | 1 | 4203 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.app
import com.almasb.fxgl.core.concurrent.Async
import com.almasb.fxgl.core.util.Platform
import com.almasb.fxgl.test.RunWithFX
import javafx.scene.input.KeyCode
import javafx.stage.Stage
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.CoreMatchers.hasItems
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import java.util.*
import java.util.concurrent.Callable
/**
*
*
* @author Almas Baimagambetov ([email protected])
*/
@ExtendWith(RunWithFX::class)
class GameSettingsTest {
class MockGameApplication : GameApplication() {
override public fun initSettings(settings: GameSettings) {
settings.width = 500
settings.height = 500
settings.title = "Test"
settings.version = "0.99"
settings.isIntroEnabled = false
settings.isMainMenuEnabled = false
settings.isGameMenuEnabled = false
settings.isFullScreenAllowed = false
settings.isProfilingEnabled = false
settings.isCloseConfirmation = false
settings.menuKey = KeyCode.ENTER
settings.credits = Arrays.asList("TestCredit1", "TestCredit2")
settings.applicationMode = ApplicationMode.RELEASE
}
}
companion object {
lateinit var settings: ReadOnlyGameSettings
@BeforeAll
@JvmStatic fun before() {
val app = MockGameApplication()
val settingsInitial = GameSettings()
app.initSettings(settingsInitial)
val stage = Async.startAsyncFX(Callable { Stage() }).await()
val engine = Engine(settingsInitial.toReadOnly())
settings = engine.settings
}
}
/**
* This is linked to [MockGameApplication] and its
* initSettings().
*/
@Test
fun `Test settings data`() {
assertThat(settings.runtimeInfo.version, `is`("11.x"))
assertThat(settings.runtimeInfo.build, `is`("?"))
assertThat(settings.width, `is`(500))
assertThat(settings.height, `is`(500))
assertThat(settings.title, `is`("Test"))
assertThat(settings.version, `is`("0.99"))
assertThat(settings.isIntroEnabled, `is`(false))
assertThat(settings.isMainMenuEnabled, `is`(false))
assertThat(settings.isGameMenuEnabled, `is`(false))
assertThat(settings.isFullScreenAllowed, `is`(false))
assertThat(settings.isProfilingEnabled, `is`(false))
assertThat(settings.isCloseConfirmation, `is`(false))
assertThat(settings.menuKey, `is`(KeyCode.ENTER))
assertThat(settings.credits, hasItems("TestCredit1", "TestCredit2"))
assertThat(settings.applicationMode, `is`(ApplicationMode.RELEASE))
assertTrue(settings.isDesktop)
assertFalse(settings.isBrowser)
assertFalse(settings.isMobile)
assertFalse(settings.isIOS)
assertFalse(settings.isAndroid)
// this only reads the default settings, so regardless of platform where test is running, the following should be Windows
// the actual platform tests are in PlatformTest.kt
assertThat(settings.runtimeInfo.platform, `is`(Platform.WINDOWS))
assertTrue(settings.isWindows)
assertFalse(settings.isLinux)
assertFalse(settings.isMac)
}
@Test
fun `Test setting of height and width from ratio`() {
val settingsInitial = GameSettings()
assertThat(settingsInitial.width, `is`(800))
assertThat(settingsInitial.height, `is`(600))
settingsInitial.width = 100;
settingsInitial.setHeightFromRatio(0.5);
assertThat(settingsInitial.height, `is`(200))
settingsInitial.height = 400;
settingsInitial.setWidthFromRatio(1.3);
assertThat(settingsInitial.width, `is`(520))
}
}
| mit | e7532b71c6cc0b35ddb6bfe2e38266d8 | 34.025 | 129 | 0.674994 | 4.424211 | false | true | false | false |
googlecodelabs/android-compose-codelabs | AnimationCodelab/start/src/main/java/com/example/android/codelab/animation/ui/Color.kt | 2 | 943 | /*
* 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.codelab.animation.ui
import androidx.compose.ui.graphics.Color
val Purple100 = Color(0xFFE1BEE7)
val Purple500 = Color(0xFF6200EE)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
val Green300 = Color(0xFF81C784)
val Green800 = Color(0xFF2E7D32)
val Amber600 = Color(0xFFFFB300)
| apache-2.0 | bab770e630e9e3a597a99eb591d18b13 | 33.925926 | 75 | 0.76246 | 3.558491 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.