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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
hummatli/MAHAds
|
app-cross-promoter/src/main/java/com/mobapphome/appcrosspromoter/tools/Constants.kt
|
2
|
509
|
package com.mobapphome.appcrosspromoter.tools
object Constants {
@JvmField val MAH_ADS_VERSION = "mah_ads_version"
@JvmField val PROGRAM_LIST_CACHE = "program_list_cache2"
@JvmField val MAH_ADS_GITHUB_LINK = "https://github.com/hummatli/MAHAds"
@JvmField val MAH_ADS_INTERNAL_CALLED = "internal_called"
@JvmField val LOG_TAG_MAH_ADS = "mah_ads_log"
@JvmField val TAG_MAH_ADS_DLG_PROGRAMS = "tag_mah_ads_dlg_programs"
@JvmField val TAG_MAH_ADS_DLG_EXIT = "tag_mah_ads_dlg_exit"
}
|
apache-2.0
|
a8bce1fb39633f73295813c3a046b48a
| 41.416667 | 76 | 0.713163 | 2.976608 | false | false | false | false |
soywiz/korge
|
korge/src/commonMain/kotlin/com/soywiz/korge/view/tiles/TileSet.kt
|
1
|
7425
|
package com.soywiz.korge.view.tiles
import com.soywiz.kds.*
import com.soywiz.kds.iterators.*
import com.soywiz.klock.*
import com.soywiz.kmem.*
import com.soywiz.korge.view.*
import com.soywiz.korim.bitmap.*
import kotlin.math.*
data class TileSetAnimationFrame(
val tileId: Int,
val duration: TimeSpan,
)
data class TileSetTileInfo(
val id: Int,
val slice: BmpSlice,
val frames: List<TileSetAnimationFrame> = emptyList()
)
class TileSet(
val texturesMap: IntMap<TileSetTileInfo>,
//val textures: List<BmpSlice?>,
val width: Int = texturesMap.firstValue().slice.width,
val height: Int = texturesMap.firstValue().slice.height,
val collisionsMap: IntMap<TileShapeInfo> = IntMap(),
) {
val base: Bitmap by lazy { if (texturesMap.size == 0) Bitmaps.transparent.bmpBase else texturesMap.firstValue().slice.bmpBase }
val hasMultipleBaseBitmaps by lazy { texturesMap.values.any { it !== null && it.slice.bmpBase !== base } }
val infos by lazy { Array<TileSetTileInfo?>(texturesMap.keys.maxOrNull()?.plus(1) ?: 0) { texturesMap[it] } }
val textures by lazy { Array<BmpSlice?>(texturesMap.keys.maxOrNull()?.plus(1) ?: 0) { texturesMap[it]?.slice } }
val collisions by lazy { Array<TileShapeInfo?>(texturesMap.keys.maxOrNull()?.plus(1) ?: 0) { collisionsMap[it] } }
//init { if (hasMultipleBaseBitmaps) throw RuntimeException("All tiles in the set must have the same base texture") }
//init {
// println("texturesMap: ${texturesMap.toMap()}")
// println("textures: ${textures.size}")
//}
fun getInfo(index: Int): TileSetTileInfo? = infos.getOrNull(index)
fun getSlice(index: Int): BmpSlice? = getInfo(index)?.slice
operator fun get(index: Int): BmpSlice? = getSlice(index)
fun clone(): TileSet = TileSet(this.texturesMap.clone(), this.width, this.height)
companion object {
@Deprecated("")
operator fun invoke(
texturesMap: Map<Int, BmpSlice>,
width: Int = texturesMap.values.first().width,
height: Int = texturesMap.values.first().height,
collisionsMap: IntMap<TileShapeInfo> = IntMap(),
) = TileSet(texturesMap.map { (key, value) -> key to TileSetTileInfo(key, value) }.toMap().toIntMap(), width, height, collisionsMap)
operator fun invoke(
textureMap: Map<Int, TileSetTileInfo>,
collisionsMap: IntMap<TileShapeInfo> = IntMap(),
): TileSet = TileSet(textureMap.toIntMap(), collisionsMap = collisionsMap)
operator fun invoke(
tileSets: List<TileSet>,
collisionsMap: IntMap<TileShapeInfo> = IntMap(),
): TileSet {
val map = IntMap<TileSetTileInfo>()
tileSets.fastForEach { tileSet ->
map.putAll(tileSet.texturesMap)
}
return TileSet(map, collisionsMap = collisionsMap)
}
operator fun invoke(
tiles: List<TileSetTileInfo>,
width: Int, height: Int,
collisionsMap: IntMap<TileShapeInfo> = IntMap(),
): TileSet {
val map = IntMap<TileSetTileInfo>()
tiles.fastForEachWithIndex { index, value -> map[index] = value }
return TileSet(map, width, height, collisionsMap = collisionsMap)
}
operator fun invoke(
base: BitmapSlice<Bitmap>,
tileWidth: Int = base.width,
tileHeight: Int = base.height,
columns: Int = -1,
totalTiles: Int = -1,
collisionsMap: IntMap<TileShapeInfo> = IntMap(),
): TileSet {
val out = IntMap<TileSetTileInfo>()
val rows = base.height / tileHeight
val actualColumns = if (columns < 0) base.width / tileWidth else columns
val actualTotalTiles = if (totalTiles < 0) rows * actualColumns else totalTiles
var n = 0
complete@ for (y in 0 until rows) {
for (x in 0 until actualColumns) {
out[n] = TileSetTileInfo(n + 1, base.sliceWithSize(x * tileWidth, y * tileHeight, tileWidth, tileHeight))
n++
if (out.size >= actualTotalTiles) break@complete
}
}
return TileSet(out, tileWidth, tileHeight, collisionsMap = collisionsMap)
}
fun extractBmpSlices(
bmp: Bitmap32,
tilewidth: Int,
tileheight: Int,
columns: Int,
tilecount: Int,
spacing: Int,
margin :Int
): List<BitmapSlice<Bitmap32>> {
return ArrayList<BitmapSlice<Bitmap32>>().apply {
loop@ for (y in 0 until bmp.height / tileheight) {
for (x in 0 until columns) {
add(bmp.sliceWithSize(
margin + x * (tilewidth + spacing),
margin + y * (tileheight + spacing),
tilewidth, tileheight
))
if (this.size >= tilecount) break@loop
}
}
}
}
fun extractBitmaps(
bmp: Bitmap32,
tilewidth: Int,
tileheight: Int,
columns: Int,
tilecount: Int,
spacing: Int,
margin :Int
): List<Bitmap32> = extractBmpSlices(bmp, tilewidth, tileheight, columns, tilecount, spacing, margin).map { it.extract() }
fun fromBitmaps(
tilewidth: Int,
tileheight: Int,
bitmaps: List<Bitmap32>,
border: Int = 1,
mipmaps: Boolean = false,
collisionsMap: IntMap<TileShapeInfo> = IntMap(),
): TileSet {
return fromBitmapSlices(tilewidth, tileheight, bitmaps.map { it.slice() }, border, mipmaps, collisionsMap = collisionsMap)
}
fun fromBitmapSlices(
tilewidth: Int,
tileheight: Int,
bmpSlices: List<BitmapSlice<Bitmap32>>,
border: Int = 1,
mipmaps: Boolean = false,
collisionsMap: IntMap<TileShapeInfo> = IntMap(),
): TileSet {
check(bmpSlices.all { it.width == tilewidth && it.height == tileheight })
if (bmpSlices.isEmpty()) return TileSet(IntMap(), tilewidth, tileheight)
//sqrt(bitmaps.size.toDouble()).toIntCeil() * tilewidth
val border2 = border * 2
val btilewidth = tilewidth + border2
val btileheight = tileheight + border2
val barea = btilewidth * btileheight
val fullArea = bmpSlices.size.nextPowerOfTwo * barea
val expectedSide = sqrt(fullArea.toDouble()).toIntCeil().nextPowerOfTwo
val premultiplied = bmpSlices.any { it.premultiplied }
val out = Bitmap32(expectedSide, expectedSide, premultiplied = premultiplied).mipmaps(mipmaps)
val texs = IntMap<TileSetTileInfo>()
val columns = (out.width / btilewidth)
lateinit var tex: Bitmap
//val tex = views.texture(out, mipmaps = mipmaps)
var nn = 0
for (m in 0 until 2) {
for (n in 0 until bmpSlices.size) {
val y = n / columns
val x = n % columns
val px = x * btilewidth + border
val py = y * btileheight + border
if (m == 0) {
out.putSliceWithBorder(px, py, bmpSlices[n], border)
} else {
texs[nn] = TileSetTileInfo(nn, tex.sliceWithSize(px, py, tilewidth, tileheight, name = bmpSlices[n].name))
nn++
}
}
if (m == 0) {
tex = out
}
}
return TileSet(texs, tilewidth, tileheight, collisionsMap = collisionsMap)
}
}
}
|
apache-2.0
|
5ed2d395eee799029bbc7c4fc07debd0
| 35.757426 | 140 | 0.605118 | 3.974839 | false | false | false | false |
calvin-li/Quest
|
app/src/main/java/com/sandbox/calvin_li/quest/MainActivity.kt
|
1
|
7483
|
package com.sandbox.calvin_li.quest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Bundle
import android.os.Environment
import androidx.appcompat.app.AppCompatActivity
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.WindowManager
import android.widget.ListView
import com.beust.klaxon.JsonArray
import com.beust.klaxon.JsonObject
import com.beust.klaxon.Parser
import java.io.*
import android.content.Intent
import android.content.res.Configuration
import android.graphics.Color
import androidx.core.content.FileProvider
import android.graphics.drawable.GradientDrawable
import androidx.appcompat.app.AppCompatDelegate
class MainActivity : AppCompatActivity() {
private lateinit var questView: ListView
private var nightMode: Int = AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
internal companion object {
private const val questFileName: String = "quests.json"
private const val dayNightMode: String = "dayNightMode"
lateinit var questJson: JsonArray<JsonObject>
fun saveJson(context: Context) {
if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED){
val externalFile = File(context.getExternalFilesDir(null), questFileName)
if (!externalFile.createNewFile()) { Log.e("Quest error", "File not created") }
val externalWriteStream = FileOutputStream(externalFile)
externalWriteStream.write(questJson.toJsonString(true).toByteArray())
externalWriteStream.close()
}
}
internal fun loadQuestJson(context: Context){
val questStream: InputStream = try {
val externalFile = File(context.getExternalFilesDir(null), questFileName)
FileInputStream(externalFile)
} catch (ex: IOException) {
context.resources.openRawResource(R.raw.quests)
}
@Suppress("UNCHECKED_CAST")
questJson = Parser().parse(questStream) as JsonArray<JsonObject>
questStream.close()
}
internal fun inNightMode(context: Context) =
context.resources.configuration.uiMode.and(Configuration.UI_MODE_NIGHT_MASK) ==
Configuration.UI_MODE_NIGHT_YES
fun getNestedArray(indices: List<Int>): JsonObject {
var nestedObject: JsonObject = questJson[indices[0]]
for (i in 1 until indices.size) {
@Suppress("UNCHECKED_CAST")
nestedObject = (nestedObject[Quest.childLabel] as JsonArray<JsonObject>)[indices[i]]
}
return nestedObject
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when(item.itemId) {
R.id.action_add -> {
val editView = QuestOptionsDialogFragment.getDialogView(this)
editView.hint = "Add new subquest here"
val dialog = QuestOptionsDialogFragment.createDialog(this, editView, "Add subquest")
{ _, _ ->
loadQuestJson(this)
val newObject = JsonObject()
newObject[Quest.nameLabel] = editView.text.toString()
newObject[Quest.expandLabel] = true
newObject[Quest.checkedLabel] = false
questJson.add(newObject)
saveJson(this)
this.onResume()
}
dialog.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_MODE_CHANGED)
dialog.show()
editView.requestFocus()
}
R.id.action_json -> {
saveJson(this)
val jsonFile = File(this.getExternalFilesDir(null), questFileName)
val jsonUri = FileProvider.getUriForFile(
this,
BuildConfig.APPLICATION_ID + ".provider",
jsonFile)
val jsonIntent = Intent(Intent.ACTION_VIEW)
jsonIntent.setDataAndType(jsonUri, "text/plain")
jsonIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
jsonIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
startActivity(Intent.createChooser(jsonIntent, "Open with: "))
}
R.id.night_follow_system -> {
setDayNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
}
R.id.night_yes -> {
setDayNightMode(AppCompatDelegate.MODE_NIGHT_YES)
}
R.id.night_no -> {
setDayNightMode(AppCompatDelegate.MODE_NIGHT_NO)
}
R.id.night_auto -> {
setDayNightMode(AppCompatDelegate.MODE_NIGHT_AUTO)
}
}
return super.onOptionsItemSelected(item)
}
override fun onCreate(savedInstanceState: Bundle?) {
AppCompatDelegate.setDefaultNightMode(
getPreferences(Context.MODE_PRIVATE).getInt(
dayNightMode, AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM))
val questsChannel = NotificationChannel(
NotificationActionReceiver.channelId,
NotificationActionReceiver.channelId,
NotificationManager.IMPORTANCE_DEFAULT)
questsChannel.enableLights(false)
questsChannel.enableVibration(false)
(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)
.createNotificationChannel(questsChannel)
super.onCreate(savedInstanceState)
setContentView(R.layout.main)
}
override fun onResume() {
super.onResume()
loadQuestJson(this)
saveJson(this)
NotificationActionReceiver.createOverallNotification(this)
val notificationIndexList: MutableList<List<QuestState>> = mutableListOf()
(0 until questJson.size).forEach { notificationIndexList.add(listOf(QuestState(it, 0))) }
NotificationActionReceiver.saveIndexList(this, notificationIndexList)
NotificationActionReceiver.refreshNotifications(this)
questView = findViewById(R.id.top_view)
questView.isSmoothScrollbarEnabled = true
Configuration.UI_MODE_NIGHT_MASK
val bgColor = if (inNightMode()) R.color.primary_dark else Color.WHITE
val colors = intArrayOf(
bgColor,
getColor(R.color.groovy),
getColor(R.color.groovy),
bgColor)
questView.divider = GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT, colors)
questView.dividerHeight = resources.getDimension(R.dimen.custom_list_divider_height).toInt()
val adapter = CustomListAdapter(this)
questView.adapter = adapter
questView.onItemClickListener = adapter.onItemClickListener
}
private fun setDayNightMode(newMode: Int) {
val sharedPrefs = getPreferences(Context.MODE_PRIVATE)
with(sharedPrefs.edit()) {
nightMode = newMode
putInt(dayNightMode, nightMode)
apply()
}
recreate()
}
private fun inNightMode() = Companion.inNightMode(this)
}
|
mit
|
51fc12159fb8966d5502f0ce459bd52c
| 37.374359 | 100 | 0.637846 | 5.08356 | false | false | false | false |
openstreetview/android
|
app/src/main/java/com/telenav/osv/data/collector/phonedata/collector/PhoneCollector.kt
|
1
|
6312
|
package com.telenav.osv.data.collector.phonedata.collector
import android.os.Handler
import com.telenav.osv.data.collector.datatype.datatypes.BaseObject
import com.telenav.osv.data.collector.phonedata.manager.PhoneDataListener
import com.telenav.osv.data.collector.phonedata.util.MicrosecondsConverter
import com.telenav.osv.data.collector.phonedata.util.MillisecondsConverter
import com.telenav.osv.data.collector.phonedata.util.NanosecondsConverter
import com.telenav.osv.data.collector.phonedata.util.TimestampConverter
open class PhoneCollector(var phoneDataListener: PhoneDataListener?, var notifyHandler: Handler?) {
/**
* The time of the first sensor event
*/
private var firstSensorReadingTime: Long = 0
/**
* The time of the system when first value of a sensor is read
*/
private var firstSystemReadingTime: Long = 0
/**
* Flag used in order to determine if the sensor was registered and values are colected
*/
private var isCollectionStarted = false
/**
* Flag used in order to determine if unit time was calculated
*/
private var isUnitTimeDetermined = false
private var timestampConverter: TimestampConverter? = null
private var desiredDelay = Int.MIN_VALUE
private var previousEventTimestamp: Long = 0
/**
* Notify the client when a sensor is not available
*/
fun sendSensorUnavailabilityStatus(baseObject: BaseObject<*>) {
phoneDataListener?.let {
it.onSensorChanged(baseObject)
}
}
@Synchronized
fun onNewSensorEvent(baseObject: BaseObject<*>) {
phoneDataListener?.let {
if (passesFrequencyFilter(baseObject)) {
previousEventTimestamp = baseObject.timestamp
it.onSensorChanged(baseObject)
}
}
}
/**
* This method determines the timestamp converter for each sensor event based on two readings.
* The second reading is delayed with one second.
* @param timeForFirstReading Timestamp of the first sensor value
* @param timeAfterOneSecond Timestamp of the the sensor value read after one second
* @return The timestamp converter (MILISECONDS, MICROSECONDS, NANOSECONDS)
*/
@Synchronized
private fun getTimestampConverter(timeForFirstReading: Long, timeAfterOneSecond: Long): TimestampConverter {
val difference = timeAfterOneSecond - timeForFirstReading
return if (difference / NANO_DIVIDER > 1) { // verifies for nano (using as referece mili)
NanosecondsConverter(isCurrentTimestampInNano(timeAfterOneSecond))
} else if (difference / MICRO_DIVIDER > 1) { // verifies for micro (using as referece mili)
MicrosecondsConverter()
} else {
MillisecondsConverter()
}
}
/**
* This method is called from collectors. It reads the first value of a sensor and then waits one second
* before reading the second value. This delay is used in order to determine the time unit of a
* sensor event. After the time unit is determined this method sets the timestamp of a sensor event
* @param eventTimestamp The timestamp of a sensor event
* @param baseObject Sensor data
*/
@Synchronized
fun determineTimestamp(eventTimestamp: Long, baseObject: BaseObject<*>) {
if (isCollectionStarted) {
val currentTime = System.currentTimeMillis()
if (currentTime - firstSystemReadingTime >= ONE_SECOND_IN_MILLI && !isUnitTimeDetermined) {
isUnitTimeDetermined = true
timestampConverter = getTimestampConverter(firstSensorReadingTime, eventTimestamp)
}
timestampConverter?.let {
if (isUnitTimeDetermined) {
val timestamp: Long = it.getTimestamp(eventTimestamp)
if (timestamp > 0) {
baseObject.timestamp = timestamp
}
onNewSensorEvent(baseObject)
}
}
} else {
firstSensorReadingTime = eventTimestamp
firstSystemReadingTime = System.currentTimeMillis()
isCollectionStarted = true
}
}
/**
* This method checks if event (sensor) timestamp is the current timestamp in nanoseconds
* @param eventTimestampInNano Event timestamp
* @return True if the event timestamp is current timestamp in nanoseconds and false if not
*/
private fun isCurrentTimestampInNano(eventTimestampInNano: Long): Boolean {
return eventTimestampInNano / NANO_TO_MILLI > Y2015
}
fun setUpFrequencyFilter(delayMicroseconds: Int) {
desiredDelay = delayMicroseconds / 1000
}
private fun passesFrequencyFilter(baseObject: BaseObject<*>): Boolean {
return if (desiredDelay <= 0) {
true
} else baseObject.timestamp - previousEventTimestamp > desiredDelay
}
companion object {
/**
* The timestamp for end of year 2015. It is used in order to determine if the sensor event timestamp
* represents the current time in nanoseconds
*/
private const val Y2015 = 1450000000000L
/**
* Value used for converting nanoseconds to milliseconds
*/
private const val NANO_TO_MILLI: Long = 1000000
/**
* Represents the value of a second in milliseconds
*/
private const val ONE_SECOND_IN_MILLI = 1000
/**
* Value used for determining if the sensor event timestamp is in nanoseconds.
* NOTE: it is used 100_000_000 instead 1_000_000_000 which represents the correct value for transforming
* nanoseconds to seconds because sometimes the difference between the two readings is like: 999_999_983.
*/
private const val NANO_DIVIDER: Long = 100000000
/**
* Value used for determining if the sensor event timestamp is in microseconds.
* NOTE: it is used 100_000 instead 1_000_000 which represents the correct value for transforming
* microseconds to seconds because sometimes the difference between the two readings is like: 999_999.
*/
private const val MICRO_DIVIDER: Long = 100000
}
}
|
lgpl-3.0
|
db970948b9d997dd92b8840471c89b8b
| 39.210191 | 113 | 0.669835 | 4.962264 | false | false | false | false |
vondear/RxTools
|
RxDemo/src/main/java/com/tamsiree/rxdemo/view/RxDialogShopCart.kt
|
1
|
3955
|
package com.tamsiree.rxdemo.view
import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.tamsiree.rxdemo.R
import com.tamsiree.rxdemo.adapter.AdapterPopupDish
import com.tamsiree.rxdemo.interfaces.ShopCartInterface
import com.tamsiree.rxdemo.model.ModelShopCart
import kotlinx.android.synthetic.main.cart_popupview.*
/**
* @author tamsiree
* @date 16-12-22
*/
class RxDialogShopCart(context: Context?, private val mModelShopCart: ModelShopCart?, themeResId: Int) : Dialog(context!!, themeResId), View.OnClickListener, ShopCartInterface {
var shopCartDialogImp: ShopCartDialogImp? = null
override fun onCreate(savedInstanceState: Bundle) {
super.onCreate(savedInstanceState)
setContentView(R.layout.cart_popupview)
shopping_cart_layout?.setOnClickListener(this)
shopping_cart_bottom?.setOnClickListener(this)
clear_layout.setOnClickListener(this)
recycleview.layoutManager = LinearLayoutManager(context)
val dishAdapter = AdapterPopupDish(context, mModelShopCart!!)
recycleview.adapter = dishAdapter
dishAdapter.shopCartInterface = this
showTotalPrice()
}
override fun show() {
super.show()
animationShow(500)
}
override fun dismiss() {
animationHide(500)
}
@SuppressLint("SetTextI18n")
private fun showTotalPrice() {
if (mModelShopCart != null && mModelShopCart.shoppingTotalPrice > 0) {
shopping_cart_total_tv!!.visibility = View.VISIBLE
shopping_cart_total_tv!!.text = context.resources.getString(R.string.rmb) + " " + mModelShopCart.shoppingTotalPrice
shopping_cart_total_num!!.visibility = View.VISIBLE
shopping_cart_total_num!!.text = "" + mModelShopCart.shoppingAccount
} else {
shopping_cart_total_tv!!.visibility = View.GONE
shopping_cart_total_num!!.visibility = View.GONE
}
}
private fun animationShow(mDuration: Int) {
val animatorSet = AnimatorSet()
animatorSet.playTogether(
ObjectAnimator.ofFloat(linearlayout, "translationY", 1000f, 0f).setDuration(mDuration.toLong())
)
animatorSet.start()
}
private fun animationHide(mDuration: Int) {
val animatorSet = AnimatorSet()
animatorSet.playTogether(
ObjectAnimator.ofFloat(linearlayout, "translationY", 0f, 1000f).setDuration(mDuration.toLong())
)
animatorSet.start()
if (shopCartDialogImp != null) {
shopCartDialogImp!!.dialogDismiss()
}
animatorSet.addListener(object : Animator.AnimatorListener {
override fun onAnimationStart(animator: Animator) {}
override fun onAnimationEnd(animator: Animator) {
[email protected]()
}
override fun onAnimationCancel(animator: Animator) {}
override fun onAnimationRepeat(animator: Animator) {}
})
}
override fun onClick(view: View) {
when (view.id) {
R.id.shopping_cart_bottom, R.id.shopping_cart_layout -> dismiss()
R.id.clear_layout -> clear()
}
}
override fun add(view: View?, position: Int) {
showTotalPrice()
}
override fun remove(view: View?, position: Int) {
showTotalPrice()
if (mModelShopCart!!.shoppingAccount == 0) {
dismiss()
}
}
interface ShopCartDialogImp {
fun dialogDismiss()
}
fun clear() {
mModelShopCart!!.clear()
showTotalPrice()
if (mModelShopCart.shoppingAccount == 0) {
dismiss()
}
}
}
|
apache-2.0
|
8dbd901159aa92f3c0e8bd3a5779f68d
| 32.243697 | 177 | 0.661188 | 4.44382 | false | false | false | false |
werelord/nullpod
|
nullpodApp/src/main/kotlin/com/cyrix/util/XmlParser.kt
|
1
|
3653
|
/**
* XmlParser
*
* Copyright 2017 Joel Braun
*
* This file is part of nullPod.
*
* nullPod is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* nullPod is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with nullPod. If not, see <http://www.gnu.org/licenses/>.
*/
package com.cyrix.util
import android.util.Xml
import org.xmlpull.v1.XmlPullParser
import java.io.StringReader
import java.util.*
/**
* XmlParser class
* - manages tag stack and parser specifically
* - processXML cacan be called recursively, on specific tag node; will break recursive call when close tag encountered
* todo: unit tests
*/
class XmlParser(xml:String) {
private val tagStack = Stack<String>()
private val log = CxLogger<XmlParser>()
private val parser: XmlPullParser = Xml.newPullParser()
init {
// todo: expose these??
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false)
parser.setInput(StringReader(xml))
}
fun processXml(nodeTag: String = "",
onStartTag: (String) -> Unit = {},
onTagAttribute: (String, String, String) -> Unit = {_, _, _ -> },
onText: (String, String) -> Unit = {_, _ ->},
onEndTag: (String) -> Unit = {}) {
//log.function("endtag: '$nodeTag'")
var eventType = parser.next()
eventTypeLoop@ while (eventType != XmlPullParser.END_DOCUMENT) {
when (eventType) {
XmlPullParser.START_TAG -> {
//log.debug { "eventType: START_TAG, parser.name=${parser.name!!}" }
tagStack.push(parser.name)
onStartTag(parser.name)
if (parser.attributeCount > 0) {
for (i in 0 until parser.attributeCount) {
onTagAttribute(parser.name, parser.getAttributeName(i), parser.getAttributeValue(i))
}
}
}
XmlPullParser.TEXT -> {
//log.debug { "eventType: TEXT, parser.text=${parser.text!!}" }
onText(tagStack.peek(), parser.text)
}
XmlPullParser.END_TAG -> {
//log.debug { "eventType: END_TAG, parser.name=${parser.name!!}" }
val endTag = tagStack.pop()
assert((endTag == parser.name), {"End tag does not match start tag!!"})
onEndTag(parser.name)
}
else -> log.warn { "Unknown handling for event type: $eventType" }
}
eventType = parser.next()
// conditions for breaking out of the loop, if this is a recursive call:
// next event is end tag && it matches the start tag node of the recursive call
if ((nodeTag.isEmpty() == false) && ((eventType == XmlPullParser.END_TAG) && (parser.name?.toLowerCase() == nodeTag))) {
//log.debug { "End tag and parser name '${parser.name}' == $nodeTag, exiting loop!!" }
break@eventTypeLoop
}
}
//log.function("exit processXML, endtag: '$nodeTag'")
}
}
|
gpl-3.0
|
88718612268364d282b008e02d878e3e
| 35.89899 | 132 | 0.573775 | 4.41717 | false | false | false | false |
panpf/sketch
|
sketch/src/main/java/com/github/panpf/sketch/stateimage/ColorFetcher.kt
|
1
|
1858
|
/*
* Copyright (C) 2022 panpf <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.panpf.sketch.stateimage
import android.content.Context
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.core.content.res.ResourcesCompat
/**
* For getting the color
*/
interface ColorFetcher {
fun getColor(context: Context): Int
}
class IntColor(@ColorInt val color: Int) : ColorFetcher {
override fun getColor(context: Context): Int = color
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is IntColor) return false
if (color != other.color) return false
return true
}
override fun hashCode(): Int = color
override fun toString(): String = "IntColor($color)"
}
/**
* Get color from resource
*/
class ResColor(@ColorRes val resId: Int) : ColorFetcher {
override fun getColor(context: Context): Int =
ResourcesCompat.getColor(context.resources, resId, null)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ResColor) return false
if (resId != other.resId) return false
return true
}
override fun hashCode(): Int = resId
override fun toString(): String = "ResColor($resId)"
}
|
apache-2.0
|
a8cd0a474ad8c4208f64c82fc5930294
| 28.046875 | 75 | 0.696448 | 4.271264 | false | false | false | false |
citiususc/calendula
|
Calendula/src/main/java/es/usc/citius/servando/calendula/util/alerts/StockAlertHandler.kt
|
1
|
2906
|
/*
* Calendula - An assistant for personal medication management.
* Copyright (C) 2016 CITIUS - USC
*
* Calendula is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software. If not, see <http://www.gnu.org/licenses/>.
*/
package es.usc.citius.servando.calendula.util.alerts
import es.usc.citius.servando.calendula.CalendulaApp
import es.usc.citius.servando.calendula.database.DB
import es.usc.citius.servando.calendula.events.StockRunningOutEvent
import es.usc.citius.servando.calendula.persistence.Medicine
import es.usc.citius.servando.calendula.persistence.alerts.StockRunningOutAlert
import es.usc.citius.servando.calendula.util.PreferenceKeys
import es.usc.citius.servando.calendula.util.PreferenceUtils
import es.usc.citius.servando.calendula.util.stock.MedicineScheduleStockProvider
import es.usc.citius.servando.calendula.util.stock.StockCalculator
import org.joda.time.LocalDate
object StockAlertHandler {
@JvmStatic
fun checkStockAlerts(m: Medicine) {
if (m.stockManagementEnabled()) {
val stockEnd = StockCalculator.calculateStockEnd(
LocalDate.now(),
MedicineScheduleStockProvider(m),
m.stock!!
)
val stockAlertPref = Integer.parseInt(
PreferenceUtils.getString(
PreferenceKeys.SETTINGS_STOCK_ALERT_DAYS,
"-1"
)
)
val alerts =
DB.alerts().findByMedicineAndType(m, StockRunningOutAlert::class.java.canonicalName)
if (stockEnd is StockCalculator.StockEnd.OnDate && stockEnd.days < stockAlertPref && alerts.isEmpty()) {
// if there are no alerts but the stock is under the preference, create them
AlertManager.createAlert(StockRunningOutAlert(m, LocalDate.now()))
CalendulaApp.eventBus().post(StockRunningOutEvent(m, stockEnd.days))
} else if (alerts.isNotEmpty() && ((stockEnd is StockCalculator.StockEnd.OnDate && stockEnd.days >= stockAlertPref) || stockEnd == StockCalculator.StockEnd.OverMax)) {
// if there are alerts but the stock is over the pref (or over the max) remove them
for (a in alerts) {
AlertManager.removeAlert(a)
}
}
}
}
}
|
gpl-3.0
|
de4b2f200e3f9457c5151f2dd3118264
| 41.735294 | 179 | 0.675843 | 4.337313 | false | false | false | false |
vanita5/twittnuker
|
twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/AbsToolbarTabPagesFragment.kt
|
1
|
11493
|
/*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.fragment
import android.content.Context
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentActivity
import android.support.v4.view.OnApplyWindowInsetsListener
import android.support.v4.view.ViewPager.OnPageChangeListener
import android.support.v7.widget.Toolbar
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_toolbar_tab_pages.*
import kotlinx.android.synthetic.main.fragment_toolbar_tab_pages.view.*
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.activity.LinkHandlerActivity
import de.vanita5.twittnuker.activity.LinkHandlerActivity.HideUiOnScroll
import de.vanita5.twittnuker.activity.iface.IControlBarActivity
import de.vanita5.twittnuker.activity.iface.IControlBarActivity.ControlBarOffsetListener
import de.vanita5.twittnuker.adapter.SupportTabsAdapter
import de.vanita5.twittnuker.constant.IntentConstants.EXTRA_INITIAL_TAB
import de.vanita5.twittnuker.constant.KeyboardShortcutConstants.*
import de.vanita5.twittnuker.fragment.iface.IBaseFragment
import de.vanita5.twittnuker.fragment.iface.IToolBarSupportFragment
import de.vanita5.twittnuker.fragment.iface.RefreshScrollTopInterface
import de.vanita5.twittnuker.fragment.iface.SupportFragmentCallback
import de.vanita5.twittnuker.util.KeyboardShortcutsHandler
import de.vanita5.twittnuker.util.KeyboardShortcutsHandler.KeyboardShortcutCallback
import de.vanita5.twittnuker.util.ThemeUtils
import de.vanita5.twittnuker.view.TabPagerIndicator
import de.vanita5.twittnuker.view.iface.IExtendedView
abstract class AbsToolbarTabPagesFragment : BaseFragment(), RefreshScrollTopInterface,
SupportFragmentCallback, IBaseFragment.SystemWindowInsetsCallback, ControlBarOffsetListener,
HideUiOnScroll, OnPageChangeListener, IToolBarSupportFragment, KeyboardShortcutCallback {
protected lateinit var pagerAdapter: SupportTabsAdapter
override val toolbar: Toolbar
get() = toolbarContainer.toolbar
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val activity = activity
pagerAdapter = SupportTabsAdapter(activity, childFragmentManager, null)
viewPager.adapter = pagerAdapter
viewPager.offscreenPageLimit = 2
viewPager.addOnPageChangeListener(this)
toolbarTabs.setViewPager(viewPager)
toolbarTabs.setTabDisplayOption(TabPagerIndicator.DisplayOption.LABEL)
tabPagesFragmentView.applyWindowInsetsListener = OnApplyWindowInsetsListener listener@ { _, insets ->
val top = insets.systemWindowInsetTop
tabPagesFragmentView.setPadding(0, top, 0, 0)
return@listener insets
}
addTabs(pagerAdapter)
toolbarTabs.notifyDataSetChanged()
toolbarContainer.onSizeChangedListener = object : IExtendedView.OnSizeChangedListener {
override fun onSizeChanged(view: View, w: Int, h: Int, oldw: Int, oldh: Int) {
val pageLimit = viewPager.offscreenPageLimit
val currentItem = viewPager.currentItem
val count = pagerAdapter.count
for (i in 0 until count) {
if (i > currentItem - pageLimit - 1 || i < currentItem + pageLimit) {
val obj = pagerAdapter.instantiateItem(viewPager, i)
if (obj is IBaseFragment<*>) {
obj.requestApplyInsets()
}
}
}
}
}
if (savedInstanceState == null) {
val initialTab = arguments?.getString(EXTRA_INITIAL_TAB)
if (initialTab != null) {
for (i in 0 until pagerAdapter.count) {
if (initialTab == pagerAdapter.get(i).tag) {
viewPager.currentItem = i
break
}
}
}
}
}
protected abstract fun addTabs(adapter: SupportTabsAdapter)
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is IControlBarActivity) {
context.registerControlBarOffsetListener(this)
}
}
override fun onDetach() {
val activity = activity
if (activity is IControlBarActivity) {
activity.unregisterControlBarOffsetListener(this)
}
super.onDetach()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_toolbar_tab_pages, container, false)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
val o = pagerAdapter.instantiateItem(viewPager, viewPager.currentItem)
o.onActivityResult(requestCode, resultCode, data)
}
override fun scrollToStart(): Boolean {
val fragment = currentVisibleFragment as? RefreshScrollTopInterface ?: return false
fragment.scrollToStart()
return true
}
override fun triggerRefresh(): Boolean {
return false
}
override val currentVisibleFragment: Fragment?
get() {
val currentItem = viewPager.currentItem
if (currentItem < 0 || currentItem >= pagerAdapter.count) return null
return pagerAdapter.instantiateItem(viewPager, currentItem)
}
override fun triggerRefresh(position: Int): Boolean {
return false
}
override fun onApplySystemWindowInsets(insets: Rect) {
}
override fun getSystemWindowInsets(caller: Fragment, insets: Rect): Boolean {
insetsCallback?.getSystemWindowInsets(this, insets)
val height = toolbarContainer.height
if (height != 0) {
insets.top = height
} else {
insets.top = ThemeUtils.getActionBarHeight(context)
}
return true
}
override fun onControlBarOffsetChanged(activity: IControlBarActivity, offset: Float) {
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
}
override fun onPageSelected(position: Int) {
}
override fun onPageScrollStateChanged(state: Int) {
val activity = activity
if (activity is LinkHandlerActivity) {
activity.setControlBarVisibleAnimate(true)
}
}
override var controlBarOffset: Float
get() {
if (toolbarContainer == null) return 0f
return 1 + toolbarContainer.translationY / controlBarHeight
}
set(offset) {
if (toolbarContainer == null) return
val translationY = (offset - 1) * controlBarHeight
toolbarContainer.translationY = translationY
windowOverlay!!.translationY = translationY
}
override val controlBarHeight: Int
get() = toolbar.measuredHeight
override fun setupWindow(activity: FragmentActivity): Boolean {
return false
}
override fun handleKeyboardShortcutSingle(handler: KeyboardShortcutsHandler, keyCode: Int, event: KeyEvent, metaState: Int): Boolean {
if (handleFragmentKeyboardShortcutSingle(handler, keyCode, event, metaState)) return true
val action = handler.getKeyAction(CONTEXT_TAG_NAVIGATION, keyCode, event, metaState)
if (action != null) {
when (action) {
ACTION_NAVIGATION_PREVIOUS_TAB -> {
val previous = viewPager.currentItem - 1
if (previous >= 0 && previous < pagerAdapter.count) {
viewPager.setCurrentItem(previous, true)
}
return true
}
ACTION_NAVIGATION_NEXT_TAB -> {
val next = viewPager.currentItem + 1
if (next >= 0 && next < pagerAdapter.count) {
viewPager.setCurrentItem(next, true)
}
return true
}
}
}
return handler.handleKey(activity, null, keyCode, event, metaState)
}
override fun isKeyboardShortcutHandled(handler: KeyboardShortcutsHandler, keyCode: Int,
event: KeyEvent, metaState: Int): Boolean {
if (isFragmentKeyboardShortcutHandled(handler, keyCode, event, metaState)) return true
val action = handler.getKeyAction(CONTEXT_TAG_NAVIGATION, keyCode, event, metaState)
return ACTION_NAVIGATION_PREVIOUS_TAB == action || ACTION_NAVIGATION_NEXT_TAB == action
}
override fun handleKeyboardShortcutRepeat(handler: KeyboardShortcutsHandler, keyCode: Int,
repeatCount: Int, event: KeyEvent, metaState: Int): Boolean {
return handleFragmentKeyboardShortcutRepeat(handler, keyCode, repeatCount, event, metaState)
}
private val keyboardShortcutRecipient: Fragment?
get() = currentVisibleFragment
private fun handleFragmentKeyboardShortcutRepeat(handler: KeyboardShortcutsHandler, keyCode: Int,
repeatCount: Int, event: KeyEvent, metaState: Int): Boolean {
val fragment = keyboardShortcutRecipient
if (fragment is KeyboardShortcutCallback) {
return fragment.handleKeyboardShortcutRepeat(handler, keyCode,
repeatCount, event, metaState)
}
return false
}
private fun handleFragmentKeyboardShortcutSingle(handler: KeyboardShortcutsHandler, keyCode: Int,
event: KeyEvent, metaState: Int): Boolean {
val fragment = keyboardShortcutRecipient
if (fragment is KeyboardShortcutCallback) {
return fragment.handleKeyboardShortcutSingle(handler, keyCode,
event, metaState)
}
return false
}
private fun isFragmentKeyboardShortcutHandled(handler: KeyboardShortcutsHandler, keyCode: Int,
event: KeyEvent, metaState: Int): Boolean {
val fragment = keyboardShortcutRecipient
if (fragment is KeyboardShortcutCallback) {
return fragment.isKeyboardShortcutHandled(handler, keyCode,
event, metaState)
}
return false
}
}
|
gpl-3.0
|
a48a0f5cc02ea806631c9563d37f0a0a
| 39.903915 | 138 | 0.668842 | 5.17936 | false | false | false | false |
stripe/stripe-android
|
payments-core/src/test/java/com/stripe/android/model/CustomerTest.kt
|
1
|
3514
|
package com.stripe.android.model
import com.google.common.truth.Truth.assertThat
import com.stripe.android.model.parsers.CustomerJsonParser
import org.json.JSONObject
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
/**
* Test class for [Customer] model object.
*/
class CustomerTest {
@Test
fun fromJson_whenNotACustomer_returnsNull() {
assertThat(parse(NON_CUSTOMER_OBJECT))
.isNull()
}
@Test
fun fromJson_whenCustomer_returnsExpectedCustomer() {
val customer = CustomerFixtures.CUSTOMER
assertNotNull(customer)
assertEquals("cus_AQsHpvKfKwJDrF", customer.id)
assertEquals("abc123", customer.defaultSource)
assertNull(customer.shippingInformation)
assertNotNull(customer.sources)
assertEquals("/v1/customers/cus_AQsHpvKfKwJDrF/sources", customer.url)
assertFalse(customer.hasMore)
assertEquals(0, customer.totalCount)
}
@Test
fun fromJson_whenCustomerHasApplePay_returnsCustomerWithoutApplePaySources() {
val customer = parse(createTestCustomerObjectWithApplePaySource())
assertNotNull(customer)
assertThat(customer.sources)
.hasSize(2)
// Note that filtering the apple_pay sources intentionally does not change the total
// count value.
assertEquals(5, customer.totalCount)
}
@Test
fun fromJson_createsSameObject() {
val expectedCustomer = parse(CustomerFixtures.CUSTOMER_JSON)
assertNotNull(expectedCustomer)
assertEquals(
expectedCustomer,
parse(CustomerFixtures.CUSTOMER_JSON)
)
}
private fun createTestCustomerObjectWithApplePaySource(): JSONObject {
val rawJsonCustomer = CustomerFixtures.CUSTOMER_JSON
val sourcesObject = rawJsonCustomer.getJSONObject("sources")
val sourcesArray = sourcesObject.getJSONArray("data").apply {
put(SourceFixtures.APPLE_PAY)
// Note that we don't yet explicitly support bitcoin sources, but this data is
// convenient for the test because it is not an apple pay source.
put(SourceFixtures.CUSTOMER_SOURCE_CARD_JSON)
put(SourceFixtures.ALIPAY_JSON)
put(JSONObject(CardFixtures.CARD_USD_JSON.toString()))
put(
JSONObject(CardFixtures.CARD_USD_JSON.toString()).apply {
put("id", "card_id55555")
put("tokenization_method", "apple_pay")
}
)
}
rawJsonCustomer.put(
"sources",
sourcesObject
.put("data", sourcesArray)
.put("total_count", 5)
)
// Verify JSON manipulation
assertEquals(
5,
rawJsonCustomer.getJSONObject("sources").getJSONArray("data").length()
)
return JSONObject(rawJsonCustomer.toString())
}
private companion object {
private val NON_CUSTOMER_OBJECT = JSONObject(
"""
{
"object": "not_a_customer",
"has_more": false,
"total_count": 22,
"url": "http://google.com"
}
""".trimIndent()
)
private fun parse(jsonObject: JSONObject): Customer? {
return CustomerJsonParser().parse(jsonObject)
}
}
}
|
mit
|
5641c90ef9eaf0edd144bec394a3f9a1
| 31.238532 | 92 | 0.624929 | 4.807114 | false | true | false | false |
rinp/study
|
base/src/main/kotlin/base/entity.kt
|
1
|
1365
|
package base
import com.fasterxml.jackson.annotation.JsonIgnore
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.userdetails.UserDetails
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.Id
@Entity
//@EntityListeners(*arrayOf(AuditingEntityListener::class))
data class Account(
@Id
@GeneratedValue
var id: Long? = null,
@Column(unique = true)
val accountName: String = "",
private val password: String = "",
@Column(unique = true)
val email: String = ""
// @CreatedBy
// val creator: String = "",
//
// @LastModifiedBy
// val lastModifier: String = ""
) : UserDetails {
override fun getAuthorities(): Collection<out GrantedAuthority> = emptyList()
@JsonIgnore
override fun getUsername(): String {
return this.accountName
}
@JsonIgnore
override fun getPassword(): String {
return this.password
}
// 以下は現状はまだ利用しない
@JsonIgnore
override fun isAccountNonExpired() = true
@JsonIgnore
override fun isAccountNonLocked() = true
@JsonIgnore
override fun isCredentialsNonExpired() = true
@JsonIgnore
override fun isEnabled() = true
}
|
mit
|
bfd234056f7b0a7885e810c23e29a9b2
| 21.333333 | 81 | 0.674384 | 4.617241 | false | false | false | false |
FDeityLink/KeroEdit
|
src/io/fdeitylink/util/Logger.kt
|
1
|
1233
|
/*
* TODO:
* Deprecate this in favor of standard java.util.logging system
*/
package io.fdeitylink.util
import java.util.logging.LogRecord
import java.util.logging.FileHandler
import java.util.logging.Level
import java.io.IOException
import java.io.PrintWriter
import java.io.StringWriter
object Logger {
fun logMessage(message: String, logFile: String = "error.log") {
try {
val handle = FileHandler(logFile)
handle.publish(LogRecord(Level.ALL, message))
handle.close()
}
catch (except: IOException) {
System.err.println(message)
}
}
@JvmOverloads
fun logThrowable(message: String = "", t: Throwable, logFile: String = "error.log") {
val writer = StringWriter()
writer.append(message).append('\n')
writer.append("${t.javaClass.name}: ${t.message}")
t.printStackTrace(PrintWriter(writer))
val finalMessage = writer.toString()
try {
val handle = FileHandler(logFile)
handle.publish(LogRecord(Level.ALL, finalMessage))
handle.close()
}
catch (except: IOException) {
System.err.println(finalMessage)
}
}
}
|
apache-2.0
|
ad15dd19cd88a87515c37d7df7851847
| 25.255319 | 89 | 0.620438 | 4.179661 | false | false | false | false |
Undin/intellij-rust
|
src/main/kotlin/org/rust/cargo/toolchain/ProxyHelper.kt
|
4
|
940
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.toolchain
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.util.net.HttpConfigurable
import java.net.URI
fun withProxyIfNeeded(cmdLine: GeneralCommandLine, http: HttpConfigurable) {
if (http.USE_HTTP_PROXY && http.PROXY_HOST.isNotEmpty()) {
cmdLine.withEnvironment("http_proxy", http.proxyUri.toString())
}
}
private val HttpConfigurable.proxyUri: URI
get() {
var userInfo: String? = null
if (PROXY_AUTHENTICATION && !proxyLogin.isNullOrEmpty() && plainProxyPassword != null) {
val login = proxyLogin
val password = plainProxyPassword!!
userInfo = if (password.isNotEmpty()) "$login:$password" else login
}
return URI("http", userInfo, PROXY_HOST, PROXY_PORT, "/", null, null)
}
|
mit
|
31d107abcc0b1d42a963ae2374ab52d0
| 33.814815 | 96 | 0.685106 | 4.177778 | false | true | false | false |
McGars/basekitk
|
basekitk/src/main/kotlin/com/mcgars/basekitk/features/recycler/SpacesItemDecoration.kt
|
1
|
853
|
package com.mcgars.basekitk.features.recycler
import android.graphics.Rect
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.view.View
class SpacesItemDecoration(private val space: Int, private val orientation: Int = LinearLayoutManager.VERTICAL) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
outRect.right = space
outRect.bottom = space
// Add top margin only for the first item to avoid double space between items
if (parent.getChildAdapterPosition(view) == 0) {
if (orientation == LinearLayoutManager.VERTICAL)
outRect.top = space
else {
outRect.left = space
}
}
}
}
|
apache-2.0
|
867b329f4d65fcb43d24dc9f77c7c811
| 36.130435 | 145 | 0.694021 | 5.047337 | false | false | false | false |
kamerok/Orny
|
app/src/main/kotlin/com/kamer/orny/data/google/model/GoogleExpense.kt
|
1
|
3052
|
package com.kamer.orny.data.google.model
import android.text.format.DateUtils
import com.google.api.services.sheets.v4.model.CellData
import com.google.api.services.sheets.v4.model.CellFormat
import com.google.api.services.sheets.v4.model.ExtendedValue
import com.google.api.services.sheets.v4.model.NumberFormat
import com.kamer.orny.data.google.GoogleRepoImpl
import com.kamer.orny.utils.dayStart
import java.lang.IllegalArgumentException
import java.util.*
data class GoogleExpense(
val row: Int,
val comment: String?,
val date: Date?,
val isOffBudget: Boolean,
val values: List<Double>
) {
companion object {
fun fromList(rowNumber: Int, list: MutableList<Any>): GoogleExpense {
val comment = list[0].toString()
val date = try {
GoogleRepoImpl.DATE_FORMAT.parse(list[1].toString())
} catch (e: IllegalArgumentException) {
null
}
val isOffBudget = list[2].toString() == "1"
val values = list
.takeLast(list.size - 3)
.map { it.toString() }
.map { it.toDoubleOrNull() ?: 0.0 }
return GoogleExpense(
row = rowNumber,
comment = comment,
date = date,
isOffBudget = isOffBudget,
values = values
)
}
}
fun toCells(): MutableList<CellData> {
val cellsData: MutableList<CellData> = mutableListOf()
cellsData.add(CellData().apply { userEnteredValue = ExtendedValue().setStringValue(comment ?: "") })
if (date == null) {
cellsData.add(CellData().apply { userEnteredValue = ExtendedValue().setStringValue("") })
} else {
val startCalendar = Calendar.getInstance().apply { set(1899, Calendar.DECEMBER, 29) }
val current = Calendar.getInstance().apply { timeInMillis = date.time }
val days: Double = daysBetween(startCalendar, current).toDouble()
cellsData.add(CellData().apply {
userEnteredValue = ExtendedValue().setNumberValue(days)
userEnteredFormat = CellFormat().setNumberFormat(NumberFormat().setType("DATE"))
})
}
cellsData.add(CellData().apply { userEnteredValue = ExtendedValue().setNumberValue(if (isOffBudget) 1.0 else 0.0) })
values.forEach { value ->
if (value == 0.0) {
cellsData.add(CellData().apply { userEnteredValue = ExtendedValue().setStringValue("") })
} else {
cellsData.add(CellData().apply { userEnteredValue = ExtendedValue().setNumberValue(value) })
}
}
return cellsData
}
private fun daysBetween(c1: Calendar, c2: Calendar): Int {
val day1 = c1.dayStart().timeInMillis / DateUtils.DAY_IN_MILLIS
val day2 = c2.dayStart().timeInMillis / DateUtils.DAY_IN_MILLIS
return (day2 - day1).toInt()
}
}
|
apache-2.0
|
2486ad1d38242f69e60e1bc927e7752d
| 39.171053 | 124 | 0.59633 | 4.341394 | false | false | false | false |
jooby-project/jooby
|
jooby/src/test/kotlin/io/jooby/Idioms.kt
|
1
|
3105
|
/*
* Jooby https://jooby.io
* Apache License Version 2.0 https://jooby.io/LICENSE.txt
* Copyright 2014 Edgar Espina
*/
package io.jooby
import io.jooby.RouterOption.IGNORE_CASE
import io.jooby.RouterOption.IGNORE_TRAILING_SLASH
import java.nio.file.Paths
import java.time.Duration
import kotlinx.coroutines.delay
/**
* Kotlin DLS in action, this class does nothing but we need it to make sure Kotlin version compiles
* sucessfully.
*/
class Idioms :
Kooby({
/** Services: */
val s = require<Jooby>()
println(s)
val named = require<Jooby>("name")
println(named)
val sklass = require(Jooby::class)
println(sklass)
val sklassname = require(Jooby::class, "name")
println(sklassname)
val j1 = services.get(Jooby::class)
println(j1)
val j2 = services.getOrNull(Jooby::class)
println(j2)
/** Options: */
serverOptions {
bufferSize = 8194
ioThreads = 8
gzip = true
defaultHeaders = false
maxRequestSize = 8000
port = 8080
server = "server"
workerThreads = 99
securePort = 8443
ssl = SslOptions().apply { cert = "/path/to/certificate.crt" }
}
routerOptions(IGNORE_CASE, IGNORE_TRAILING_SLASH)
setHiddenMethod { ctx -> ctx.header("").toOptional() }
environmentOptions {
this.activeNames = listOf("foo")
this.basedir = Paths.get(".").toString()
this.filename = "myfile"
}
val cors = cors {
this.exposedHeaders = listOf("f")
this.headers = listOf("d")
this.maxAge = Duration.ZERO
this.methods = listOf("GET")
this.origin = listOf("*")
this.useCredentials = true
}
println(cors)
/** Value DSL: */
get("/") {
val query = ctx.query()
val name: String by ctx.query
val n1 = query["name"].value()
val n2 = query[0].value()
val n3 = query.to<Int>()
val n4 = ctx.query["name"] to Int::class
val n5 = ctx.form("name") to String::class
val n6 = query.to(Int::class)
println(n1 + n2 + n3 + n4 + n5 + name + n6)
ctx
}
get("/attributes") { "some" }.attribute("k", "v")
/** Router DSL: */
before { ctx.path() }
after { ctx.getRequestPath() }
use { next.apply(ctx) }
get("/") { ctx.path() }
post("/") { ctx.path() }
put("/") { ctx.path() }
patch("/") { ctx.path() }
delete("/") { ctx.path() }
options("/") { ctx.path() }
trace("/") { ctx.path() }
// mvc
mvc(IdiomsController::class)
mvc(IdiomsController::class, ::IdiomsController)
/** Coroutine: */
coroutine {
get("/") { "Hi Kotlin!" }
get("/suspend") {
delay(100)
"Hi Coroutine"
}
get("/ctx-access") { ctx.getRequestPath() }
}
install(::SubApp)
install("/with-path", ::SubApp)
/** WebSocket: */
ws("/ws") {
configurer.onConnect { ws -> ws.send("SS") }
configurer.onMessage { ws, message ->
val value = message.to<IdiomsPojo>()
ws.render(value)
}
}
})
class IdiomsController {}
class IdiomsPojo {}
|
apache-2.0
|
adfcd96ad20c52b090e852948c502b82
| 22 | 100 | 0.575201 | 3.589595 | false | false | false | false |
odd-poet/kotlin-expect
|
src/main/kotlin/net/oddpoet/expect/ErrorExpectation.kt
|
1
|
1765
|
package net.oddpoet.expect
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import kotlin.reflect.KClass
/**
* Expectation of error.
*
* it's catch given block and test the exception.
*
* @author Yunsang Choi
*/
class ErrorExpectation
internal constructor(block: () -> Unit) {
// execute and catch
private val thrown: Throwable? = try {
block()
null
} catch (e: Throwable) {
e
}
private val log: Logger = LoggerFactory.getLogger(this.javaClass)
/**
* Test type of exception.
*
* Caught exception should be instance of given expection class.
* if not, it will throw AssertionError.
*
*/
fun <T : Throwable> throws(exceptionClass: KClass<out T>,
clause: (T) -> Unit = {}) {
if (thrown == null) {
log.debug("No exception had been thrown : FAIL")
throw AssertionError("expected to occur a exception<$exceptionClass> but no exception was thrown.")
}
if (!exceptionClass.isInstance(thrown)) {
log.debug("${thrown.literal} has been thrown, but expected <$exceptionClass> : FAIL")
throw AssertionError("expected <$exceptionClass> to be thrown, but <${thrown::class}> was thrown.", thrown)
}
log.debug("${thrown.literal} has been thrown (expected:<$exceptionClass>) : OK")
@Suppress("UNCHECKED_CAST")
clause(thrown as T)
}
/**
* short-cut method.
*
*/
fun throws(clause: (Exception) -> Unit = {}) {
throws(Exception::class, clause)
}
// Expect class scoped extension (for print object in assertion message)
internal val <X : Any?> X.literal: String
get() = Literalizer.literal(this)
}
|
apache-2.0
|
00407564d4249b476591e1910f50d91d
| 28.932203 | 119 | 0.606799 | 4.304878 | false | false | false | false |
kenrube/Fantlab-client
|
app/src/main/kotlin/ru/fantlab/android/ui/modules/settings/category/SettingsCategoryActivity.kt
|
2
|
1243
|
package ru.fantlab.android.ui.modules.settings.category
import android.app.Activity
import android.os.Bundle
import com.evernote.android.state.State
import ru.fantlab.android.R
import ru.fantlab.android.helper.BundleConstant
import ru.fantlab.android.ui.base.BaseActivity
class SettingsCategoryActivity : BaseActivity<SettingsCategoryMvp.View, SettingsCategoryPresenter>(), SettingsCategoryFragment.SettingsCallback {
@State var title: String? = null
@State @JvmField var settingsType: Int = 0
override fun layout(): Int = R.layout.activity_settings_category
override fun isTransparent() = false
override fun canBack() = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setResult(Activity.RESULT_CANCELED)
if (savedInstanceState == null) {
val bundle = intent.extras
title = bundle.getString(BundleConstant.EXTRA)
settingsType = bundle.getInt(BundleConstant.ITEM)
supportFragmentManager
.beginTransaction()
.replace(R.id.settingsContainer, SettingsCategoryFragment(), SettingsCategoryFragment.TAG)
.commit()
}
setTitle(title)
}
override fun providePresenter() = SettingsCategoryPresenter()
override fun getSettingsType(): Int = settingsType
}
|
gpl-3.0
|
fbc4c2467a512e7c0051f22ece211030
| 30.075 | 145 | 0.786002 | 4.256849 | false | false | false | false |
teobaranga/T-Tasks
|
t-tasks/src/main/java/com/teo/ttasks/ui/task_detail/TaskDetailViewModel.kt
|
1
|
1872
|
package com.teo.ttasks.ui.task_detail
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.teo.ttasks.data.local.WidgetHelper
import com.teo.ttasks.data.model.Task
import com.teo.ttasks.data.model.TaskList
import com.teo.ttasks.data.remote.TasksHelper
import com.teo.ttasks.ui.base.RealmViewModel
import com.teo.ttasks.util.NotificationHelper
import org.koin.core.KoinComponent
import org.koin.core.inject
class TaskDetailViewModel : RealmViewModel(), KoinComponent {
private val notificationHelper: NotificationHelper by inject()
private val tasksHelper: TasksHelper by inject()
private val widgetHelper: WidgetHelper by inject()
private val _task: MutableLiveData<Task> = MutableLiveData()
private val _taskList: MutableLiveData<TaskList> = MutableLiveData()
val task: LiveData<Task>
get() = _task
val taskList: LiveData<TaskList>
get() = _taskList
fun loadTask(taskId: String) {
val task = tasksHelper.getTask(taskId, realm)
task?.addChangeListener { t: Task ->
if (t.isLoaded && t.isValid) {
_task.value = t
}
}
}
fun loadTaskList(taskListId: String) {
val taskList = tasksHelper.getTaskList(taskListId, realm)
taskList?.addChangeListener { t: TaskList ->
if (t.isLoaded && t.isValid) {
_taskList.value = t
}
}
}
fun updateCompletionStatus() {
_task.value?.let {
tasksHelper.updateCompletionStatus(it, realm)
// Trigger a widget update
widgetHelper.updateWidgets(it.taskListId)
// Reschedule the reminder if going from completed -> active
if (!it.isCompleted) {
notificationHelper.scheduleTaskNotification(it)
}
}
}
}
|
apache-2.0
|
cbcbaed7c4fb89498a920e607e7f40c1
| 28.25 | 72 | 0.657051 | 4.46778 | false | false | false | false |
westnordost/StreetComplete
|
app/src/main/java/de/westnordost/streetcomplete/quests/diet_type/AddDietTypeForm.kt
|
1
|
1512
|
package de.westnordost.streetcomplete.quests.diet_type
import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.quests.AbstractQuestAnswerFragment
import de.westnordost.streetcomplete.quests.diet_type.DietAvailability.*
import kotlinx.android.synthetic.main.quest_buttonpanel_yes_no_only.*
import kotlinx.android.synthetic.main.quest_diet_type_explanation.*
class AddDietTypeForm : AbstractQuestAnswerFragment<DietAvailability>() {
override val contentLayoutResId = R.layout.quest_diet_type_explanation
override val buttonsResId = R.layout.quest_buttonpanel_yes_no_only
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
yesButton.setOnClickListener { applyAnswer(DIET_YES) }
noButton.setOnClickListener { applyAnswer(DIET_NO) }
onlyButton.setOnClickListener { applyAnswer(DIET_ONLY) }
val resId = arguments?.getInt(ARG_DIET) ?: 0
if (resId > 0) {
descriptionLabel.setText(resId)
} else {
descriptionLabel.visibility = View.GONE
}
}
companion object {
private const val ARG_DIET = "diet_explanation"
fun create(dietExplanationResId: Int): AddDietTypeForm {
val form = AddDietTypeForm()
form.arguments = bundleOf(ARG_DIET to dietExplanationResId)
return form
}
}
}
|
gpl-3.0
|
93cbb71d3a75cd62fffa3cf492652dec
| 35 | 74 | 0.721561 | 4.513433 | false | false | false | false |
rhdunn/xquery-intellij-plugin
|
src/plugin-api/main/uk/co/reecedunn/intellij/plugin/processor/query/settings/QueryProcessors.kt
|
1
|
3011
|
/*
* Copyright (C) 2018 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.processor.query.settings
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.xmlb.XmlSerializerUtil
import uk.co.reecedunn.intellij.plugin.processor.query.QueryProcessorSettings
@State(name = "XIJPQueryProcessors", storages = [Storage("xijp_processors_config.xml")])
class QueryProcessors : PersistentStateComponent<QueryProcessorsData> {
private val data = QueryProcessorsData()
// region Processors Event Listener
private val queryProcessorsListeners = ContainerUtil.createLockFreeCopyOnWriteList<QueryProcessorsListener>()
fun addQueryProcessorsListener(listener: QueryProcessorsListener) {
queryProcessorsListeners.add(listener)
}
fun removeQueryResultListener(listener: QueryProcessorsListener) {
queryProcessorsListeners.add(listener)
}
// endregion
// region Processors
val processors: List<QueryProcessorSettings>
get() = data.processors
fun addProcessor(processor: QueryProcessorSettings) {
(processors as ArrayList<QueryProcessorSettings>).add(processor)
data.currentProcessorId++
processor.id = data.currentProcessorId
queryProcessorsListeners.forEach { it.onAddProcessor(processor) }
}
fun setProcessor(index: Int, processor: QueryProcessorSettings) {
val id = processors[index].id
(processors as ArrayList<QueryProcessorSettings>)[index] = processor
processor.id = id
queryProcessorsListeners.forEach { it.onEditProcessor(index, processor) }
}
fun removeProcessor(index: Int) {
(processors as ArrayList<QueryProcessorSettings>).removeAt(index)
queryProcessorsListeners.forEach { it.onRemoveProcessor(index) }
}
// endregion
// region PersistentStateComponent
override fun getState(): QueryProcessorsData = data
override fun loadState(state: QueryProcessorsData): Unit = XmlSerializerUtil.copyBean(state, data)
// endregion
// region Instance
companion object {
fun getInstance(): QueryProcessors = ApplicationManager.getApplication().getService(QueryProcessors::class.java)
}
// endregion
}
|
apache-2.0
|
71bd687b67e20347c94e7c4a198aabe8
| 34.423529 | 120 | 0.75191 | 4.840836 | false | false | false | false |
WangDaYeeeeee/GeometricWeather
|
app/src/main/java/wangdaye/com/geometricweather/common/basic/models/options/unit/RelativeHumidityUnit.kt
|
1
|
1739
|
package wangdaye.com.geometricweather.common.basic.models.options.unit
import android.content.Context
import wangdaye.com.geometricweather.common.basic.models.options._basic.UnitEnum
import wangdaye.com.geometricweather.common.basic.models.options._basic.Utils
import wangdaye.com.geometricweather.common.utils.DisplayUtils
enum class RelativeHumidityUnit(
override val id: String,
override val unitFactor: Float
): UnitEnum<Int> {
PERCENT("%", 1f);
override val valueArrayId = 0
override val nameArrayId = 0
override val voiceArrayId = 0
override fun getName(context: Context) = "%"
override fun getVoice(context: Context) = "%"
override fun getValueWithoutUnit(
valueInDefaultUnit: Int
) = (valueInDefaultUnit * unitFactor).toInt()
override fun getValueInDefaultUnit(
valueInCurrentUnit: Int
) = (valueInCurrentUnit / unitFactor).toInt()
override fun getValueTextWithoutUnit(
valueInDefaultUnit: Int
) = Utils.getValueTextWithoutUnit(this, valueInDefaultUnit)!!
override fun getValueText(
context: Context,
valueInDefaultUnit: Int
) = getValueText(context, valueInDefaultUnit, DisplayUtils.isRtl(context))
override fun getValueText(
context: Context,
valueInDefaultUnit: Int,
rtl: Boolean
) = Utils.formatInt(valueInDefaultUnit) + "\u202f" + id
override fun getValueVoice(
context: Context,
valueInDefaultUnit: Int
) = getValueVoice(context, valueInDefaultUnit, DisplayUtils.isRtl(context))
override fun getValueVoice(
context: Context,
valueInDefaultUnit: Int,
rtl: Boolean
) = Utils.formatInt(valueInDefaultUnit) + "\u202f" + id
}
|
lgpl-3.0
|
552121e0374c116ce5b013517ee90cdb
| 30.071429 | 80 | 0.714204 | 4.262255 | false | false | false | false |
StepicOrg/stepic-android
|
app/src/main/java/org/stepik/android/domain/course/analytic/BuyCoursePressedEvent.kt
|
2
|
813
|
package org.stepik.android.domain.course.analytic
import org.stepik.android.domain.base.analytic.AnalyticEvent
import org.stepik.android.model.Course
class BuyCoursePressedEvent(
course: Course,
source: String,
isWishlisted: Boolean
) : AnalyticEvent {
companion object {
private const val PARAM_COURSE = "course"
private const val PARAM_SOURCE = "source"
private const val PARAM_IS_WISHLISTED = "is_wishlisted"
const val HOME_WIDGET = "home_widget"
const val COURSE_SCREEN = "course_screen"
}
override val name: String =
"Buy course pressed"
override val params: Map<String, Any> =
mapOf(
PARAM_COURSE to course.id,
PARAM_SOURCE to source,
PARAM_IS_WISHLISTED to isWishlisted
)
}
|
apache-2.0
|
6b353d1edb21dc52c5c1af46ae85ff51
| 27.068966 | 63 | 0.659287 | 4.212435 | false | false | false | false |
Akjir/WiFabs
|
src/main/kotlin/net/kejira/wifabs/ui/fabric/FabricView.kt
|
1
|
3441
|
/*
* Copyright (c) 2017 Stefan Neubert
*
* 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 net.kejira.wifabs.ui.fabric
import javafx.geometry.Insets
import javafx.scene.control.Button
import javafx.scene.layout.BorderPane
import net.kejira.wifabs.*
import net.kejira.wifabs.ui.ButtonGroup
import net.kejira.wifabs.util.hspacer
import tornadofx.*
class FabricView : View() {
private val preview_box = FabricPreviewBox()
private val buttons: ButtonGroup
override val root = BorderPane()
init {
val app_controller = find(AppController::class)
val fav_controller = find(FabricViewController::class)
val button_create = Button("Hinzufügen")
val button_edit = Button("Bearbeiten")
val button_delete = Button("Löschen")
val button_exit = Button("Beenden")
button_create.setOnAction { fav_controller.createFabric() }
button_edit .setOnAction { fav_controller.editCurrentFabric() }
button_delete.setOnAction { fav_controller.deleteCurrentFabric() }
button_exit .setOnAction { app_controller.exit() }
buttons = ButtonGroup(
buttons = setOf(button_create, button_edit, button_delete, button_exit),
blockable_buttons = setOf(button_edit, button_delete)
)
buttons.isBlocked = true
subscribe<FabricsSaved> { buttons.isDisable = false }
subscribe<FabricsSaving> { buttons.isDisable = true }
subscribe<SelectedFabricEdited> { preview_box.set(it.fabric) }
subscribe<SelectedFabricChanged> {
preview_box.set(it.fabric)
buttons.isBlocked = it.fabric == null
}
with(root) {
padding = Insets(10.0)
left = vbox(10.0) {
padding = Insets(0.0, 10.0, 0.0, 0.0)
this += preview_box
this += FabricDetailsView::class
}
center = vbox(10.0) {
this += FabricTilesView::class
hbox(10.0) {
label("Stoff:") { prefHeight = 25.0 }
this += button_create
this += button_edit
this += button_delete
hspacer()
this += button_exit
}
}
find(FabricViewController::class)
}
}
}
|
mit
|
0bb8ec3ac211f4494341dfc9d7c64fca
| 36.391304 | 98 | 0.635359 | 4.460441 | false | false | false | false |
spkingr/50-android-kotlin-projects-in-100-days
|
ProjectBasicMVP/app/src/main/java/me/liuqingwen/android/projectbasicmvp/presenter/MovieSearchPresenter.kt
|
1
|
1627
|
package me.liuqingwen.android.projectbasicmvp.presenter
import io.reactivex.disposables.CompositeDisposable
import me.liuqingwen.android.projectbasicmvp.model.APIMovieService
import me.liuqingwen.android.projectbasicmvp.view.IMovieView
/**
* Created by Qingwen on 2018-3-1, project: ProjectBasicMVP.
*
* @Author: Qingwen
* @DateTime: 2018-3-1
* @Package: me.liuqingwen.android.projectbasicmvp.presenter in project: ProjectBasicMVP
*
* Notice: If you are using this class or file, check it and do some modification.
*/
class MovieSearchPresenter(private val view: IMovieView)
{
private var startIndex = 0
private var countLoaded = 20
private var isRefreshing = false
private val disposables by lazy(LazyThreadSafetyMode.NONE) { CompositeDisposable() }
fun onCreate() = Unit
fun onStart() = Unit
fun onDestroy()
{
this.disposables.dispose()
}
fun searchMovieList(text: String)
{
if (this.isRefreshing || text.isEmpty())
{
return
}
this.view.onLoadStarted()
this.disposables.add(
APIMovieService.searchMovie(text, onSuccess = {
this.startIndex += it.size
if (it.isNotEmpty())
{
this.view.onLoadSuccess(it)
}
else
{
this.view.onLoadError("Empty list!")
}
}, onFailure = {
this.view.onLoadError(it.message)
}))
}
}
|
mit
|
5adc5cd1c49e9ed9e789af800f7a9f50
| 27.068966 | 88 | 0.57775 | 4.715942 | false | false | false | false |
CarlosEsco/tachiyomi
|
app/src/main/java/eu/kanade/presentation/browse/components/BaseBrowseItem.kt
|
1
|
1109
|
package eu.kanade.presentation.browse.components
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import eu.kanade.presentation.util.horizontalPadding
@Composable
fun BaseBrowseItem(
modifier: Modifier = Modifier,
onClickItem: () -> Unit = {},
onLongClickItem: () -> Unit = {},
icon: @Composable RowScope.() -> Unit = {},
action: @Composable RowScope.() -> Unit = {},
content: @Composable RowScope.() -> Unit = {},
) {
Row(
modifier = modifier
.combinedClickable(
onClick = onClickItem,
onLongClick = onLongClickItem,
)
.padding(horizontal = horizontalPadding, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
icon()
content()
action()
}
}
|
apache-2.0
|
feb17b55dbcb998680d387549fd9ebd8
| 30.685714 | 70 | 0.675383 | 4.679325 | false | false | false | false |
kvakil/venus
|
src/main/kotlin/venus/riscv/Program.kt
|
1
|
3209
|
package venus.riscv
import venus.assembler.DebugInfo
import venus.linker.RelocationInfo
import venus.riscv.insts.dsl.relocators.Relocator
/**
* An (unlinked) program.
*
* @param name the name of the program, used for debug info
* @see venus.assembler.Assembler
* @see venus.linker.Linker
*/
class Program(val name: String = "anonymous") {
/* TODO: abstract away these variables */
val insts = ArrayList<MachineCode>()
val debugInfo = ArrayList<DebugInfo>()
val labels = HashMap<String, Int>()
val relocationTable = ArrayList<RelocationInfo>()
val dataSegment = ArrayList<Byte>()
var textSize = 0
var dataSize = 0
private val globalLabels = HashSet<String>()
/**
* Adds an instruction to the program, and increments the text size.
*
* @param mcode the instruction to add
*/
fun add(mcode: MachineCode) {
insts.add(mcode)
textSize += mcode.length
}
/**
* Adds a byte of data to the program, and increments the data size.
*
* @param byte the byte to add
*/
fun addToData(byte: Byte) {
dataSegment.add(byte)
dataSize++
}
/**
* Adds debug info to the instruction currently being assembled.
*
* In the case of pseudo-instructions, the original instruction will be added multiple times.
* @todo Find a better way to deal with pseudoinstructions
*
* @param dbg the debug info to add
*/
fun addDebugInfo(dbg: DebugInfo) {
while (debugInfo.size < insts.size) {
debugInfo.add(dbg)
}
}
/**
* Adds a label with a given offset to the program.
*
* @param label the label to add
* @param offset the byte offset to add it at (from the start of the program)
*/
fun addLabel(label: String, offset: Int) = labels.put(label, offset)
/**
* Gets the _relative_ label offset, or null if it does not exist.
*
* The _relative_ offset is relative to the instruction currently being assembled.
*
* @param label the label to find
* @returns the relative offset, or null if it does not exist.
*/
fun getLabelOffset(label: String): Int? {
val loc = labels.get(label)
return loc?.minus(textSize)
}
/**
* Adds a line to the relocation table.
*
* @param label the label to relocate
* @param offset the byte offset the label is at (from the start of the program)
*/
fun addRelocation(relocator: Relocator, label: String, offset: Int = textSize) =
relocationTable.add(RelocationInfo(relocator, offset, label))
/**
* Makes a label global.
*
* @param label the label to make global
*/
fun makeLabelGlobal(label: String) {
globalLabels.add(label)
}
/**
* Checks if a label is global.
*
* @param label the label to check
* @return true if the label is global
*/
fun isGlobalLabel(label: String) = globalLabels.contains(label)
/* TODO: add dump formats */
/**
* Dumps the instructions.
*
* @return a list of instructions in this program
*/
fun dump(): List<MachineCode> = insts
}
|
mit
|
736f3d1611581fa1acf29819d5663801
| 27.39823 | 97 | 0.624805 | 4.072335 | false | false | false | false |
sivaprasadreddy/springboot-tutorials
|
spring-boot-k8s-demo/src/main/kotlin/com/sivalabs/geeksclub/entities/Category.kt
|
1
|
558
|
package com.sivalabs.geeksclub.entities
import javax.persistence.*
@Entity
@Table(name = "categories")
class Category {
@Id
@SequenceGenerator(name = "cat_generator", sequenceName = "cat_sequence", initialValue = 100)
@GeneratedValue(generator = "cat_generator")
var id: Long? = null
@Column(nullable = false, unique = true)
var name: String = ""
@Column(nullable = false, unique = true)
var label: String = ""
override fun toString(): String {
return "Category(id=$id, name='$name', label='$label')"
}
}
|
apache-2.0
|
845ffb212fb78a2aec7d3dd1e0c92c07
| 23.304348 | 97 | 0.648746 | 3.875 | false | false | false | false |
Maccimo/intellij-community
|
platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/LinkedListEntity.kt
|
2
|
2024
|
package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
data class LinkedListEntityId(val name: String) : PersistentEntityId<LinkedListEntity> {
override val presentableName: String
get() = name
}
interface LinkedListEntity : WorkspaceEntityWithPersistentId {
val myName: String
val next: LinkedListEntityId
override val persistentId: LinkedListEntityId
get() = LinkedListEntityId(myName)
//region generated code
//@formatter:off
@GeneratedCodeApiVersion(1)
interface Builder: LinkedListEntity, ModifiableWorkspaceEntity<LinkedListEntity>, ObjBuilder<LinkedListEntity> {
override var myName: String
override var entitySource: EntitySource
override var next: LinkedListEntityId
}
companion object: Type<LinkedListEntity, Builder>() {
operator fun invoke(myName: String, entitySource: EntitySource, next: LinkedListEntityId, init: (Builder.() -> Unit)? = null): LinkedListEntity {
val builder = builder()
builder.myName = myName
builder.entitySource = entitySource
builder.next = next
init?.invoke(builder)
return builder
}
}
//@formatter:on
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: LinkedListEntity, modification: LinkedListEntity.Builder.() -> Unit) = modifyEntity(LinkedListEntity.Builder::class.java, entity, modification)
//endregion
fun MutableEntityStorage.addLinkedListEntity(name: String, next: LinkedListEntityId): LinkedListEntity {
val linkedListEntity = LinkedListEntity(name, MySource, next)
this.addEntity(linkedListEntity)
return linkedListEntity
}
|
apache-2.0
|
7218b9c0045c8108bcf05107ea4901d1
| 33.913793 | 189 | 0.773715 | 5.298429 | false | false | false | false |
Appyx/AlexaHome
|
skill/src/main/kotlin/at/rgstoettner/alexahome/skill/endpoints/websocket/ExecutorController.kt
|
1
|
3702
|
package at.rgstoettner.alexahome.skill.endpoints.websocket
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.node.ArrayNode
import org.slf4j.LoggerFactory
import org.springframework.context.annotation.Configuration
import org.springframework.web.socket.CloseStatus
import org.springframework.web.socket.TextMessage
import org.springframework.web.socket.WebSocketSession
import org.springframework.web.socket.handler.TextWebSocketHandler
@Configuration
class ExecutorController : TextWebSocketHandler() {
private var logger = LoggerFactory.getLogger(this::class.java)
private val clients = mutableListOf<ExecutorClient>()
private val mapper = ObjectMapper()
override fun afterConnectionClosed(session: WebSocketSession, status: CloseStatus?) {
val client = clients.find { it.session == session }
client?.close()
clients.remove(client)
}
override fun afterConnectionEstablished(session: WebSocketSession) {
clients.add(ExecutorClient(session))
}
override fun handleTextMessage(session: WebSocketSession, textMessage: TextMessage) {
val client = clients.find { it.session == session }
client?.onMessage(textMessage.payload)
}
/**
* Sends the name to all devices.
*
* @return The message containing an array of discovered devices.
* If none are found it simply returns a message with an empty array.
*/
fun discoverDevices(name: String): ExecutorMessage {
val devices = mapper.nodeFactory.arrayNode()
var newMessage = ExecutorMessage("DiscoverAppliancesResponse")
clients.forEach {
val message = it.discover(name)
val arrayNode = mapper.convertValue(message.payload, ArrayNode::class.java)
logger.info("Discovered ${arrayNode.count()} devices at: ${it.host}")
devices.addAll(arrayNode)
newMessage = message
}
newMessage.payload = devices
return newMessage
}
/**
* Sends the name and payload to all devices.
* If a device can handle it, it has to set the "executed" flag to true.
* This method returns the message that has the first "executed" flag set to true.
*
* @return The Message which contains the response payload or an error if no device was executed.
*/
fun queryDevices(name: String, payload: JsonNode): ExecutorMessage {
clients.forEach {
val message = it.query(name, payload)
if (message.executed) {
logger.info("Executed at: ${it.host}")
return message
}
}
if (clients.size == 0) {
return ExecutorMessage("BridgeOfflineError")
} else {
return ExecutorMessage("NoSuchTargetError")
}
}
/**
* Sends the name and payload to all devices.
* If a device can handle it, it has to set the "executed" flag to true.
* This method returns the message that has the first "executed" flag set to true.
*
* The Message which contains the response payload or an error if no device was executed.
*/
fun controlDevices(name: String, payload: JsonNode): ExecutorMessage {
clients.forEach {
val message = it.control(name, payload)
if (message.executed) {
logger.info("Executed at: ${it.host}")
return message
}
}
if (clients.size == 0) {
return ExecutorMessage("BridgeOfflineError")
} else {
return ExecutorMessage("NoSuchTargetError")
}
}
}
|
apache-2.0
|
694ecf7176cff5b2f2a79b119dba48e8
| 36.40404 | 101 | 0.660724 | 4.734015 | false | false | false | false |
AcornUI/Acorn
|
acornui-core/src/main/kotlin/com/acornui/dom/computedStyleChanged.kt
|
1
|
3590
|
/*
* Copyright 2020 Poly Forest, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.acornui.dom
import com.acornui.component.UiComponent
import com.acornui.signal.Signal
import com.acornui.signal.SignalImpl
import com.acornui.signal.SignalSubscription
import com.acornui.signal.filtered
import kotlinx.browser.document
import kotlinx.browser.window
import org.w3c.dom.*
import org.w3c.dom.events.Event
object ComputedStyleChangedSignal : SignalImpl<Unit>() {
/**
* If a style element changes its content.
*/
private val styleContentsObserver = MutationObserver { mutations, _ ->
dispatch(Unit)
}
private val targetObserver = MutationObserver { mutations, _ ->
if (mutations.any { mutationRecord ->
when (mutationRecord.type) {
"attributes" -> true
"childList" -> {
var shouldDispatch = false
mutationRecord.addedNodes.asList().forEach { addedNode ->
if (addedNode.nodeName == "STYLE") {
observeStyleElement(addedNode.unsafeCast<HTMLStyleElement>())
shouldDispatch = true
} else if (addedNode.nodeName == "LINK") {
observeLinkElement(addedNode.unsafeCast<HTMLLinkElement>())
shouldDispatch = true
}
}
shouldDispatch
}
else -> false
}
}) {
dispatch(Unit)
}
}
private fun observeStyleElement(it: HTMLStyleElement) {
styleContentsObserver.observe(it, MutationObserverInit(
childList = true,
subtree = true,
attributes = true,
characterData = true
))
}
private fun observeLinkElement(it: HTMLLinkElement) {
it.addEventListener("load", ::loadedHandler)
}
private fun loadedHandler(e: Event) {
dispatch(Unit)
}
override fun removeSubscription(subscription: SignalSubscription) {
super.removeSubscription(subscription)
if (isEmpty())
disconnect()
}
override fun listen(isOnce: Boolean, handler: (Unit) -> Unit): SignalSubscription {
if (isEmpty())
connect()
return super.listen(isOnce, handler)
}
private fun connect() {
document.getElementsByTagName("STYLE").asList().forEach {
observeStyleElement(it.unsafeCast<HTMLStyleElement>())
}
document.getElementsByTagName("LINK").asList().forEach {
observeLinkElement(it.unsafeCast<HTMLLinkElement>())
}
targetObserver.observe(document, MutationObserverInit(
childList = true,
subtree = true,
attributes = true,
attributeFilter = arrayOf("style", "class", "src")
))
}
private fun disconnect() {
targetObserver.disconnect()
styleContentsObserver.disconnect()
document.getElementsByTagName("LINK").asList().forEach {
it.removeEventListener("load", ::loadedHandler)
}
}
}
/**
* Dispatched when the computed style of this component with the given name has changed.
*/
fun UiComponent.computedStyleChanged(property: String): Signal<Unit> {
val computed = window.getComputedStyle(dom)
var value = computed.getPropertyValue(property)
return ComputedStyleChangedSignal.filtered {
val newValue = computed.getPropertyValue(property)
if (newValue != value) {
value = newValue
true
} else {
false
}
}
}
|
apache-2.0
|
3c9be910a60dc4d573e1e1187a37d4b6
| 26 | 88 | 0.721727 | 3.839572 | false | false | false | false |
JetBrains/ideavim
|
src/main/java/com/maddyhome/idea/vim/helper/CommandStateExtensions.kt
|
1
|
3950
|
/*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
@file:JvmName("CommandStateHelper")
package com.maddyhome.idea.vim.helper
import com.intellij.openapi.editor.Editor
import com.maddyhome.idea.vim.command.CommandState
import com.maddyhome.idea.vim.command.VimStateMachine
import com.maddyhome.idea.vim.command.engine
import com.maddyhome.idea.vim.command.ij
import com.maddyhome.idea.vim.newapi.vim
val Editor.isEndAllowed: Boolean
get() = when (this.editorMode) {
VimStateMachine.Mode.INSERT, VimStateMachine.Mode.VISUAL, VimStateMachine.Mode.SELECT, VimStateMachine.Mode.INSERT_VISUAL, VimStateMachine.Mode.INSERT_SELECT -> true
VimStateMachine.Mode.COMMAND, VimStateMachine.Mode.CMD_LINE, VimStateMachine.Mode.REPLACE, VimStateMachine.Mode.OP_PENDING, VimStateMachine.Mode.INSERT_NORMAL -> {
// One day we'll use a proper insert_normal mode
if (this.editorMode.inSingleMode) true else usesVirtualSpace
}
}
val VimStateMachine.Mode.isEndAllowedIgnoringOnemore: Boolean
get() = when (this) {
VimStateMachine.Mode.INSERT, VimStateMachine.Mode.VISUAL, VimStateMachine.Mode.SELECT -> true
VimStateMachine.Mode.COMMAND, VimStateMachine.Mode.CMD_LINE, VimStateMachine.Mode.REPLACE, VimStateMachine.Mode.OP_PENDING -> false
VimStateMachine.Mode.INSERT_NORMAL -> false
VimStateMachine.Mode.INSERT_VISUAL -> true
VimStateMachine.Mode.INSERT_SELECT -> true
}
val VimStateMachine.Mode.hasVisualSelection
get() = when (this) {
VimStateMachine.Mode.VISUAL, VimStateMachine.Mode.SELECT -> true
VimStateMachine.Mode.REPLACE, VimStateMachine.Mode.CMD_LINE, VimStateMachine.Mode.COMMAND, VimStateMachine.Mode.INSERT, VimStateMachine.Mode.OP_PENDING -> false
VimStateMachine.Mode.INSERT_NORMAL -> false
VimStateMachine.Mode.INSERT_VISUAL -> true
VimStateMachine.Mode.INSERT_SELECT -> true
}
val Editor.editorMode
get() = this.vim.vimStateMachine.mode
/**
* COMPATIBILITY-LAYER: New method
* Please see: https://jb.gg/zo8n0r
*/
val Editor.mode
get() = this.vim.vimStateMachine.mode.ij
/**
* COMPATIBILITY-LAYER: New method
* Please see: https://jb.gg/zo8n0r
*/
val CommandState.Mode.isEndAllowed: Boolean
get() = this.engine.isEndAllowed
var Editor.subMode
get() = this.vim.vimStateMachine.subMode
set(value) {
this.vim.vimStateMachine.subMode = value
}
@get:JvmName("inNormalMode")
val Editor.inNormalMode
get() = this.editorMode.inNormalMode
@get:JvmName("inNormalMode")
val VimStateMachine.Mode.inNormalMode
get() = this == VimStateMachine.Mode.COMMAND || this == VimStateMachine.Mode.INSERT_NORMAL
@get:JvmName("inInsertMode")
val Editor.inInsertMode
get() = this.editorMode == VimStateMachine.Mode.INSERT || this.editorMode == VimStateMachine.Mode.REPLACE
@get:JvmName("inRepeatMode")
val Editor.inRepeatMode
get() = this.vim.vimStateMachine.isDotRepeatInProgress
@get:JvmName("inVisualMode")
val Editor.inVisualMode
get() = this.editorMode.inVisualMode
@get:JvmName("inSelectMode")
val Editor.inSelectMode
get() = this.editorMode == VimStateMachine.Mode.SELECT || this.editorMode == VimStateMachine.Mode.INSERT_SELECT
@get:JvmName("inBlockSubMode")
val Editor.inBlockSubMode
get() = this.subMode == VimStateMachine.SubMode.VISUAL_BLOCK
@get:JvmName("inSingleCommandMode")
val Editor.inSingleCommandMode: Boolean
get() = this.editorMode.inSingleMode
@get:JvmName("inSingleMode")
val VimStateMachine.Mode.inSingleMode: Boolean
get() = when (this) {
VimStateMachine.Mode.INSERT_NORMAL, VimStateMachine.Mode.INSERT_SELECT, VimStateMachine.Mode.INSERT_VISUAL -> true
else -> false
}
@get:JvmName("inSingleNormalMode")
val VimStateMachine.Mode.inSingleNormalMode: Boolean
get() = when (this) {
VimStateMachine.Mode.INSERT_NORMAL -> true
else -> false
}
|
mit
|
7c6c04a82ef6ba3cb83c361c96ac5f45
| 33.649123 | 169 | 0.765316 | 3.868756 | false | false | false | false |
lcmatrix/betting-game
|
src/main/kotlin/de/bettinggame/adapter/BaseController.kt
|
1
|
1642
|
package de.bettinggame.adapter
import de.bettinggame.domain.NewsRepository
import de.bettinggame.ui.Navigation
import org.springframework.security.core.Authentication
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.ModelAttribute
import org.springframework.web.bind.annotation.RequestMapping
interface AbstractController {
/**
* Returns navigation items
*/
@ModelAttribute("nonRestrictedNavigation")
fun getNonRestrictedNavigation(): List<Navigation> = Navigation.getNonRestrictedNavigation()
@ModelAttribute("userRestrictedNavigation")
fun getUserRestrictedNavigation(): List<Navigation> = Navigation.getUserRestrictedNavigation()
@ModelAttribute("adminRestrictedNavigation")
fun getAdminRestrictedNavigation(): List<Navigation> = Navigation.getAdminRestrictedNavigation()
}
/**
* Controller for index/startpage.
*/
@Controller
class MainController(private val newsRepository: NewsRepository) : AbstractController {
@RequestMapping("/login")
fun login() = "login"
@RequestMapping("/index")
fun index() = "index"
@RequestMapping("/")
fun root(model: Model): String {
val authentication: Authentication? = SecurityContextHolder.getContext().authentication
if (authentication != null && authentication.isAuthenticated) {
val news = newsRepository.findAllByOrderByPublishDateDesc()
model.addAttribute(news)
return "news/news"
}
return "index"
}
}
|
apache-2.0
|
0c83462999c597c1a267e8cb111fc5c6
| 33.93617 | 100 | 0.753959 | 5.115265 | false | false | false | false |
JStege1206/AdventOfCode
|
aoc-2015/src/main/kotlin/nl/jstege/adventofcode/aoc2015/days/Day13.kt
|
1
|
1835
|
package nl.jstege.adventofcode.aoc2015.days
import nl.jstege.adventofcode.aoccommon.days.Day
import nl.jstege.adventofcode.aoccommon.utils.extensions.*
/**
*
* @author Jelle Stege
*/
class Day13 : Day(title = "Knights of the Dinner Table") {
private companion object Configuration {
private const val INPUT_PATTERN_STRING = "([a-zA-Z]+) would (lose|gain) (\\d+) happiness " +
"units by sitting next to ([a-zA-Z]+)\\."
private val INPUT_REGEX = INPUT_PATTERN_STRING.toRegex()
private const val PERSON1_INDEX = 1
private const val NEGATE_INDEX = 2
private const val AMOUNT_INDEX = 3
private const val PERSON2_INDEX = 4
private val PARAM_INDICES =
intArrayOf(PERSON1_INDEX, NEGATE_INDEX, AMOUNT_INDEX, PERSON2_INDEX)
}
override fun first(input: Sequence<String>) = input.parse().optimal()
override fun second(input: Sequence<String>) = input.parse().addOwn().optimal()
private fun Sequence<String>.parse(): Map<String, Map<String, Int>> = this
.map { it.extractValues(INPUT_REGEX, *PARAM_INDICES) }
.transformTo(mutableMapOf<String, MutableMap<String, Int>>())
{ relations, (p1, neg, amt, p2) ->
relations[p1, p2] = amt.toInt() * if (neg == "lose") -1 else 1
}
private fun Map<String, Map<String, Int>>.addOwn() = this
.map { (k, v) -> Pair(k, v + Pair("", 0)) }
.toMap() + ("" to mapOf(*this.keys.map { it to 0 }.toTypedArray()))
private fun Map<String, Map<String, Int>>.optimal() = this.keys.toList()
.permutations()
.map {
it.zipWithNext { prev, cur ->
(this[prev, cur] ?: 0) + (this[cur, prev] ?: 0)
}.sum() + (this[it.head, it.last] ?: 0) + (this[it.last, it.head] ?: 0)
}.max()!!
}
|
mit
|
1efb9cdec7204fac130b26ae56ec0481
| 37.229167 | 100 | 0.59673 | 3.556202 | false | false | false | false |
edwardharks/Aircraft-Recognition
|
recognition/src/test/kotlin/com/edwardharker/aircraftrecognition/feedback/FeedbackPresenterTest.kt
|
1
|
2081
|
package com.edwardharker.aircraftrecognition.feedback
import com.nhaarman.mockito_kotlin.never
import com.nhaarman.mockito_kotlin.verify
import org.junit.Test
import org.mockito.Mockito
class FeedbackPresenterTest {
@Test
fun `submits feedback`() {
val mockSubmitFeedbackUseCase = Mockito.mock(ScheduleFeedbackUseCase::class.java)
val presenter = FeedbackPresenter(mockSubmitFeedbackUseCase)
presenter.submitFeedback(MESSAGE)
verify(mockSubmitFeedbackUseCase).scheduleFeedback(MESSAGE)
}
@Test
fun `shows success`() {
val mockView = Mockito.mock(FeedbackView::class.java)
val presenter = FeedbackPresenter(ScheduleFeedbackUseCase.NO_OP)
presenter.startPresenting(mockView)
presenter.submitFeedback(MESSAGE)
verify(mockView).showSuccess()
}
@Test
fun `does not submit feedback when message is too short`() {
val mockSubmitFeedbackUseCase = Mockito.mock(ScheduleFeedbackUseCase::class.java)
val presenter = FeedbackPresenter(mockSubmitFeedbackUseCase)
presenter.submitFeedback(EMPTY_MESSAGE)
verify(mockSubmitFeedbackUseCase, never()).scheduleFeedback(EMPTY_MESSAGE)
}
@Test
fun `shows validation error when message is too short`() {
val mockView = Mockito.mock(FeedbackView::class.java)
val presenter = FeedbackPresenter(ScheduleFeedbackUseCase.NO_OP)
presenter.startPresenting(mockView)
presenter.submitFeedback(EMPTY_MESSAGE)
verify(mockView).showValidationError()
}
@Test
fun `never shows success after stopPresenting`() {
val mockView = Mockito.mock(FeedbackView::class.java)
val presenter = FeedbackPresenter(ScheduleFeedbackUseCase.NO_OP)
presenter.startPresenting(mockView)
presenter.stopPresenting()
presenter.submitFeedback(MESSAGE)
verify(mockView, never()).showSuccess()
}
companion object {
private const val MESSAGE = "a nice message"
private const val EMPTY_MESSAGE = ""
}
}
|
gpl-3.0
|
02cc9b9771ea80b38ae29609cd56d7f5
| 30.059701 | 89 | 0.709274 | 4.81713 | false | true | false | false |
mdaniel/intellij-community
|
platform/platform-impl/src/com/intellij/ide/util/TipsOrderUtil.kt
|
1
|
6005
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.util
import com.fasterxml.jackson.databind.ObjectMapper
import com.intellij.internal.statistic.eventLog.EventLogConfiguration
import com.intellij.internal.statistic.local.ActionSummary
import com.intellij.internal.statistic.local.ActionsLocalSummary
import com.intellij.internal.statistic.utils.StatisticsUploadAssistant
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.ProjectPostStartupActivity
import com.intellij.util.PlatformUtils
import com.intellij.util.io.HttpRequests
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.time.Duration.Companion.hours
private val LOG = logger<TipsOrderUtil>()
private const val EXPERIMENT_RANDOM_SEED = 0L
private const val USED_BUCKETS_COUNT = 128
private const val RANDOM_SHUFFLE_ALGORITHM = "default_shuffle"
private const val TIPS_SERVER_URL = "https://feature-recommendation.analytics.aws.intellij.net/tips/v1"
internal data class RecommendationDescription(val algorithm: String, val tips: List<TipAndTrickBean>, val version: String?)
private fun getUtilityExperiment(): TipsUtilityExperiment? {
if (!ApplicationManager.getApplication().isEAP) return null
val shuffledBuckets = (0 until USED_BUCKETS_COUNT).shuffled(Random(EXPERIMENT_RANDOM_SEED))
return when (shuffledBuckets[EventLogConfiguration.getInstance().bucket % USED_BUCKETS_COUNT]) {
in 0..31 -> TipsUtilityExperiment.BY_TIP_UTILITY
in 32..63 -> TipsUtilityExperiment.BY_TIP_UTILITY_IGNORE_USED
in 64..95 -> TipsUtilityExperiment.RANDOM_IGNORE_USED
else -> null
}
}
private fun randomShuffle(tips: List<TipAndTrickBean>): RecommendationDescription {
return RecommendationDescription(RANDOM_SHUFFLE_ALGORITHM, tips.shuffled(), null)
}
@Service
internal class TipsOrderUtil {
private class RecommendationsStartupActivity : ProjectPostStartupActivity {
private val isScheduled = AtomicBoolean()
override suspend fun execute(project: Project) {
if (!isScheduled.compareAndSet(false, true)) {
return
}
val app = ApplicationManager.getApplication()
if (!app.isEAP || app.isHeadlessEnvironment || !StatisticsUploadAssistant.isSendAllowed()) {
return
}
ApplicationManager.getApplication().coroutineScope.launch(Dispatchers.IO) {
sync()
while (isActive) {
delay(3.hours)
sync()
}
}
}
}
companion object {
private fun sync() {
LOG.assertTrue(!ApplicationManager.getApplication().isDispatchThread)
LOG.debug { "Fetching tips order from the server: $TIPS_SERVER_URL" }
val allTips = TipAndTrickBean.EP_NAME.iterable.map { it.fileName }
val actionsSummary = service<ActionsLocalSummary>().getActionsStats()
val startTimestamp = System.currentTimeMillis()
HttpRequests.post(TIPS_SERVER_URL, HttpRequests.JSON_CONTENT_TYPE)
.connect(HttpRequests.RequestProcessor { request ->
val bucket = EventLogConfiguration.getInstance().bucket
val tipsRequest = TipsRequest(allTips, actionsSummary, PlatformUtils.getPlatformPrefix(), bucket)
val objectMapper = ObjectMapper()
request.write(objectMapper.writeValueAsBytes(tipsRequest))
val recommendation = objectMapper.readValue(request.readString(), ServerRecommendation::class.java)
LOG.debug {
val duration = System.currentTimeMillis() - startTimestamp
val algorithmInfo = "${recommendation.usedAlgorithm}:${recommendation.version}"
"Server recommendation made. Algorithm: $algorithmInfo. Duration: ${duration}"
}
service<TipsOrderUtil>().serverRecommendation = recommendation
}, null, LOG)
}
}
@Volatile
private var serverRecommendation: ServerRecommendation? = null
/**
* Reorders tips to show the most useful ones in the beginning
*
* @return object that contains sorted tips and describes approach of how the tips are sorted
*/
fun sort(tips: List<TipAndTrickBean>): RecommendationDescription {
getUtilityExperiment()?.let {
return service<TipsUsageManager>().sortTips(tips, it)
}
serverRecommendation?.let { return it.reorder(tips) }
return randomShuffle(tips)
}
}
enum class TipsUtilityExperiment {
BY_TIP_UTILITY {
override fun toString(): String = "tip_utility"
},
BY_TIP_UTILITY_IGNORE_USED {
override fun toString(): String = "tip_utility_and_ignore_used"
},
RANDOM_IGNORE_USED {
override fun toString(): String = "random_ignore_used"
}
}
private data class TipsRequest(
val tips: List<String>,
val usageInfo: Map<String, ActionSummary>,
val ideName: String, // product code
val bucket: Int
)
private class ServerRecommendation {
@JvmField
var showingOrder = emptyList<String>()
@JvmField
var usedAlgorithm = "unknown"
@JvmField
var version: String? = null
fun reorder(tips: List<TipAndTrickBean>): RecommendationDescription {
val tipToIndex = Object2IntOpenHashMap<String>(showingOrder.size)
showingOrder.forEachIndexed { index, tipFile -> tipToIndex.put(tipFile, index) }
for (tip in tips) {
if (!tipToIndex.containsKey(tip.fileName)) {
LOG.error("Unknown tips file: ${tip.fileName}")
return randomShuffle(tips)
}
}
return RecommendationDescription(usedAlgorithm, tips.sortedBy { tipToIndex.getInt(it.fileName) }, version)
}
}
|
apache-2.0
|
0247628f18e2f71203bd3b68f4fb6c26
| 36.5375 | 123 | 0.742714 | 4.504876 | false | false | false | false |
ingokegel/intellij-community
|
plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveNestedClass/innerToTopLevelWithThis/after/test.kt
|
13
|
529
|
package test
inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()
class A {
class X {
}
inner class OuterY
fun outerFoo(n: Int) {}
val outerBar = 1
companion object {
class Y
fun foo(n: Int) {}
val bar = 1
fun Int.extFoo(n: Int) {}
val Int.extBar: Int get() = 1
}
object O {
class Y
fun foo(n: Int) {}
val bar = 1
fun Int.extFoo(n: Int) {}
val Int.extBar: Int get() = 1
}
}
|
apache-2.0
|
d5143980724e090144469459372d8003
| 12.25 | 75 | 0.470699 | 3.412903 | false | false | false | false |
mdaniel/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddStarProjectionsFix.kt
|
1
|
5072
|
// 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.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.descriptors.ClassDescriptor
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.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.descriptorUtil.parentsWithSelf
import org.jetbrains.kotlin.resolve.scopes.LexicalScope
import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier
import org.jetbrains.kotlin.types.expressions.TypeReconstructionUtil
import org.jetbrains.kotlin.utils.sure
object AddStarProjectionsFixFactory : KotlinSingleIntentionActionFactory() {
public override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val diagnosticWithParameters = Errors.NO_TYPE_ARGUMENTS_ON_RHS.cast(diagnostic)
val typeReference = diagnosticWithParameters.psiElement
if (typeReference.classDescriptor()?.isInner == true)
return AddStartProjectionsForInnerClass(typeReference)
else {
val typeElement = typeReference.typeElement ?: return null
val unwrappedType =
generateSequence(typeElement) { (it as? KtNullableType)?.innerType }.lastOrNull() as? KtUserType ?: return null
return AddStarProjectionsFix(unwrappedType, diagnosticWithParameters.a)
}
}
}
@Nls
private val starProjectionFixFamilyName = KotlinBundle.message("fix.add.star.projection.family")
class AddStarProjectionsFix(element: KtUserType, private val argumentCount: Int) : KotlinQuickFixAction<KtUserType>(element) {
override fun getFamilyName() = starProjectionFixFamilyName
override fun getText() =
KotlinBundle.message("fix.add.star.projection.text", TypeReconstructionUtil.getTypeNameAndStarProjectionsString("", argumentCount))
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
assert(element.typeArguments.isEmpty())
val typeString = TypeReconstructionUtil.getTypeNameAndStarProjectionsString(element.text, argumentCount)
val replacement = KtPsiFactory(file).createType(typeString).typeElement.sure { "No type element after parsing " + typeString }
element.replace(replacement)
}
}
class AddStartProjectionsForInnerClass(element: KtTypeReference) : KotlinQuickFixAction<KtTypeReference>(element) {
override fun getFamilyName() = text
override fun getText() = starProjectionFixFamilyName
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val typeReference = element ?: return
val targetClasses = getTargetClasses(typeReference) ?: return
val replaceString = createReplaceString(targetClasses)
typeReference.replace(KtPsiFactory(file).createType(replaceString))
}
private fun getTargetClasses(typeReference: KtTypeReference): List<ClassDescriptor>? {
val classDescriptor = typeReference.classDescriptor() ?: return null
val parentWithSelfClasses = classDescriptor.parentsWithSelf.mapNotNull { it as? ClassDescriptor }.toList()
val scope = typeReference.getResolutionScope()
val targets = parentWithSelfClasses.takeWhile { it.isInner || !it.inScope(scope) }
val last = targets.lastOrNull() ?: return targets
val next = parentWithSelfClasses.getOrNull(targets.size) ?: return targets
return if (last.isInner && next.declaredTypeParameters.isNotEmpty() || !last.inScope(scope)) {
targets + next
} else {
targets
}
}
private fun createReplaceString(targetClasses: List<ClassDescriptor>): String {
return targetClasses.mapIndexed { index, c ->
val name = c.name.asString()
val last = targetClasses.getOrNull(index - 1)
val size = if (index == 0 || last?.isInner == true) c.declaredTypeParameters.size else 0
if (size == 0) name else TypeReconstructionUtil.getTypeNameAndStarProjectionsString(name, size)
}.reversed().joinToString(".")
}
}
private fun KtTypeReference.classDescriptor(): ClassDescriptor? =
this.analyze()[BindingContext.TYPE, this]?.constructor?.declarationDescriptor as? ClassDescriptor
private fun ClassDescriptor.inScope(scope: LexicalScope): Boolean = scope.findClassifier(this.name, NoLookupLocation.FROM_IDE) != null
|
apache-2.0
|
414ed2910fff0e424f613128c319904d
| 47.304762 | 158 | 0.754929 | 4.962818 | false | false | false | false |
ingokegel/intellij-community
|
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/toolwindow/GHPRRepositorySelectorComponentFactory.kt
|
1
|
12149
|
// 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.plugins.github.pullrequest.ui.toolwindow
import com.intellij.collaboration.async.DisposingMainScope
import com.intellij.collaboration.auth.AccountsListener
import com.intellij.collaboration.ui.CollaborationToolsUIUtil.defaultButton
import com.intellij.ide.plugins.newui.HorizontalLayout
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.project.Project
import com.intellij.ui.components.ActionLink
import com.intellij.util.castSafelyTo
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UI
import com.intellij.util.ui.UIUtil
import kotlinx.coroutines.launch
import net.miginfocom.layout.CC
import net.miginfocom.layout.LC
import net.miginfocom.layout.PlatformDefaults
import net.miginfocom.swing.MigLayout
import org.jetbrains.plugins.github.api.GithubServerPath
import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.ui.component.ComboBoxWithActionsModel
import org.jetbrains.plugins.github.ui.component.GHAccountSelectorComponentFactory
import org.jetbrains.plugins.github.ui.component.GHRepositorySelectorComponentFactory
import org.jetbrains.plugins.github.ui.util.getName
import org.jetbrains.plugins.github.util.GHGitRepositoryMapping
import org.jetbrains.plugins.github.util.GHHostedRepositoriesManager
import java.awt.event.ActionEvent
import javax.swing.*
import javax.swing.event.ListDataEvent
import javax.swing.event.ListDataListener
class GHPRRepositorySelectorComponentFactory(private val project: Project,
private val authManager: GithubAuthenticationManager,
private val repositoryManager: GHHostedRepositoriesManager) {
fun create(disposable: Disposable, onSelected: (GHGitRepositoryMapping, GithubAccount) -> Unit): JComponent {
val repositoriesModel = ComboBoxWithActionsModel<GHGitRepositoryMapping>().apply {
//todo: add remote action
}
val accountsModel = ComboBoxWithActionsModel<GithubAccount>()
val applyAction = object : AbstractAction(GithubBundle.message("pull.request.view.list")) {
override fun actionPerformed(e: ActionEvent?) {
val repo = repositoriesModel.selectedItem ?: return
val account = accountsModel.selectedItem ?: return
onSelected(repo.wrappee, account.wrappee)
}
}
val githubLoginAction = object : AbstractAction(GithubBundle.message("action.Github.Accounts.AddGHAccount.text")) {
override fun actionPerformed(e: ActionEvent?) {
authManager.requestNewAccountForDefaultServer(project)?.run {
applyAction.actionPerformed(e)
}
}
}
val tokenLoginAction = object : AbstractAction(GithubBundle.message("action.Github.Accounts.AddGHAccountWithToken.text")) {
override fun actionPerformed(e: ActionEvent?) {
authManager.requestNewAccountForDefaultServer(project, true)?.run {
applyAction.actionPerformed(e)
}
}
}
val gheLoginAction = object : AbstractAction(GithubBundle.message("action.Github.Accounts.AddGHEAccount.text")) {
override fun actionPerformed(e: ActionEvent?) {
val server = repositoriesModel.selectedItem?.wrappee?.ghRepositoryCoordinates?.serverPath ?: return
authManager.requestNewAccountForServer(server, project)?.run {
applyAction.actionPerformed(e)
}
}
}
Controller(project = project, authManager = authManager, repositoriesManager = repositoryManager,
repositoriesModel = repositoriesModel, accountsModel = accountsModel,
applyAction = applyAction, githubLoginAction = githubLoginAction, tokenLoginAction = tokenLoginAction,
gheLoginActon = gheLoginAction,
disposable = disposable)
val repoCombo = GHRepositorySelectorComponentFactory().create(repositoriesModel).apply {
putClientProperty(PlatformDefaults.VISUAL_PADDING_PROPERTY, insets)
}
val accountCombo = GHAccountSelectorComponentFactory().create(accountsModel).apply {
putClientProperty(PlatformDefaults.VISUAL_PADDING_PROPERTY, insets)
}
val applyButton = JButton(applyAction).defaultButton().apply {
isOpaque = false
controlVisibilityFromAction(this, applyAction)
}
val githubLoginButton = JButton(githubLoginAction).defaultButton().apply {
isOpaque = false
controlVisibilityFromAction(this, githubLoginAction)
}
val tokenLoginLink = createLinkLabel(tokenLoginAction)
val gheLoginButton = JButton(gheLoginAction).defaultButton().apply {
isOpaque = false
controlVisibilityFromAction(this, gheLoginAction)
}
val actionsPanel = JPanel(HorizontalLayout(UI.scale(16))).apply {
isOpaque = false
add(applyButton)
add(githubLoginButton)
add(tokenLoginLink)
add(gheLoginButton)
putClientProperty(PlatformDefaults.VISUAL_PADDING_PROPERTY, applyButton.insets)
}
return JPanel(null).apply {
isOpaque = false
border = JBUI.Borders.empty(30, 16)
layout = MigLayout(LC().fill().gridGap("${UI.scale(10)}px", "${UI.scale(16)}px").insets("0").hideMode(3).noGrid())
add(repoCombo, CC().growX().push())
add(accountCombo, CC())
add(actionsPanel, CC().newline())
add(JLabel(GithubBundle.message("pull.request.login.note")).apply {
foreground = UIUtil.getContextHelpForeground()
}, CC().newline().minWidth("0"))
}
}
private class Controller(private val project: Project,
private val authManager: GithubAuthenticationManager,
private val repositoriesManager: GHHostedRepositoriesManager,
private val repositoriesModel: ComboBoxWithActionsModel<GHGitRepositoryMapping>,
private val accountsModel: ComboBoxWithActionsModel<GithubAccount>,
private val applyAction: Action,
private val githubLoginAction: Action,
private val tokenLoginAction: Action,
private val gheLoginActon: Action,
disposable: Disposable) {
private val scope = DisposingMainScope(disposable)
init {
repositoriesModel.addSelectionChangeListener(::updateAccounts)
repositoriesModel.addSelectionChangeListener(::updateActions)
accountsModel.addSelectionChangeListener(::updateActions)
scope.launch {
repositoriesManager.knownRepositoriesState.collect {
repositoriesModel.items = it.toList()
repositoriesModel.preSelect()
}
}
authManager.addListener(disposable, object : AccountsListener<GithubAccount> {
override fun onAccountListChanged(old: Collection<GithubAccount>, new: Collection<GithubAccount>) {
invokeAndWaitIfNeeded(runnable = ::updateAccounts)
}
})
updateAccounts()
updateActions()
}
private fun updateAccounts() {
val serverPath = repositoriesModel.selectedItem?.wrappee?.ghRepositoryCoordinates?.serverPath
if (serverPath == null) {
accountsModel.items = emptyList()
accountsModel.actions = emptyList()
return
}
val accounts = authManager.getAccounts()
val matchingAccounts = accounts.filter { it.server.equals(serverPath, true) }
accountsModel.items = matchingAccounts
accountsModel.actions = getAccountsPopupActions(serverPath)
preselectAccount()
}
private fun getAccountsPopupActions(server: GithubServerPath): List<Action> {
return if (server.isGithubDotCom)
listOf(object : AbstractAction(GithubBundle.message("action.Github.Accounts.AddGHAccount.text")) {
override fun actionPerformed(e: ActionEvent?) {
authManager.requestNewAccountForDefaultServer(project)?.let(::trySelectAccount)
}
}, object : AbstractAction(GithubBundle.message("action.Github.Accounts.AddGHAccountWithToken.text")) {
override fun actionPerformed(e: ActionEvent?) {
authManager.requestNewAccountForDefaultServer(project, true)?.let(::trySelectAccount)
}
})
else listOf(
object : AbstractAction(GithubBundle.message("action.Github.Accounts.AddGHEAccount.text")) {
override fun actionPerformed(e: ActionEvent?) {
authManager.requestNewAccountForServer(server, project)?.let(::trySelectAccount)
}
})
}
private fun trySelectAccount(account: GithubAccount) {
with(accountsModel) {
if (size > 0) {
for (i in 0 until size) {
val item = getElementAt(i) as? ComboBoxWithActionsModel.Item.Wrapper<GithubAccount>
if (item != null && item.wrappee.castSafelyTo<GithubAccount>() == account) {
selectedItem = item
break
}
}
}
}
}
private fun preselectAccount() {
with(accountsModel) {
if (selectedItem == null && size > 0) {
val defaultAccount = authManager.getDefaultAccount(project)
var newSelection = getElementAt(0) as? ComboBoxWithActionsModel.Item.Wrapper
for (i in 0 until size) {
val item = getElementAt(i) as? ComboBoxWithActionsModel.Item.Wrapper
if (item != null && item.wrappee.castSafelyTo<GithubAccount>() == defaultAccount) {
newSelection = item
break
}
}
selectedItem = newSelection
}
}
}
private fun updateActions() {
val hasAccounts = accountsModel.items.isNotEmpty()
val serverPath = repositoriesModel.selectedItem?.wrappee?.ghRepositoryCoordinates?.serverPath
val isGithubServer = serverPath?.isGithubDotCom ?: false
applyAction.isEnabled = accountsModel.selectedItem != null
applyAction.visible = hasAccounts
githubLoginAction.visible = !hasAccounts && isGithubServer
tokenLoginAction.visible = !hasAccounts && isGithubServer
gheLoginActon.visible = !hasAccounts && !isGithubServer
}
}
companion object {
private const val ACTION_VISIBLE_KEY = "ACTION_VISIBLE"
private fun controlVisibilityFromAction(button: JButton, action: Action) {
fun update() {
button.isVisible = action.getValue(ACTION_VISIBLE_KEY) as? Boolean ?: true
}
action.addPropertyChangeListener {
update()
}
update()
}
private var Action.visible: Boolean
get() = getValue(ACTION_VISIBLE_KEY) as? Boolean ?: true
set(value) = putValue(ACTION_VISIBLE_KEY, value)
fun createLinkLabel(action: Action): ActionLink {
val label = ActionLink(action.getName()) {
action.actionPerformed(it)
}
label.isEnabled = action.isEnabled
label.isVisible = action.getValue(ACTION_VISIBLE_KEY) as? Boolean ?: true
action.addPropertyChangeListener {
label.text = action.getName()
label.isEnabled = action.isEnabled
label.isVisible = action.getValue(ACTION_VISIBLE_KEY) as? Boolean ?: true
}
return label
}
private fun <T> ComboBoxModel<T>.addSelectionChangeListener(listener: () -> Unit) {
addListDataListener(object : ListDataListener {
override fun contentsChanged(e: ListDataEvent) {
if (e.index0 == -1 && e.index1 == -1) listener()
}
override fun intervalAdded(e: ListDataEvent) {}
override fun intervalRemoved(e: ListDataEvent) {}
})
}
private fun ComboBoxWithActionsModel<GHGitRepositoryMapping>.preSelect() {
if (selectedItem != null) return
if (size == 0) return
selectedItem = getElementAt(0) as? ComboBoxWithActionsModel.Item.Wrapper
}
}
}
|
apache-2.0
|
42fa60f76993b13e06b8c256da436b66
| 40.896552 | 127 | 0.69586 | 5.270716 | false | false | false | false |
hermantai/samples
|
kotlin/udacity-kotlin-bootcamp/HelloKotlin/src/ams.kt
|
1
|
1951
|
import java.util.*
fun main(args: Array<String>) {
println("Hello, ${args[0]}!")
feedTheFish()
}
fun dayOfWeek() {
println("What day is it today?")
when(Calendar.getInstance().get(Calendar.DAY_OF_WEEK)) {
1 -> println("Sunday")
2 -> println("Monday")
3 -> println("Tuesday")
4 -> println("Wednesday")
5 -> println("Thursday")
6 -> println("Friday")
7 -> println("Saturday")
else -> println("Invalid")
}
}
fun feedTheFish() {
val day = randomDay()
val food = fishFood(day)
println("Today is $day and the fish eat $food")
if (shouldChangeWater(day)) {
println("Change the water today")
}
}
fun shouldChangeWater(
day: String,
temperature: Int = 22,
dirty: Int = 20) : Boolean {
return when {
isTooHot(temperature) -> true
dirty > 30 -> true
day == "Sunday" -> true
else -> false
}
}
fun isTooHot(temperature: Int)= temperature > 30
fun swim(time: Int, speed: String = "fast") {
println("Swimming $speed")
}
fun randomDay() : String {
val week = listOf("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
return week[Random().nextInt(7)]
}
fun fishFood (day : String) : String {
return when(day) {
"Monday" -> "flakes"
"Tuesday" -> "pellets"
"Wednesday" -> "redworms"
"Thursday" -> "granules"
"Friday" -> "mosquitoes"
"Saturday" -> "lettuce"
"Sunday" -> "plankton"
else -> "fasting"
}
}
var dirty = 20
val waterFilter: (Int) -> Int = { dirty -> dirty / 2}
fun feedFish(dirty: Int) = dirty + 10
// Kotlin prefers function parameter to be the last one
fun updateDirty(dirty: Int, operation: (Int) -> Int) : Int {
return operation(dirty)
}
fun dirtyProcessor() {
dirty = updateDirty(dirty, waterFilter)
dirty = updateDirty(dirty, ::feedFish)
// combine higher order function and lambdas: last paramater called syntax
dirty = updateDirty(dirty) {
dirty -> dirty + 50
}
}
|
apache-2.0
|
8f0d49e7817b6c933984662213fa51b9
| 21.436782 | 97 | 0.62122 | 3.290051 | false | false | false | false |
Turbo87/intellij-emberjs
|
src/main/kotlin/com/emberjs/configuration/utils/ElementUtils.kt
|
1
|
3375
|
package com.emberjs.configuration.utils
import org.jdom.Element
// taken from intellij-rust
// @see https://github.com/intellij-rust/intellij-rust/blob/322011b0a8bede40c10fd57cb7b816004047f405/src/main/kotlin/org/rust/cargo/runconfig/command/CargoCommandConfiguration.kt#L170
class ElementUtils {
companion object {
fun writeString(element: Element, elementName: String = "option", value: Any, name: String? = null) {
val opt = org.jdom.Element(elementName)
if (name != null) {
opt.setAttribute("name", name)
}
opt.setAttribute("value", value.toString())
element.addContent(opt)
}
fun readString(element: Element, elementName: String = "option", name: String? = null): String? {
return element.children
.find {
var matches = it.name == elementName
if (name != null) {
matches = matches && it.getAttributeValue("name") == name
}
matches
}
?.getAttributeValue("value")
}
fun writeBool(element: Element, elementName: String = "option", value: Boolean, name: String? = null) {
writeString(element, elementName, value.toString(), name)
}
fun readBool(element: Element, elementName: String = "option", name: String? = null) = readString(element, elementName, name)?.toBoolean()
fun removeField(element: Element, elementName: String = "option", name: String? = null) {
element.children
.find {
var matches = it.name == elementName
if (name != null) {
matches = matches && it.getAttributeValue("name") == name
}
matches
}
?.let { it.parent.removeContent(it) }
}
/**
* ENV uses the following structure:
* <envs>
* <env name="FOO" value="BAR" />
* </envs>
*/
fun readEnv(element: Element): Map<String, String>? {
val env = mutableMapOf<String, String>()
val envs = element.children
.find { it.name === "envs" } ?: return null
envs.let {
it.children
.filter { it.name === "env" }
.forEach {
env[it.getAttributeValue("name")] = it.getAttributeValue("value")
}
}
return env;
}
fun removeEnv(element: Element) {
element.children
.find { it.name === "envs" }
?.let { it.parentElement.removeContent(it) }
}
fun writeEnv(element: Element, map: Map<String, String>) {
val envs = org.jdom.Element("envs")
// do nothing if map is empty
if (map.size == 0) return
map.forEach {
val env = org.jdom.Element("env")
env.setAttribute("name", it.key)
env.setAttribute("value", it.value)
envs.addContent(env)
}
element.addContent(envs)
}
}
}
|
apache-2.0
|
3729a9ba4af38fe8e3cd94836ed7b65b
| 34.914894 | 183 | 0.491259 | 4.814551 | false | false | false | false |
hzsweers/CatchUp
|
libraries/base-ui/src/main/kotlin/io/sweers/catchup/base/ui/FloatProp.kt
|
1
|
1449
|
/*
* Copyright (C) 2020. Zac Sweers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.sweers.catchup.base.ui
import android.os.Build
import android.util.FloatProperty
import android.util.Property
/**
* A delegate for creating a [Property] of `float` type.
*/
abstract class FloatProp<T>(val name: String) {
abstract operator fun set(o: T, value: Float)
abstract operator fun get(o: T): Float
}
fun <T> createFloatProperty(impl: FloatProp<T>): Property<T, Float> {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
object : FloatProperty<T>(impl.name) {
override fun get(o: T): Float = impl[o]
override fun setValue(o: T, value: Float) {
impl[o] = value
}
}
} else {
object : Property<T, Float>(Float::class.java, impl.name) {
override fun get(o: T): Float = impl[o]
override fun set(o: T, value: Float) {
impl[o] = value
}
}
}
}
|
apache-2.0
|
ac43f0f9b8d41c89acc067e7973ffea8
| 29.1875 | 75 | 0.675638 | 3.586634 | false | false | false | false |
GunoH/intellij-community
|
platform/lang-impl/src/com/intellij/application/options/CodeCompletionConfigurable.kt
|
7
|
9199
|
// 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.application.options
import com.intellij.application.options.editor.EditorOptionsProvider
import com.intellij.codeInsight.CodeInsightSettings
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.ide.PowerSaveMode
import com.intellij.ide.ui.UISettings
import com.intellij.lang.LangBundle
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.application.ApplicationBundle
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
import com.intellij.openapi.extensions.BaseExtensionPointName
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.options.BoundCompositeConfigurable
import com.intellij.openapi.options.Configurable
import com.intellij.openapi.options.Configurable.WithEpDependencies
import com.intellij.openapi.options.UnnamedConfigurable
import com.intellij.openapi.options.ex.ConfigurableWrapper
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.DialogPanel
import com.intellij.ui.IdeUICustomization
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.JBRadioButton
import com.intellij.ui.dsl.builder.*
import com.intellij.ui.dsl.builder.Cell
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.layout.*
class CodeCompletionConfigurable : BoundCompositeConfigurable<UnnamedConfigurable>(
ApplicationBundle.message("title.code.completion"), "reference.settingsdialog.IDE.editor.code.completion"),
EditorOptionsProvider, WithEpDependencies {
companion object {
const val ID = "editor.preferences.completion"
private val LOG = Logger.getInstance(CodeCompletionConfigurable::class.java)
}
private lateinit var cbMatchCase: JBCheckBox
private lateinit var rbLettersOnly: JBRadioButton
private lateinit var rbAllOnly: JBRadioButton
override fun createConfigurables(): List<UnnamedConfigurable> =
ConfigurableWrapper.createConfigurables(CodeCompletionConfigurableEP.EP_NAME)
override fun getId() = ID
override fun getDependencies(): Collection<BaseExtensionPointName<*>> =
listOf(CodeCompletionConfigurableEP.EP_NAME)
var caseSensitive: Int
get() =
if (cbMatchCase.isSelected) {
if (rbAllOnly.isSelected) CodeInsightSettings.ALL else CodeInsightSettings.FIRST_LETTER
}
else {
CodeInsightSettings.NONE
}
set(value) =
when (value) {
CodeInsightSettings.ALL -> {
cbMatchCase.isSelected = true
rbAllOnly.setSelected(true)
}
CodeInsightSettings.NONE -> {
cbMatchCase.isSelected = false
}
CodeInsightSettings.FIRST_LETTER -> {
cbMatchCase.isSelected = true
rbLettersOnly.setSelected(true)
}
else -> LOG.warn("Unsupported caseSensitive: $value")
}
override fun reset() {
super<BoundCompositeConfigurable>.reset()
val codeInsightSettings = CodeInsightSettings.getInstance()
caseSensitive = codeInsightSettings.completionCaseSensitive
}
override fun apply() {
super.apply()
val codeInsightSettings = CodeInsightSettings.getInstance()
codeInsightSettings.completionCaseSensitive = caseSensitive
for (project in ProjectManager.getInstance().openProjects) {
DaemonCodeAnalyzer.getInstance(project).settingsChanged()
}
}
override fun isModified(): Boolean {
val result = super<BoundCompositeConfigurable>.isModified()
val codeInsightSettings = CodeInsightSettings.getInstance()
return result || caseSensitive != codeInsightSettings.completionCaseSensitive
}
override fun createPanel(): DialogPanel {
val actionManager = ActionManager.getInstance()
val settings = CodeInsightSettings.getInstance()
return panel {
buttonsGroup {
row {
cbMatchCase = checkBox(ApplicationBundle.message("completion.option.match.case"))
.component
rbLettersOnly = radioButton(ApplicationBundle.message("completion.option.first.letter.only"))
.enabledIf(cbMatchCase.selected)
.component.apply { isSelected = true }
rbAllOnly = radioButton(ApplicationBundle.message("completion.option.all.letters"))
.enabledIf(cbMatchCase.selected)
.component
}
}
val codeCompletion = OptionsApplicabilityFilter.isApplicable(OptionId.AUTOCOMPLETE_ON_BASIC_CODE_COMPLETION)
val smartTypeCompletion = OptionsApplicabilityFilter.isApplicable(OptionId.COMPLETION_SMART_TYPE)
if (codeCompletion || smartTypeCompletion) {
buttonsGroup(ApplicationBundle.message("label.autocomplete.when.only.one.choice")) {
if (codeCompletion) {
row {
checkBox(ApplicationBundle.message("checkbox.autocomplete.basic"))
.bindSelected(settings::AUTOCOMPLETE_ON_CODE_COMPLETION)
.gap(RightGap.SMALL)
comment(KeymapUtil.getFirstKeyboardShortcutText(actionManager.getAction(IdeActions.ACTION_CODE_COMPLETION)))
}
}
if (smartTypeCompletion) {
row {
checkBox(ApplicationBundle.message("checkbox.autocomplete.smart.type"))
.bindSelected(settings::AUTOCOMPLETE_ON_SMART_TYPE_COMPLETION)
.gap(RightGap.SMALL)
comment(KeymapUtil.getFirstKeyboardShortcutText(actionManager.getAction(IdeActions.ACTION_SMART_TYPE_COMPLETION)))
}
}
}
}
row {
checkBox(ApplicationBundle.message("completion.option.sort.suggestions.alphabetically"))
.bindSelected(UISettings.getInstance()::sortLookupElementsLexicographically)
}
lateinit var cbAutocompletion: Cell<JBCheckBox>
row {
cbAutocompletion = checkBox(ApplicationBundle.message("editbox.auto.complete") +
if (PowerSaveMode.isEnabled()) LangBundle.message("label.not.available.in.power.save.mode") else "")
.bindSelected(settings::AUTO_POPUP_COMPLETION_LOOKUP)
}
indent {
row {
checkBox(IdeUICustomization.getInstance().selectAutopopupByCharsText)
.bindSelected(settings::isSelectAutopopupSuggestionsByChars, settings::setSelectAutopopupSuggestionsByChars)
.enabledIf(cbAutocompletion.selected)
}
}
row {
val cbAutopopupJavaDoc = checkBox(ApplicationBundle.message("editbox.autopopup.javadoc.in"))
.bindSelected(settings::AUTO_POPUP_JAVADOC_INFO)
.gap(RightGap.SMALL)
intTextField(CodeInsightSettings.JAVADOC_INFO_DELAY_RANGE.asRange(), 100)
.bindIntText(settings::JAVADOC_INFO_DELAY)
.columns(4)
.enabledIf(cbAutopopupJavaDoc.selected)
.gap(RightGap.SMALL)
@Suppress("DialogTitleCapitalization")
label(ApplicationBundle.message("editbox.ms"))
}
if (OptionsApplicabilityFilter.isApplicable(OptionId.INSERT_PARENTHESES_AUTOMATICALLY)) {
row {
checkBox(ApplicationBundle.message("completion.option.insert.parentheses"))
.bindSelected(EditorSettingsExternalizable.getInstance()::isInsertParenthesesAutomatically,
EditorSettingsExternalizable.getInstance()::setInsertParenthesesAutomatically)
}
}
addOptions()
group(ApplicationBundle.message("title.parameter.info")) {
if (OptionsApplicabilityFilter.isApplicable(OptionId.SHOW_PARAMETER_NAME_HINTS_ON_COMPLETION)) {
row {
checkBox(ApplicationBundle.message("editbox.complete.with.parameters"))
.bindSelected(settings::SHOW_PARAMETER_NAME_HINTS_ON_COMPLETION)
}
}
row {
val cbParameterInfoPopup = checkBox(ApplicationBundle.message("editbox.autopopup.in"))
.bindSelected(settings::AUTO_POPUP_PARAMETER_INFO)
.gap(RightGap.SMALL)
intTextField(CodeInsightSettings.PARAMETER_INFO_DELAY_RANGE.asRange(), 100)
.bindIntText(settings::PARAMETER_INFO_DELAY)
.columns(4)
.enabledIf(cbParameterInfoPopup.selected)
.gap(RightGap.SMALL)
@Suppress("DialogTitleCapitalization")
label(ApplicationBundle.message("editbox.ms"))
}
row {
checkBox(ApplicationBundle.message("checkbox.show.full.signatures"))
.bindSelected(settings::SHOW_FULL_SIGNATURES_IN_PARAMETER_INFO)
}
}
addSections()
}
}
private fun Panel.addOptions() {
configurables.filter { it !is CodeCompletionOptionsCustomSection }
.forEach { appendDslConfigurable(it) }
}
private fun Panel.addSections() {
configurables.filterIsInstance<CodeCompletionOptionsCustomSection>()
.sortedWith(Comparator.comparing { c ->
(c as? Configurable)?.displayName ?: ""
})
.forEach { appendDslConfigurable(it) }
}
}
|
apache-2.0
|
63a37ec35dd17a3a59c7884a1cf2a09c
| 38.148936 | 136 | 0.70899 | 5.147734 | false | true | false | false |
GunoH/intellij-community
|
platform/vcs-impl/src/com/intellij/openapi/vcs/checkin/OptimizeImportsBeforeCheckinHandler.kt
|
1
|
1948
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.checkin
import com.intellij.codeInsight.CodeInsightBundle
import com.intellij.codeInsight.actions.AbstractLayoutCodeProcessor
import com.intellij.codeInsight.actions.OptimizeImportsProcessor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.changes.CommitContext
import com.intellij.openapi.vcs.changes.ui.BooleanCommitOption
import com.intellij.openapi.vcs.checkin.CheckinHandlerUtil.getPsiFiles
import com.intellij.openapi.vcs.ui.RefreshableOnComponent
import com.intellij.openapi.vfs.VirtualFile
class OptimizeOptionsCheckinHandlerFactory : CheckinHandlerFactory() {
override fun createHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler =
OptimizeImportsBeforeCheckinHandler(panel.project)
}
class OptimizeImportsBeforeCheckinHandler(project: Project) : CodeProcessorCheckinHandler(project) {
override fun getBeforeCheckinConfigurationPanel(): RefreshableOnComponent =
BooleanCommitOption(project, VcsBundle.message("checkbox.checkin.options.optimize.imports"), true,
settings::OPTIMIZE_IMPORTS_BEFORE_PROJECT_COMMIT)
override fun isEnabled(): Boolean = settings.OPTIMIZE_IMPORTS_BEFORE_PROJECT_COMMIT
override fun getProgressMessage(): String = VcsBundle.message("progress.text.optimizing.imports")
override fun createCodeProcessor(files: List<VirtualFile>): AbstractLayoutCodeProcessor =
OptimizeImportsProcessor(project, getPsiFiles(project, files), COMMAND_NAME, null)
companion object {
@JvmField
@NlsSafe
val COMMAND_NAME: String = CodeInsightBundle.message("process.optimize.imports.before.commit")
}
}
|
apache-2.0
|
ec7ea3998a55df66e81b942a26520490
| 47.725 | 140 | 0.820329 | 4.77451 | false | false | false | false |
McMoonLakeDev/MoonLake
|
API/src/main/kotlin/com/mcmoonlake/api/packet/PacketListenerLegacyAdapter.kt
|
1
|
3341
|
/*
* Copyright (C) 2016-Present The MoonLake ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mcmoonlake.api.packet
import org.bukkit.plugin.Plugin
import java.util.*
open class PacketListenerLegacyAdapter<P: PacketBukkitLegacy, T>(
final override val plugin: Plugin,
final override val priority: PacketListenerPriority,
val legacyAdapter: PacketLegacyAdapter<P, T>
) : PacketListener where T: PacketBukkitLegacy, T: PacketLegacy {
private val _sendingTypes: MutableSet<Class<out PacketOut>> = HashSet()
private val _receivingTypes: MutableSet<Class<out PacketIn>> = HashSet()
constructor(plugin: Plugin, legacyAdapter: PacketLegacyAdapter<P, T>) : this(plugin, PacketListenerPriority.NORMAL, legacyAdapter)
init {
val clazz = legacyAdapter.result
if(!Packets.isRegisteredWrapped(clazz))
throw IllegalArgumentException("待监听的数据包包装类 $clazz 没有注册.")
when(PacketOut::class.java.isAssignableFrom(clazz)) {
true -> _sendingTypes.add(clazz.asSubclass(PacketOut::class.java))
false -> _receivingTypes.add(clazz.asSubclass(PacketIn::class.java))
}
}
final override val sendingTypes: Set<Class<out PacketOut>>
get() = if(_sendingTypes.isEmpty()) Collections.emptySet() else HashSet(_sendingTypes)
final override val receivingTypes: Set<Class<out PacketIn>>
get() = if(_receivingTypes.isEmpty()) Collections.emptySet() else HashSet(_receivingTypes)
override fun onSending(event: PacketEvent) {}
override fun onReceiving(event: PacketEvent) {}
override fun handlerException(ex: Exception) { ex.printStackTrace() }
final override fun equals(other: Any?): Boolean {
if(other === this)
return true
if(other is PacketListenerLegacyAdapter<*, *>)
return plugin == other.plugin && priority == other.priority && legacyAdapter == other.legacyAdapter && _sendingTypes == other._sendingTypes && _receivingTypes == other._receivingTypes
return false
}
final override fun hashCode(): Int {
var result = plugin.hashCode()
result = 31 * result + priority.hashCode()
result = 31 * result + legacyAdapter.hashCode()
result = 31 * result + _sendingTypes.hashCode()
result = 31 * result + _receivingTypes.hashCode()
return result
}
final override fun toString(): String {
return "PacketListenerLegacy(plugin=$plugin, priority=$priority, legacyAdapter=$legacyAdapter, sendingTypes=$_sendingTypes, receivingTypes=$_receivingTypes)"
}
val PacketEvent.isLegacy: Boolean
get() = legacyAdapter.isLegacy
}
|
gpl-3.0
|
5f1f01364159110d8c05cab6ce5bbabc
| 40.936709 | 195 | 0.701479 | 4.423231 | false | false | false | false |
dbrant/apps-android-wikipedia
|
app/src/main/java/org/wikipedia/feed/mostread/MostReadFragment.kt
|
1
|
5617
|
package org.wikipedia.feed.mostread
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityOptionsCompat
import androidx.core.os.bundleOf
import androidx.core.util.Pair
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import org.wikipedia.Constants
import org.wikipedia.Constants.InvokeSource
import org.wikipedia.R
import org.wikipedia.databinding.FragmentMostReadBinding
import org.wikipedia.feed.model.Card
import org.wikipedia.feed.view.ListCardItemView
import org.wikipedia.history.HistoryEntry
import org.wikipedia.json.GsonMarshaller
import org.wikipedia.json.GsonUnmarshaller
import org.wikipedia.page.ExclusiveBottomSheetPresenter
import org.wikipedia.page.PageActivity
import org.wikipedia.readinglist.AddToReadingListDialog
import org.wikipedia.readinglist.MoveToReadingListDialog
import org.wikipedia.readinglist.ReadingListBehaviorsUtil
import org.wikipedia.util.DimenUtil
import org.wikipedia.util.FeedbackUtil
import org.wikipedia.util.L10nUtil
import org.wikipedia.util.TabUtil
import org.wikipedia.views.DefaultRecyclerAdapter
import org.wikipedia.views.DefaultViewHolder
import org.wikipedia.views.DrawableItemDecoration
class MostReadFragment : Fragment() {
private var _binding: FragmentMostReadBinding? = null
private val binding get() = _binding!!
private val bottomSheetPresenter = ExclusiveBottomSheetPresenter()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
super.onCreateView(inflater, container, savedInstanceState)
_binding = FragmentMostReadBinding.inflate(inflater, container, false)
val card = GsonUnmarshaller.unmarshal(MostReadListCard::class.java, requireActivity().intent.getStringExtra(MostReadArticlesActivity.MOST_READ_CARD))
(requireActivity() as AppCompatActivity).supportActionBar?.title = getString(R.string.top_read_activity_title, card.subtitle())
L10nUtil.setConditionalLayoutDirection(binding.root, card.wikiSite().languageCode())
binding.mostReadRecyclerView.layoutManager = LinearLayoutManager(context)
binding.mostReadRecyclerView.addItemDecoration(DrawableItemDecoration(requireContext(), R.attr.list_separator_drawable))
binding.mostReadRecyclerView.isNestedScrollingEnabled = false
binding.mostReadRecyclerView.adapter = RecyclerAdapter(card.items(), Callback())
return binding.root
}
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
private class RecyclerAdapter constructor(items: List<MostReadItemCard>, private val callback: Callback) :
DefaultRecyclerAdapter<MostReadItemCard, ListCardItemView>(items) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DefaultViewHolder<ListCardItemView> {
return DefaultViewHolder(ListCardItemView(parent.context))
}
override fun onBindViewHolder(holder: DefaultViewHolder<ListCardItemView>, position: Int) {
val card = item(position)
holder.view.setCard(card).setHistoryEntry(HistoryEntry(card.pageTitle(),
HistoryEntry.SOURCE_FEED_MOST_READ_ACTIVITY)).setCallback(callback)
}
}
private inner class Callback : ListCardItemView.Callback {
override fun onSelectPage(card: Card, entry: HistoryEntry, openInNewBackgroundTab: Boolean) {
if (openInNewBackgroundTab) {
TabUtil.openInNewBackgroundTab(entry)
FeedbackUtil.showMessage(requireActivity(), R.string.article_opened_in_background_tab)
} else {
startActivity(PageActivity.newIntentForNewTab(requireContext(), entry, entry.title))
}
}
override fun onSelectPage(card: Card, entry: HistoryEntry, sharedElements: Array<Pair<View, String>>) {
val options = ActivityOptionsCompat.makeSceneTransitionAnimation(requireActivity(), *sharedElements)
val intent = PageActivity.newIntentForNewTab(requireContext(), entry, entry.title)
if (sharedElements.isNotEmpty()) {
intent.putExtra(Constants.INTENT_EXTRA_HAS_TRANSITION_ANIM, true)
}
startActivity(intent, if (DimenUtil.isLandscape(requireContext()) || sharedElements.isEmpty()) null else options.toBundle())
}
override fun onAddPageToList(entry: HistoryEntry, addToDefault: Boolean) {
if (addToDefault) {
ReadingListBehaviorsUtil.addToDefaultList(requireActivity(),
entry.title, InvokeSource.MOST_READ_ACTIVITY) { readingListId -> onMovePageToList(readingListId, entry) }
} else {
bottomSheetPresenter.show(childFragmentManager,
AddToReadingListDialog.newInstance(entry.title, InvokeSource.MOST_READ_ACTIVITY))
}
}
override fun onMovePageToList(sourceReadingListId: Long, entry: HistoryEntry) {
bottomSheetPresenter.show(childFragmentManager,
MoveToReadingListDialog.newInstance(sourceReadingListId, entry.title, InvokeSource.MOST_READ_ACTIVITY))
}
}
companion object {
fun newInstance(card: MostReadItemCard): MostReadFragment {
return MostReadFragment().apply {
arguments = bundleOf(MostReadArticlesActivity.MOST_READ_CARD to GsonMarshaller.marshal(card))
}
}
}
}
|
apache-2.0
|
4ddca9808aed81414e516f02e22273f7
| 46.201681 | 157 | 0.740253 | 5.115665 | false | false | false | false |
dkandalov/katas
|
kotlin/src/katas/kotlin/leetcode/fruit_into_baskets/FruitIntoBaskets.kt
|
1
|
1377
|
package katas.kotlin.leetcode.fruit_into_baskets
import datsok.*
import org.junit.*
/**
* https://leetcode.com/problems/fruit-into-baskets/
*/
class FruitIntoBasketsTests {
@Test fun `count amount of fruit collected into baskets`() {
totalFruit(intArrayOf()) shouldEqual 0
totalFruit(intArrayOf(1)) shouldEqual 1
totalFruit(intArrayOf(1, 2)) shouldEqual 2
totalFruit(intArrayOf(1, 2, 3)) shouldEqual 2
totalFruit(intArrayOf(1, 2, 1)) shouldEqual 3
totalFruit(intArrayOf(1, 2, 3, 3)) shouldEqual 3
totalFruit(intArrayOf(1, 2, 1, 3)) shouldEqual 3
totalFruit(intArrayOf(0, 1, 2, 2)) shouldEqual 3
totalFruit(intArrayOf(1, 2, 3, 2, 2)) shouldEqual 4
totalFruit(intArrayOf(3, 3, 3, 1, 2, 1, 1, 2, 3, 3, 4)) shouldEqual 5
}
private fun totalFruit(tree: IntArray): Int {
var maxCount = 0
var count = 0
val bucket = HashSet<Int>()
tree.indices.forEach { i ->
bucket.add(tree[i])
if (bucket.size <= 2) {
count++
} else {
maxCount = maxOf(maxCount, count)
bucket.clear()
bucket.add(tree[i - 1])
bucket.add(tree[i])
count = 2
}
}
maxCount = maxOf(maxCount, count)
return maxCount
}
}
|
unlicense
|
03f87439dca808378ff4bec98077fad8
| 29.622222 | 77 | 0.564996 | 3.911932 | false | false | false | false |
tateisu/SubwayTooter
|
app/src/main/java/jp/juggler/subwaytooter/column/ColumnActions.kt
|
1
|
15861
|
package jp.juggler.subwaytooter.column
import jp.juggler.subwaytooter.api.TootParser
import jp.juggler.subwaytooter.api.entity.*
import jp.juggler.subwaytooter.columnviewholder.onListListUpdated
import jp.juggler.subwaytooter.notification.onNotificationCleared
import jp.juggler.subwaytooter.table.SavedAccount
import jp.juggler.subwaytooter.util.BucketList
import jp.juggler.subwaytooter.util.matchHost
import jp.juggler.util.*
import kotlinx.coroutines.launch
import kotlin.collections.set
private val log = LogCategory("ColumnActions")
/*
なんらかアクションを行った後にカラムデータを更新する処理など
*/
// 予約した投稿を削除した後の処理
fun Column.onScheduleDeleted(item: TootScheduled) {
val tmpList = ArrayList<TimelineItem>(listData.size)
for (o in listData) {
if (o === item) continue
tmpList.add(o)
}
if (tmpList.size != listData.size) {
listData.clear()
listData.addAll(tmpList)
fireShowContent(reason = "onScheduleDeleted")
}
}
// ステータスが削除された時に呼ばれる
fun Column.onStatusRemoved(tlHost: Host, statusId: EntityId) {
if (isDispose.get() || bInitialLoading || bRefreshLoading) return
if (!accessInfo.matchHost(tlHost)) return
val tmpList = ArrayList<TimelineItem>(listData.size)
for (o in listData) {
if (o is TootStatus) {
if (statusId == o.id) continue
if (statusId == (o.reblog?.id ?: -1L)) continue
} else if (o is TootNotification) {
val s = o.status
if (s != null) {
if (statusId == s.id) continue
if (statusId == (s.reblog?.id ?: -1L)) continue
}
}
tmpList.add(o)
}
if (tmpList.size != listData.size) {
listData.clear()
listData.addAll(tmpList)
fireShowContent(reason = "removeStatus")
}
}
// ブーストやお気に入りの更新に使う。ステータスを列挙する。
fun Column.findStatus(
targetApDomain: Host,
targetStatusId: EntityId,
callback: (account: SavedAccount, status: TootStatus) -> Boolean,
// callback return true if rebind view required
) {
if (!accessInfo.matchHost(targetApDomain)) return
var bChanged = false
fun procStatus(status: TootStatus?) {
if (status != null) {
if (targetStatusId == status.id) {
if (callback(accessInfo, status)) bChanged = true
}
procStatus(status.reblog)
}
}
for (data in listData) {
when (data) {
is TootNotification -> procStatus(data.status)
is TootStatus -> procStatus(data)
}
}
if (bChanged) fireRebindAdapterItems()
}
private const val INVALID_ACCOUNT = -1L
// ミュート、ブロックが成功した時に呼ばれる
// リストメンバーカラムでメンバーをリストから除去した時に呼ばれる
fun Column.removeAccountInTimeline(
targetAccount: SavedAccount,
whoId: EntityId,
removeFromUserList: Boolean = false,
) {
if (targetAccount != accessInfo) return
val tmpList = ArrayList<TimelineItem>(listData.size)
for (o in listData) {
if (o is TootStatus) {
if (whoId == (o.account.id)) continue
if (whoId == (o.reblog?.account?.id ?: INVALID_ACCOUNT)) continue
} else if (o is TootNotification) {
if (whoId == (o.account?.id ?: INVALID_ACCOUNT)) continue
if (whoId == (o.status?.account?.id ?: INVALID_ACCOUNT)) continue
if (whoId == (o.status?.reblog?.account?.id ?: INVALID_ACCOUNT)) continue
} else if (o is TootAccountRef && removeFromUserList) {
if (whoId == o.get().id) continue
}
tmpList.add(o)
}
if (tmpList.size != listData.size) {
listData.clear()
listData.addAll(tmpList)
fireShowContent(reason = "removeAccountInTimeline")
}
}
// ミュート、ブロックが成功した時に呼ばれる
// リストメンバーカラムでメンバーをリストから除去した時に呼ばれる
// require full acct
fun Column.removeAccountInTimelinePseudo(acct: Acct) {
val tmpList = ArrayList<TimelineItem>(listData.size)
for (o in listData) {
if (o is TootStatus) {
if (acct == accessInfo.getFullAcct(o.account)) continue
if (acct == accessInfo.getFullAcct(o.reblog?.account)) continue
} else if (o is TootNotification) {
if (acct == accessInfo.getFullAcct(o.account)) continue
if (acct == accessInfo.getFullAcct(o.status?.account)) continue
if (acct == accessInfo.getFullAcct(o.status?.reblog?.account)) continue
}
tmpList.add(o)
}
if (tmpList.size != listData.size) {
listData.clear()
listData.addAll(tmpList)
fireShowContent(reason = "removeAccountInTimelinePseudo")
}
}
// misskeyカラムやプロフカラムでブロック成功した時に呼ばれる
fun Column.updateFollowIcons(targetAccount: SavedAccount) {
if (targetAccount != accessInfo) return
fireShowContent(reason = "updateFollowIcons", reset = true)
}
// ユーザのブロック、ミュート、フォロー推奨の削除、フォローリクエストの承認/却下などから呼ばれる
fun Column.removeUser(targetAccount: SavedAccount, columnType: ColumnType, whoId: EntityId) {
if (type == columnType && targetAccount == accessInfo) {
val tmpList = ArrayList<TimelineItem>(listData.size)
for (o in listData) {
if (o is TootAccountRef) {
if (o.get().id == whoId) continue
}
tmpList.add(o)
}
if (tmpList.size != listData.size) {
listData.clear()
listData.addAll(tmpList)
fireShowContent(reason = "removeUser")
}
}
}
// 通知カラムの通知を全て削除した後に呼ばれる
fun Column.removeNotifications() {
cancelLastTask()
mRefreshLoadingErrorPopupState = 0
mRefreshLoadingError = ""
bRefreshLoading = false
mInitialLoadingError = ""
bInitialLoading = false
idOld = null
idRecent = null
offsetNext = 0
pagingType = ColumnPagingType.Default
listData.clear()
duplicateMap.clear()
fireShowContent(reason = "removeNotifications", reset = true)
EmptyScope.launch {
try {
onNotificationCleared(context, accessInfo.db_id)
} catch (ex: Throwable) {
log.trace(ex, "onNotificationCleared failed.")
}
}
}
// 通知を削除した後に呼ばれる
fun Column.removeNotificationOne(targetAccount: SavedAccount, notification: TootNotification) {
if (!isNotificationColumn) return
if (accessInfo != targetAccount) return
val tmpList = ArrayList<TimelineItem>(listData.size)
for (o in listData) {
if (o is TootNotification) {
if (o.id == notification.id) continue
}
tmpList.add(o)
}
if (tmpList.size != listData.size) {
listData.clear()
listData.addAll(tmpList)
fireShowContent(reason = "removeNotificationOne")
}
}
fun Column.onMuteUpdated() {
val checker = { status: TootStatus? -> status?.checkMuted() ?: false }
val tmpList = ArrayList<TimelineItem>(listData.size)
for (o in listData) {
if (o is TootStatus) {
if (checker(o)) continue
}
if (o is TootNotification) {
if (checker(o.status)) continue
}
tmpList.add(o)
}
if (tmpList.size != listData.size) {
listData.clear()
listData.addAll(tmpList)
fireShowContent(reason = "onMuteUpdated")
}
}
fun Column.replaceStatus(statusId: EntityId, statusJson: JsonObject) {
if (type == ColumnType.STATUS_HISTORY) return
fun createStatus() =
TootParser(context, accessInfo).status(statusJson)
?: error("replaceStatus: parse failed.")
val tmpList = ArrayList(listData)
var changed = false
for (i in 0 until tmpList.size) {
when (val item = tmpList[i]) {
is TootStatus -> {
if (item.id == statusId) {
tmpList[i] = createStatus()
changed = true
} else if (item.reblog?.id == statusId) {
item.reblog = createStatus().also { it.reblogParent = item }
changed = true
}
}
is TootNotification -> {
if (item.status?.id == statusId) {
item.status = createStatus()
changed = true
}
}
}
}
if (changed) {
listData.clear()
listData.addAll(tmpList)
fireShowContent(reason = "replaceStatus")
}
}
fun Column.onHideFavouriteNotification(acct: Acct) {
if (!isNotificationColumn) return
val tmpList = ArrayList<TimelineItem>(listData.size)
for (o in listData) {
if (o is TootNotification && o.type != TootNotification.TYPE_MENTION) {
val who = o.account
if (who != null) {
val whoAcct = accessInfo.getFullAcct(who)
if (whoAcct == acct) continue
}
}
tmpList.add(o)
}
if (tmpList.size != listData.size) {
listData.clear()
listData.addAll(tmpList)
fireShowContent(reason = "onHideFavouriteNotification")
}
}
fun Column.onDomainBlockChanged(
targetAccount: SavedAccount,
domain: Host,
bBlocked: Boolean,
) {
if (targetAccount.apiHost != accessInfo.apiHost) return
if (accessInfo.isPseudo) return
if (type == ColumnType.DOMAIN_BLOCKS) {
// ドメインブロック一覧を読み直す
startLoading()
return
}
if (bBlocked) {
// ブロックしたのとドメイン部分が一致するアカウントからのステータスと通知をすべて除去する
val checker =
{ account: TootAccount? -> if (account == null) false else account.acct.host == domain }
val tmpList = ArrayList<TimelineItem>(listData.size)
for (o in listData) {
if (o is TootStatus) {
if (checker(o.account)) continue
if (checker(o.reblog?.account)) continue
} else if (o is TootNotification) {
if (checker(o.account)) continue
if (checker(o.status?.account)) continue
if (checker(o.status?.reblog?.account)) continue
}
tmpList.add(o)
}
if (tmpList.size != listData.size) {
listData.clear()
listData.addAll(tmpList)
fireShowContent(reason = "onDomainBlockChanged")
}
}
}
fun Column.onListListUpdated(account: SavedAccount) {
if (account != accessInfo) return
if (type == ColumnType.LIST_LIST || type == ColumnType.MISSKEY_ANTENNA_LIST) {
startLoading()
val vh = viewHolder
vh?.onListListUpdated()
}
}
fun Column.onListNameUpdated(account: SavedAccount, item: TootList) {
if (account != accessInfo) return
if (type == ColumnType.LIST_LIST) {
startLoading()
} else if (type == ColumnType.LIST_TL || type == ColumnType.LIST_MEMBER) {
if (item.id == profileId) {
this.listInfo = item
fireShowColumnHeader()
}
}
}
// fun onAntennaNameUpdated(account : SavedAccount, item : MisskeyAntenna) {
// if(account != access_info) return
// if(type == ColumnType.MISSKEY_ANTENNA_LIST) {
// startLoading()
// } else if(type == ColumnType.MISSKEY_ANTENNA_TL) {
// if(item.id == profile_id) {
// this.antenna_info = item
// fireShowColumnHeader()
// }
// }
// }
fun Column.onListMemberUpdated(
account: SavedAccount,
listId: EntityId,
who: TootAccount,
bAdd: Boolean,
) {
if (type == ColumnType.LIST_TL && accessInfo == account && listId == profileId) {
if (!bAdd) {
removeAccountInTimeline(account, who.id)
}
} else if (type == ColumnType.LIST_MEMBER && accessInfo == account && listId == profileId) {
if (!bAdd) {
removeAccountInTimeline(account, who.id)
}
}
}
// 既存データ中の会話サマリ項目と追加データの中にIDが同じものがあれば
// 既存データを入れ替えて追加データから削除するか
// 既存データを削除するかする
fun replaceConversationSummary(
changeList: ArrayList<AdapterChange>,
listNew: ArrayList<TimelineItem>,
listData: BucketList<TimelineItem>,
) {
val newMap = HashMap<EntityId, TootConversationSummary>().apply {
for (o in listNew) {
if (o is TootConversationSummary) this[o.id] = o
}
}
if (listData.isEmpty() || newMap.isEmpty()) return
val removeSet = HashSet<EntityId>()
for (i in listData.size - 1 downTo 0) {
val o = listData[i] as? TootConversationSummary ?: continue
val newItem = newMap[o.id] ?: continue
if (o.last_status.uri == newItem.last_status.uri) {
// 投稿が同じなので順序を入れ替えず、その場所で更新する
changeList.add(AdapterChange(AdapterChangeType.RangeChange, i, 1))
listData[i] = newItem
removeSet.add(newItem.id)
log.d("replaceConversationSummary: in-place update")
} else {
// 投稿が異なるので古い方を削除して、リストの順序を変える
changeList.add(AdapterChange(AdapterChangeType.RangeRemove, i, 1))
listData.removeAt(i)
log.d("replaceConversationSummary: order change")
}
}
val it = listNew.iterator()
while (it.hasNext()) {
val o = it.next() as? TootConversationSummary ?: continue
if (removeSet.contains(o.id)) it.remove()
}
}
// タグのフォロー状態が変わったら呼ばれる
fun Column.onTagFollowChanged(account: SavedAccount, newTag: TootTag) {
if (isDispose.get() || bInitialLoading || bRefreshLoading) return
if (accessInfo != account) return
when (type) {
ColumnType.FOLLOWED_HASHTAGS, ColumnType.TREND_TAG, ColumnType.SEARCH -> {
val tmpList = ArrayList<TimelineItem>(listData.size)
for (o in listData) {
if (o is TootTag && o.name == newTag.name) {
tmpList.add(newTag)
} else {
tmpList.add(o)
}
}
if (type == ColumnType.FOLLOWED_HASHTAGS) {
val tagFinder: (TimelineItem) -> Boolean =
{ it is TootTag && it.name == newTag.name }
when (newTag.following) {
true ->
if (tmpList.none(tagFinder)) {
tmpList.add(0, newTag)
}
else -> tmpList.indexOfFirst(tagFinder)
.takeIf { it >= 0 }?.let { tmpList.removeAt(it) }
}
}
listData.clear()
listData.addAll(tmpList)
fireShowContent(reason = "onTagFollowChanged")
}
else -> Unit
}
}
|
apache-2.0
|
e62d63e4eaa63eec409f98af960dbfd6
| 29.439746 | 100 | 0.579584 | 3.918577 | false | false | false | false |
github/codeql
|
java/kotlin-extractor/src/main/kotlin/KotlinUsesExtractor.kt
|
1
|
86075
|
package com.github.codeql
import com.github.codeql.utils.*
import com.github.codeql.utils.versions.codeQlWithHasQuestionMark
import com.github.codeql.utils.versions.getKotlinType
import com.github.codeql.utils.versions.isRawType
import com.semmle.extractor.java.OdasaOutput
import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
import org.jetbrains.kotlin.backend.common.ir.*
import org.jetbrains.kotlin.backend.common.lower.parents
import org.jetbrains.kotlin.backend.common.lower.parentsWithSelf
import org.jetbrains.kotlin.backend.jvm.ir.propertyIfAccessor
import org.jetbrains.kotlin.codegen.JvmCodegenUtil
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.ir.ObsoleteDescriptorBasedAPI
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.symbols.*
import org.jetbrains.kotlin.ir.types.*
import org.jetbrains.kotlin.ir.types.impl.*
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.load.java.BuiltinMethodsWithSpecialGenericSignature
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.load.java.sources.JavaSourceElement
import org.jetbrains.kotlin.load.java.structure.*
import org.jetbrains.kotlin.load.java.typeEnhancement.hasEnhancedNullability
import org.jetbrains.kotlin.load.kotlin.getJvmModuleNameForDeserializedDescriptor
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.NameUtils
import org.jetbrains.kotlin.name.SpecialNames
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.util.OperatorNameConventions
open class KotlinUsesExtractor(
open val logger: Logger,
open val tw: TrapWriter,
val dependencyCollector: OdasaOutput.TrapFileManager?,
val externalClassExtractor: ExternalDeclExtractor,
val primitiveTypeMapping: PrimitiveTypeMapping,
val pluginContext: IrPluginContext,
val globalExtensionState: KotlinExtractorGlobalState
) {
val javaLangObject by lazy {
val result = pluginContext.referenceClass(FqName("java.lang.Object"))?.owner
result?.let { extractExternalClassLater(it) }
result
}
val javaLangObjectType by lazy {
javaLangObject?.typeWith()
}
private fun usePackage(pkg: String): Label<out DbPackage> {
return extractPackage(pkg)
}
fun extractPackage(pkg: String): Label<out DbPackage> {
val pkgLabel = "@\"package;$pkg\""
val id: Label<DbPackage> = tw.getLabelFor(pkgLabel, {
tw.writePackages(it, pkg)
})
return id
}
fun useFileClassType(f: IrFile) = TypeResults(
TypeResult(extractFileClass(f), "", ""),
TypeResult(fakeKotlinType(), "", "")
)
@OptIn(kotlin.ExperimentalStdlibApi::class) // Annotation required by kotlin versions < 1.5
fun extractFileClass(f: IrFile): Label<out DbClass> {
val fileName = f.fileEntry.name
val pkg = f.fqName.asString()
val defaultName = fileName.replaceFirst(Regex(""".*[/\\]"""), "").replaceFirst(Regex("""\.kt$"""), "").replaceFirstChar({ it.uppercase() }) + "Kt"
var jvmName = getJvmName(f) ?: defaultName
val qualClassName = if (pkg.isEmpty()) jvmName else "$pkg.$jvmName"
val label = "@\"class;$qualClassName\""
val id: Label<DbClass> = tw.getLabelFor(label, {
val fileId = tw.mkFileId(f.path, false)
val locId = tw.getWholeFileLocation(fileId)
val pkgId = extractPackage(pkg)
tw.writeClasses(it, jvmName, pkgId, it)
tw.writeFile_class(it)
tw.writeHasLocation(it, locId)
addModifiers(it, "public", "final")
})
return id
}
data class UseClassInstanceResult(val typeResult: TypeResult<DbClassorinterface>, val javaClass: IrClass)
fun useType(t: IrType, context: TypeContext = TypeContext.OTHER): TypeResults {
when(t) {
is IrSimpleType -> return useSimpleType(t, context)
else -> {
logger.error("Unrecognised IrType: " + t.javaClass)
return extractErrorType()
}
}
}
private fun extractJavaErrorType(): TypeResult<DbErrortype> {
val typeId = tw.getLabelFor<DbErrortype>("@\"errorType\"") {
tw.writeError_type(it)
}
return TypeResult(typeId, "<CodeQL error type>", "<CodeQL error type>")
}
private fun extractErrorType(): TypeResults {
val javaResult = extractJavaErrorType()
val kotlinTypeId = tw.getLabelFor<DbKt_nullable_type>("@\"errorKotlinType\"") {
tw.writeKt_nullable_types(it, javaResult.id)
}
return TypeResults(javaResult,
TypeResult(kotlinTypeId, "<CodeQL error type>", "<CodeQL error type>"))
}
fun getJavaEquivalentClass(c: IrClass) =
getJavaEquivalentClassId(c)?.let { pluginContext.referenceClass(it.asSingleFqName()) }?.owner
/**
* Gets a KotlinFileExtractor based on this one, except it attributes locations to the file that declares the given class.
*/
private fun withFileOfClass(cls: IrClass): KotlinFileExtractor {
val clsFile = cls.fileOrNull
if (this is KotlinFileExtractor && this.filePath == clsFile?.path) {
return this
}
val newDeclarationStack =
if (this is KotlinFileExtractor)
this.declarationStack
else
KotlinFileExtractor.DeclarationStack()
if (clsFile == null || isExternalDeclaration(cls)) {
val filePath = getIrClassBinaryPath(cls)
val newTrapWriter = tw.makeFileTrapWriter(filePath, true)
val newLoggerTrapWriter = logger.tw.makeFileTrapWriter(filePath, false)
val newLogger = FileLogger(logger.loggerBase, newLoggerTrapWriter)
return KotlinFileExtractor(newLogger, newTrapWriter, null, filePath, dependencyCollector, externalClassExtractor, primitiveTypeMapping, pluginContext, newDeclarationStack, globalExtensionState)
}
val newTrapWriter = tw.makeSourceFileTrapWriter(clsFile, true)
val newLoggerTrapWriter = logger.tw.makeSourceFileTrapWriter(clsFile, false)
val newLogger = FileLogger(logger.loggerBase, newLoggerTrapWriter)
return KotlinFileExtractor(newLogger, newTrapWriter, null, clsFile.path, dependencyCollector, externalClassExtractor, primitiveTypeMapping, pluginContext, newDeclarationStack, globalExtensionState)
}
// The Kotlin compiler internal representation of Outer<T>.Inner<S>.InnerInner<R> is InnerInner<R, S, T>. This function returns just `R`.
fun removeOuterClassTypeArgs(c: IrClass, argsIncludingOuterClasses: List<IrTypeArgument>?): List<IrTypeArgument>? {
return argsIncludingOuterClasses?.let {
if (it.size > c.typeParameters.size)
it.take(c.typeParameters.size)
else
null
} ?: argsIncludingOuterClasses
}
private fun isStaticClass(c: IrClass) = c.visibility != DescriptorVisibilities.LOCAL && !c.isInner
// Gets nested inner classes starting at `c` and proceeding outwards to the innermost enclosing static class.
// For example, for (java syntax) `class A { static class B { class C { class D { } } } }`,
// `nonStaticParentsWithSelf(D)` = `[D, C, B]`.
private fun parentsWithTypeParametersInScope(c: IrClass): List<IrDeclarationParent> {
val parentsList = c.parentsWithSelf.toList()
val firstOuterClassIdx = parentsList.indexOfFirst { it is IrClass && isStaticClass(it) }
return if (firstOuterClassIdx == -1) parentsList else parentsList.subList(0, firstOuterClassIdx + 1)
}
// Gets the type parameter symbols that are in scope for class `c` in Kotlin order (i.e. for
// `class NotInScope<T> { static class OutermostInScope<A, B> { class QueryClass<C, D> { } } }`,
// `getTypeParametersInScope(QueryClass)` = `[C, D, A, B]`.
private fun getTypeParametersInScope(c: IrClass) =
parentsWithTypeParametersInScope(c).mapNotNull({ getTypeParameters(it) }).flatten()
// Returns a map from `c`'s type variables in scope to type arguments `argsIncludingOuterClasses`.
// Hack for the time being: the substituted types are always nullable, to prevent downstream code
// from replacing a generic parameter by a primitive. As and when we extract Kotlin types we will
// need to track this information in more detail.
private fun makeTypeGenericSubstitutionMap(c: IrClass, argsIncludingOuterClasses: List<IrTypeArgument>) =
getTypeParametersInScope(c).map({ it.symbol }).zip(argsIncludingOuterClasses.map { it.withQuestionMark(true) }).toMap()
fun makeGenericSubstitutionFunction(c: IrClass, argsIncludingOuterClasses: List<IrTypeArgument>) =
makeTypeGenericSubstitutionMap(c, argsIncludingOuterClasses).let {
{ x: IrType, useContext: TypeContext, pluginContext: IrPluginContext ->
x.substituteTypeAndArguments(
it,
useContext,
pluginContext
)
}
}
// The Kotlin compiler internal representation of Outer<A, B>.Inner<C, D>.InnerInner<E, F>.someFunction<G, H>.LocalClass<I, J> is LocalClass<I, J, G, H, E, F, C, D, A, B>. This function returns [A, B, C, D, E, F, G, H, I, J].
private fun orderTypeArgsLeftToRight(c: IrClass, argsIncludingOuterClasses: List<IrTypeArgument>?): List<IrTypeArgument>? {
if(argsIncludingOuterClasses.isNullOrEmpty())
return argsIncludingOuterClasses
val ret = ArrayList<IrTypeArgument>()
// Iterate over nested inner classes starting at `c`'s surrounding top-level or static nested class and ending at `c`, from the outermost inwards:
val truncatedParents = parentsWithTypeParametersInScope(c)
for(parent in truncatedParents.reversed()) {
val parentTypeParameters = getTypeParameters(parent)
val firstArgIdx = argsIncludingOuterClasses.size - (ret.size + parentTypeParameters.size)
ret.addAll(argsIncludingOuterClasses.subList(firstArgIdx, firstArgIdx + parentTypeParameters.size))
}
return ret
}
// `typeArgs` can be null to describe a raw generic type.
// For non-generic types it will be zero-length list.
fun useClassInstance(c: IrClass, typeArgs: List<IrTypeArgument>?, inReceiverContext: Boolean = false): UseClassInstanceResult {
val substituteClass = getJavaEquivalentClass(c)
val extractClass = substituteClass ?: c
// `KFunction1<T1,T2>` is substituted by `KFunction<T>`. The last type argument is the return type.
// Similarly Function23 and above get replaced by kotlin.jvm.functions.FunctionN with only one type arg, the result type.
// References to SomeGeneric<T1, T2, ...> where SomeGeneric is declared SomeGeneric<T1, T2, ...> are extracted
// as if they were references to the unbound type SomeGeneric.
val extractedTypeArgs = when {
extractClass.symbol.isKFunction() && typeArgs != null && typeArgs.isNotEmpty() -> listOf(typeArgs.last())
extractClass.fqNameWhenAvailable == FqName("kotlin.jvm.functions.FunctionN") && typeArgs != null && typeArgs.isNotEmpty() -> listOf(typeArgs.last())
typeArgs != null && isUnspecialised(c, typeArgs, logger) -> listOf()
else -> typeArgs
}
val classTypeResult = addClassLabel(extractClass, extractedTypeArgs, inReceiverContext)
// Extract both the Kotlin and equivalent Java classes, so that we have database entries
// for both even if all internal references to the Kotlin type are substituted.
if(c != extractClass) {
extractClassLaterIfExternal(c)
}
return UseClassInstanceResult(classTypeResult, extractClass)
}
private fun isArray(t: IrSimpleType) = t.isBoxedArray || t.isPrimitiveArray()
private fun extractClassLaterIfExternal(c: IrClass) {
if (isExternalDeclaration(c)) {
extractExternalClassLater(c)
}
}
private fun extractExternalEnclosingClassLater(d: IrDeclaration) {
when (val parent = d.parent) {
is IrClass -> extractExternalClassLater(parent)
is IrFunction -> extractExternalEnclosingClassLater(parent)
is IrFile -> logger.error("extractExternalEnclosingClassLater but no enclosing class.")
else -> logger.error("Unrecognised extractExternalEnclosingClassLater: " + d.javaClass)
}
}
private fun propertySignature(p: IrProperty) =
((p.getter ?: p.setter)?.extensionReceiverParameter?.let { useType(erase(it.type)).javaResult.signature } ?: "")
private fun extractPropertyLaterIfExternalFileMember(p: IrProperty) {
if (isExternalFileClassMember(p)) {
extractExternalClassLater(p.parentAsClass)
val signature = propertySignature(p) + externalClassExtractor.propertySignature
dependencyCollector?.addDependency(p, signature)
externalClassExtractor.extractLater(p, signature)
}
}
private fun extractFieldLaterIfExternalFileMember(f: IrField) {
if (isExternalFileClassMember(f)) {
extractExternalClassLater(f.parentAsClass)
val signature = (f.correspondingPropertySymbol?.let { propertySignature(it.owner) } ?: "") + externalClassExtractor.fieldSignature
dependencyCollector?.addDependency(f, signature)
externalClassExtractor.extractLater(f, signature)
}
}
private fun extractFunctionLaterIfExternalFileMember(f: IrFunction) {
if (isExternalFileClassMember(f)) {
extractExternalClassLater(f.parentAsClass)
(f as? IrSimpleFunction)?.correspondingPropertySymbol?.let {
extractPropertyLaterIfExternalFileMember(it.owner)
// No need to extract the function specifically, as the property's
// getters and setters are extracted alongside it
return
}
// Note we erase the parameter types before calling useType even though the signature should be the same
// in order to prevent an infinite loop through useTypeParameter -> useDeclarationParent -> useFunction
// -> extractFunctionLaterIfExternalFileMember, which would result for `fun <T> f(t: T) { ... }` for example.
val ext = f.extensionReceiverParameter
val parameters = if (ext != null) {
listOf(ext) + f.valueParameters
} else {
f.valueParameters
}
val paramSigs = parameters.map { useType(erase(it.type)).javaResult.signature }
val signature = paramSigs.joinToString(separator = ",", prefix = "(", postfix = ")")
dependencyCollector?.addDependency(f, signature)
externalClassExtractor.extractLater(f, signature)
}
}
fun extractExternalClassLater(c: IrClass) {
dependencyCollector?.addDependency(c)
externalClassExtractor.extractLater(c)
}
private fun tryReplaceAndroidSyntheticClass(c: IrClass): IrClass {
// The Android Kotlin Extensions Gradle plugin introduces synthetic functions, fields and classes. The most
// obvious signature is that they lack any supertype information even though they are not root classes.
// If possible, replace them by a real version of the same class.
if (c.superTypes.isNotEmpty() ||
c.origin != IrDeclarationOrigin.IR_EXTERNAL_JAVA_DECLARATION_STUB ||
c.hasEqualFqName(FqName("java.lang.Object")))
return c
return globalExtensionState.syntheticToRealClassMap.getOrPut(c) {
val qualifiedName = c.fqNameWhenAvailable
if (qualifiedName == null) {
logger.warn("Failed to replace synthetic class ${c.name} because it has no fully qualified name")
return@getOrPut null
}
val result = pluginContext.referenceClass(qualifiedName)?.owner
if (result != null) {
logger.info("Replaced synthetic class ${c.name} with its real equivalent")
return@getOrPut result
}
// The above doesn't work for (some) generated nested classes, such as R$id, which should be R.id
val fqn = qualifiedName.asString()
if (fqn.indexOf('$') >= 0) {
val nested = pluginContext.referenceClass(FqName(fqn.replace('$', '.')))?.owner
if (nested != null) {
logger.info("Replaced synthetic nested class ${c.name} with its real equivalent")
return@getOrPut nested
}
}
logger.warn("Failed to replace synthetic class ${c.name}")
return@getOrPut null
} ?: c
}
private fun tryReplaceFunctionInSyntheticClass(f: IrFunction, getClassReplacement: (IrClass) -> IrClass): IrFunction {
val parentClass = f.parent as? IrClass ?: return f
val replacementClass = getClassReplacement(parentClass)
if (replacementClass === parentClass)
return f
return globalExtensionState.syntheticToRealFunctionMap.getOrPut(f) {
val result = replacementClass.declarations.findSubType<IrSimpleFunction> { replacementDecl ->
replacementDecl.name == f.name && replacementDecl.valueParameters.size == f.valueParameters.size && replacementDecl.valueParameters.zip(f.valueParameters).all {
erase(it.first.type) == erase(it.second.type)
}
}
if (result == null) {
logger.warn("Failed to replace synthetic class function ${f.name}")
} else {
logger.info("Replaced synthetic class function ${f.name} with its real equivalent")
}
result
} ?: f
}
fun tryReplaceSyntheticFunction(f: IrFunction): IrFunction {
val androidReplacement = tryReplaceFunctionInSyntheticClass(f) { tryReplaceAndroidSyntheticClass(it) }
return tryReplaceFunctionInSyntheticClass(androidReplacement) { tryReplaceParcelizeRawType(it)?.first ?: it }
}
fun tryReplaceAndroidSyntheticField(f: IrField): IrField {
val parentClass = f.parent as? IrClass ?: return f
val replacementClass = tryReplaceAndroidSyntheticClass(parentClass)
if (replacementClass === parentClass)
return f
return globalExtensionState.syntheticToRealFieldMap.getOrPut(f) {
val result = replacementClass.declarations.findSubType<IrField> { replacementDecl -> replacementDecl.name == f.name }
?: replacementClass.declarations.findSubType<IrProperty> { it.backingField?.name == f.name}?.backingField
if (result == null) {
logger.warn("Failed to replace synthetic class field ${f.name}")
} else {
logger.info("Replaced synthetic class field ${f.name} with its real equivalent")
}
result
} ?: f
}
private fun tryReplaceType(cBeforeReplacement: IrClass, argsIncludingOuterClassesBeforeReplacement: List<IrTypeArgument>?): Pair<IrClass, List<IrTypeArgument>?> {
val c = tryReplaceAndroidSyntheticClass(cBeforeReplacement)
val p = tryReplaceParcelizeRawType(c)
return Pair(
p?.first ?: c,
p?.second ?: argsIncludingOuterClassesBeforeReplacement
)
}
// `typeArgs` can be null to describe a raw generic type.
// For non-generic types it will be zero-length list.
private fun addClassLabel(cBeforeReplacement: IrClass, argsIncludingOuterClassesBeforeReplacement: List<IrTypeArgument>?, inReceiverContext: Boolean = false): TypeResult<DbClassorinterface> {
val replaced = tryReplaceType(cBeforeReplacement, argsIncludingOuterClassesBeforeReplacement)
val replacedClass = replaced.first
val replacedArgsIncludingOuterClasses = replaced.second
val classLabelResult = getClassLabel(replacedClass, replacedArgsIncludingOuterClasses)
var instanceSeenBefore = true
val classLabel : Label<out DbClassorinterface> = tw.getLabelFor(classLabelResult.classLabel) {
instanceSeenBefore = false
extractClassLaterIfExternal(replacedClass)
}
if (replacedArgsIncludingOuterClasses == null || replacedArgsIncludingOuterClasses.isNotEmpty()) {
// If this is a generic type instantiation or a raw type then it has no
// source entity, so we need to extract it here
val shouldExtractClassDetails = inReceiverContext && tw.lm.genericSpecialisationsExtracted.add(classLabelResult.classLabel)
if (!instanceSeenBefore || shouldExtractClassDetails) {
this.withFileOfClass(replacedClass).extractClassInstance(classLabel, replacedClass, replacedArgsIncludingOuterClasses, !instanceSeenBefore, shouldExtractClassDetails)
}
}
val fqName = replacedClass.fqNameWhenAvailable
val signature = if (replacedClass.isAnonymousObject) {
null
} else if (fqName == null) {
logger.error("Unable to find signature/fqName for ${replacedClass.name}")
null
} else {
fqName.asString()
}
return TypeResult(
classLabel,
signature,
classLabelResult.shortName)
}
private fun tryReplaceParcelizeRawType(c: IrClass): Pair<IrClass, List<IrTypeArgument>?>? {
if (c.superTypes.isNotEmpty() ||
c.origin != IrDeclarationOrigin.DEFINED ||
c.hasEqualFqName(FqName("java.lang.Object"))) {
return null
}
val fqName = c.fqNameWhenAvailable
if (fqName == null) {
return null
}
fun tryGetPair(arity: Int): Pair<IrClass, List<IrTypeArgument>?>? {
val replaced = pluginContext.referenceClass(fqName)?.owner ?: return null
return Pair(replaced, List(arity) { makeTypeProjection(pluginContext.irBuiltIns.anyNType, Variance.INVARIANT) })
}
// The list of types handled here match https://github.com/JetBrains/kotlin/blob/d7c7d1efd2c0983c13b175e9e4b1cda979521159/plugins/parcelize/parcelize-compiler/src/org/jetbrains/kotlin/parcelize/ir/AndroidSymbols.kt
// Specifically, types are added for generic types created in AndroidSymbols.kt.
// This replacement is from a raw type to its matching parameterized type with `Object` type arguments.
return when (fqName.asString()) {
"java.util.ArrayList" -> tryGetPair(1)
"java.util.LinkedHashMap" -> tryGetPair(2)
"java.util.LinkedHashSet" -> tryGetPair(1)
"java.util.List" -> tryGetPair(1)
"java.util.TreeMap" -> tryGetPair(2)
"java.util.TreeSet" -> tryGetPair(1)
"java.lang.Class" -> tryGetPair(1)
else -> null
}
}
private fun useAnonymousClass(c: IrClass) =
tw.lm.anonymousTypeMapping.getOrPut(c) {
TypeResults(
TypeResult(tw.getFreshIdLabel<DbClass>(), "", ""),
TypeResult(fakeKotlinType(), "TODO", "TODO")
)
}
fun fakeKotlinType(): Label<out DbKt_type> {
val fakeKotlinPackageId: Label<DbPackage> = tw.getLabelFor("@\"FakeKotlinPackage\"", {
tw.writePackages(it, "fake.kotlin")
})
val fakeKotlinClassId: Label<DbClass> = tw.getLabelFor("@\"FakeKotlinClass\"", {
tw.writeClasses(it, "FakeKotlinClass", fakeKotlinPackageId, it)
})
val fakeKotlinTypeId: Label<DbKt_nullable_type> = tw.getLabelFor("@\"FakeKotlinType\"", {
tw.writeKt_nullable_types(it, fakeKotlinClassId)
})
return fakeKotlinTypeId
}
// `args` can be null to describe a raw generic type.
// For non-generic types it will be zero-length list.
fun useSimpleTypeClass(c: IrClass, args: List<IrTypeArgument>?, hasQuestionMark: Boolean): TypeResults {
val classInstanceResult = useClassInstance(c, args)
val javaClassId = classInstanceResult.typeResult.id
val kotlinQualClassName = getUnquotedClassLabel(c, args).classLabel
val javaResult = classInstanceResult.typeResult
val kotlinResult = if (true) TypeResult(fakeKotlinType(), "TODO", "TODO") else
if (hasQuestionMark) {
val kotlinSignature = "$kotlinQualClassName?" // TODO: Is this right?
val kotlinLabel = "@\"kt_type;nullable;$kotlinQualClassName\""
val kotlinId: Label<DbKt_nullable_type> = tw.getLabelFor(kotlinLabel, {
tw.writeKt_nullable_types(it, javaClassId)
})
TypeResult(kotlinId, kotlinSignature, "TODO")
} else {
val kotlinSignature = kotlinQualClassName // TODO: Is this right?
val kotlinLabel = "@\"kt_type;notnull;$kotlinQualClassName\""
val kotlinId: Label<DbKt_notnull_type> = tw.getLabelFor(kotlinLabel, {
tw.writeKt_notnull_types(it, javaClassId)
})
TypeResult(kotlinId, kotlinSignature, "TODO")
}
return TypeResults(javaResult, kotlinResult)
}
// Given either a primitive array or a boxed array, returns primitive arrays unchanged,
// but returns boxed arrays with a nullable, invariant component type, with any nested arrays
// similarly transformed. For example, Array<out Array<in E>> would become Array<Array<E?>?>
// Array<*> will become Array<Any?>.
private fun getInvariantNullableArrayType(arrayType: IrSimpleType): IrSimpleType =
if (arrayType.isPrimitiveArray())
arrayType
else {
val componentType = arrayType.getArrayElementType(pluginContext.irBuiltIns)
val componentTypeBroadened = when (componentType) {
is IrSimpleType ->
if (isArray(componentType)) getInvariantNullableArrayType(componentType) else componentType
else -> componentType
}
val unchanged =
componentType == componentTypeBroadened &&
(arrayType.arguments[0] as? IrTypeProjection)?.variance == Variance.INVARIANT &&
componentType.isNullable()
if (unchanged)
arrayType
else
IrSimpleTypeImpl(
arrayType.classifier,
true,
listOf(makeTypeProjection(componentTypeBroadened, Variance.INVARIANT)),
listOf()
)
}
data class ArrayInfo(val elementTypeResults: TypeResults,
val componentTypeResults: TypeResults,
val dimensions: Int)
/**
* `t` is somewhere in a stack of array types, or possibly the
* element type of the innermost array. For example, in
* `Array<Array<Int>>`, we will be called with `t` being
* `Array<Array<Int>>`, then `Array<Int>`, then `Int`.
* `isPrimitiveArray` is true if we are immediately nested
* inside a primitive array.
*/
private fun useArrayType(t: IrType, isPrimitiveArray: Boolean): ArrayInfo {
if (!t.isBoxedArray && !t.isPrimitiveArray()) {
val nullableT = if (t.isPrimitiveType() && !isPrimitiveArray) t.makeNullable() else t
val typeResults = useType(nullableT)
return ArrayInfo(typeResults, typeResults, 0)
}
if (t !is IrSimpleType) {
logger.error("Unexpected non-simple array type: ${t.javaClass}")
return ArrayInfo(extractErrorType(), extractErrorType(), 0)
}
val arrayClass = t.classifier.owner
if (arrayClass !is IrClass) {
logger.error("Unexpected owner type for array type: ${arrayClass.javaClass}")
return ArrayInfo(extractErrorType(), extractErrorType(), 0)
}
// Because Java's arrays are covariant, Kotlin will render
// Array<in X> as Object[], Array<Array<in X>> as Object[][] etc.
val elementType = if ((t.arguments.singleOrNull() as? IrTypeProjection)?.variance == Variance.IN_VARIANCE) {
pluginContext.irBuiltIns.anyType
} else {
t.getArrayElementType(pluginContext.irBuiltIns)
}
val recInfo = useArrayType(elementType, t.isPrimitiveArray())
val javaShortName = recInfo.componentTypeResults.javaResult.shortName + "[]"
val kotlinShortName = recInfo.componentTypeResults.kotlinResult.shortName + "[]"
val elementTypeLabel = recInfo.elementTypeResults.javaResult.id
val componentTypeLabel = recInfo.componentTypeResults.javaResult.id
val dimensions = recInfo.dimensions + 1
val id = tw.getLabelFor<DbArray>("@\"array;$dimensions;{${elementTypeLabel}}\"") {
tw.writeArrays(
it,
javaShortName,
elementTypeLabel,
dimensions,
componentTypeLabel)
extractClassSupertypes(arrayClass, it, ExtractSupertypesMode.Specialised(t.arguments))
// array.length
val length = tw.getLabelFor<DbField>("@\"field;{$it};length\"")
val intTypeIds = useType(pluginContext.irBuiltIns.intType)
tw.writeFields(length, "length", intTypeIds.javaResult.id, it, length)
tw.writeFieldsKotlinType(length, intTypeIds.kotlinResult.id)
addModifiers(length, "public", "final")
// Note we will only emit one `clone()` method per Java array type, so we choose `Array<C?>` as its Kotlin
// return type, where C is the component type with any nested arrays themselves invariant and nullable.
val kotlinCloneReturnType = getInvariantNullableArrayType(t).makeNullable()
val kotlinCloneReturnTypeLabel = useType(kotlinCloneReturnType).kotlinResult.id
val clone = tw.getLabelFor<DbMethod>("@\"callable;{$it}.clone(){$it}\"")
tw.writeMethods(clone, "clone", "clone()", it, it, clone)
tw.writeMethodsKotlinType(clone, kotlinCloneReturnTypeLabel)
addModifiers(clone, "public")
}
val javaResult = TypeResult(
id,
recInfo.componentTypeResults.javaResult.signature + "[]",
javaShortName)
val kotlinResult = TypeResult(
fakeKotlinType(),
recInfo.componentTypeResults.kotlinResult.signature + "[]",
kotlinShortName)
val typeResults = TypeResults(javaResult, kotlinResult)
return ArrayInfo(recInfo.elementTypeResults, typeResults, dimensions)
}
enum class TypeContext {
RETURN, GENERIC_ARGUMENT, OTHER
}
private fun isOnDeclarationStackWithoutTypeParameters(f: IrFunction) =
this is KotlinFileExtractor && this.declarationStack.findOverriddenAttributes(f)?.typeParameters?.isEmpty() == true
private fun isStaticFunctionOnStackBeforeClass(c: IrClass) =
this is KotlinFileExtractor && (this.declarationStack.findFirst { it.first == c || it.second?.isStatic == true })?.second?.isStatic == true
private fun isUnavailableTypeParameter(t: IrType) =
t is IrSimpleType && t.classifier.owner.let { owner ->
owner is IrTypeParameter && owner.parent.let { parent ->
when (parent) {
is IrFunction -> isOnDeclarationStackWithoutTypeParameters(parent)
is IrClass -> isStaticFunctionOnStackBeforeClass(parent)
else -> false
}
}
}
private fun argIsUnavailableTypeParameter(t: IrTypeArgument) =
t is IrTypeProjection && isUnavailableTypeParameter(t.type)
private fun useSimpleType(s: IrSimpleType, context: TypeContext): TypeResults {
if (s.abbreviation != null) {
// TODO: Extract this information
}
// We use this when we don't actually have an IrClass for a class
// we want to refer to
// TODO: Eliminate the need for this if possible
fun makeClass(pkgName: String, className: String): Label<DbClass> {
val pkgId = extractPackage(pkgName)
val label = "@\"class;$pkgName.$className\""
val classId: Label<DbClass> = tw.getLabelFor(label, {
tw.writeClasses(it, className, pkgId, it)
})
return classId
}
fun primitiveType(kotlinClass: IrClass, primitiveName: String?,
otherIsPrimitive: Boolean,
javaClass: IrClass,
kotlinPackageName: String, kotlinClassName: String): TypeResults {
// Note the use of `hasEnhancedNullability` here covers cases like `@NotNull Integer`, which must be extracted as `Integer` not `int`.
val javaResult = if ((context == TypeContext.RETURN || (context == TypeContext.OTHER && otherIsPrimitive)) && !s.isNullable() && getKotlinType(s)?.hasEnhancedNullability() != true && primitiveName != null) {
val label: Label<DbPrimitive> = tw.getLabelFor("@\"type;$primitiveName\"", {
tw.writePrimitives(it, primitiveName)
})
TypeResult(label, primitiveName, primitiveName)
} else {
addClassLabel(javaClass, listOf())
}
val kotlinClassId = useClassInstance(kotlinClass, listOf()).typeResult.id
val kotlinResult = if (true) TypeResult(fakeKotlinType(), "TODO", "TODO") else
if (s.isNullable()) {
val kotlinSignature = "$kotlinPackageName.$kotlinClassName?" // TODO: Is this right?
val kotlinLabel = "@\"kt_type;nullable;$kotlinPackageName.$kotlinClassName\""
val kotlinId: Label<DbKt_nullable_type> = tw.getLabelFor(kotlinLabel, {
tw.writeKt_nullable_types(it, kotlinClassId)
})
TypeResult(kotlinId, kotlinSignature, "TODO")
} else {
val kotlinSignature = "$kotlinPackageName.$kotlinClassName" // TODO: Is this right?
val kotlinLabel = "@\"kt_type;notnull;$kotlinPackageName.$kotlinClassName\""
val kotlinId: Label<DbKt_notnull_type> = tw.getLabelFor(kotlinLabel, {
tw.writeKt_notnull_types(it, kotlinClassId)
})
TypeResult(kotlinId, kotlinSignature, "TODO")
}
return TypeResults(javaResult, kotlinResult)
}
val owner = s.classifier.owner
val primitiveInfo = primitiveTypeMapping.getPrimitiveInfo(s)
when {
primitiveInfo != null -> {
if (owner is IrClass) {
return primitiveType(
owner,
primitiveInfo.primitiveName, primitiveInfo.otherIsPrimitive,
primitiveInfo.javaClass,
primitiveInfo.kotlinPackageName, primitiveInfo.kotlinClassName
)
} else {
logger.error("Got primitive info for non-class (${owner.javaClass}) for ${s.render()}")
return extractErrorType()
}
}
(s.isBoxedArray && s.arguments.isNotEmpty()) || s.isPrimitiveArray() -> {
val arrayInfo = useArrayType(s, false)
return arrayInfo.componentTypeResults
}
owner is IrClass -> {
val args = if (s.isRawType() || s.arguments.any { argIsUnavailableTypeParameter(it) }) null else s.arguments
return useSimpleTypeClass(owner, args, s.isNullable())
}
owner is IrTypeParameter -> {
if (isUnavailableTypeParameter(s))
return useType(erase(s), context)
val javaResult = useTypeParameter(owner)
val aClassId = makeClass("kotlin", "TypeParam") // TODO: Wrong
val kotlinResult = if (true) TypeResult(fakeKotlinType(), "TODO", "TODO") else
if (s.isNullable()) {
val kotlinSignature = "${javaResult.signature}?" // TODO: Wrong
val kotlinLabel = "@\"kt_type;nullable;type_param\"" // TODO: Wrong
val kotlinId: Label<DbKt_nullable_type> = tw.getLabelFor(kotlinLabel, {
tw.writeKt_nullable_types(it, aClassId)
})
TypeResult(kotlinId, kotlinSignature, "TODO")
} else {
val kotlinSignature = javaResult.signature // TODO: Wrong
val kotlinLabel = "@\"kt_type;notnull;type_param\"" // TODO: Wrong
val kotlinId: Label<DbKt_notnull_type> = tw.getLabelFor(kotlinLabel, {
tw.writeKt_notnull_types(it, aClassId)
})
TypeResult(kotlinId, kotlinSignature, "TODO")
}
return TypeResults(javaResult, kotlinResult)
}
else -> {
logger.error("Unrecognised IrSimpleType: " + s.javaClass + ": " + s.render())
return extractErrorType()
}
}
}
fun useDeclarationParent(
// The declaration parent according to Kotlin
dp: IrDeclarationParent,
// Whether the type of entity whose parent this is can be a
// top-level entity in the JVM's eyes. If so, then its parent may
// be a file; otherwise, if dp is a file foo.kt, then the parent
// is really the JVM class FooKt.
canBeTopLevel: Boolean,
classTypeArguments: List<IrTypeArgument>? = null,
inReceiverContext: Boolean = false):
Label<out DbElement>? =
when(dp) {
is IrFile ->
if(canBeTopLevel) {
usePackage(dp.fqName.asString())
} else {
extractFileClass(dp)
}
is IrClass ->
if (classTypeArguments != null) {
useClassInstance(dp, classTypeArguments, inReceiverContext).typeResult.id
} else {
val replacedType = tryReplaceParcelizeRawType(dp)
if (replacedType == null) {
useClassSource(dp)
} else {
useClassInstance(replacedType.first, replacedType.second, inReceiverContext).typeResult.id
}
}
is IrFunction -> useFunction(dp)
is IrExternalPackageFragment -> {
// TODO
logger.error("Unhandled IrExternalPackageFragment")
null
}
else -> {
logger.error("Unrecognised IrDeclarationParent: " + dp.javaClass)
null
}
}
private val IrDeclaration.isAnonymousFunction get() = this is IrSimpleFunction && name == SpecialNames.NO_NAME_PROVIDED
data class FunctionNames(val nameInDB: String, val kotlinName: String)
@OptIn(ObsoleteDescriptorBasedAPI::class)
private fun getJvmModuleName(f: IrFunction) =
NameUtils.sanitizeAsJavaIdentifier(
getJvmModuleNameForDeserializedDescriptor(f.descriptor) ?: JvmCodegenUtil.getModuleName(pluginContext.moduleDescriptor)
)
fun getFunctionShortName(f: IrFunction) : FunctionNames {
if (f.origin == IrDeclarationOrigin.LOCAL_FUNCTION_FOR_LAMBDA || f.isAnonymousFunction)
return FunctionNames(
OperatorNameConventions.INVOKE.asString(),
OperatorNameConventions.INVOKE.asString())
fun getSuffixIfInternal() =
if (f.visibility == DescriptorVisibilities.INTERNAL && f !is IrConstructor) {
"\$" + getJvmModuleName(f)
} else {
""
}
(f as? IrSimpleFunction)?.correspondingPropertySymbol?.let {
val propName = it.owner.name.asString()
val getter = it.owner.getter
val setter = it.owner.setter
if (it.owner.parentClassOrNull?.kind == ClassKind.ANNOTATION_CLASS) {
if (getter == null) {
logger.error("Expected to find a getter for a property inside an annotation class")
return FunctionNames(propName, propName)
} else {
val jvmName = getJvmName(getter)
return FunctionNames(jvmName ?: propName, propName)
}
}
val maybeFunctionName = when (f) {
getter -> JvmAbi.getterName(propName)
setter -> JvmAbi.setterName(propName)
else -> {
logger.error(
"Function has a corresponding property, but is neither the getter nor the setter"
)
null
}
}
maybeFunctionName?.let { defaultFunctionName ->
val suffix = if (f.visibility == DescriptorVisibilities.PRIVATE && f.origin == IrDeclarationOrigin.DEFAULT_PROPERTY_ACCESSOR) {
"\$private"
} else {
getSuffixIfInternal()
}
return FunctionNames(getJvmName(f) ?: "$defaultFunctionName$suffix", defaultFunctionName)
}
}
return FunctionNames(getJvmName(f) ?: "${f.name.asString()}${getSuffixIfInternal()}", f.name.asString())
}
// This excludes class type parameters that show up in (at least) constructors' typeParameters list.
fun getFunctionTypeParameters(f: IrFunction): List<IrTypeParameter> {
return if (f is IrConstructor) f.typeParameters else f.typeParameters.filter { it.parent == f }
}
private fun getTypeParameters(dp: IrDeclarationParent): List<IrTypeParameter> =
when(dp) {
is IrClass -> dp.typeParameters
is IrFunction -> getFunctionTypeParameters(dp)
else -> listOf()
}
private fun getEnclosingClass(it: IrDeclarationParent): IrClass? =
when(it) {
is IrClass -> it
is IrFunction -> getEnclosingClass(it.parent)
else -> null
}
val javaUtilCollection by lazy {
val result = pluginContext.referenceClass(FqName("java.util.Collection"))?.owner
result?.let { extractExternalClassLater(it) }
result
}
val wildcardCollectionType by lazy {
javaUtilCollection?.let {
it.symbol.typeWithArguments(listOf(IrStarProjectionImpl))
}
}
private fun makeCovariant(t: IrTypeArgument) =
t.typeOrNull?.let { makeTypeProjection(it, Variance.OUT_VARIANCE) } ?: t
private fun makeArgumentsCovariant(t: IrType) = (t as? IrSimpleType)?.let {
t.toBuilder().also { b -> b.arguments = b.arguments.map(this::makeCovariant) }.buildSimpleType()
} ?: t
fun eraseCollectionsMethodParameterType(t: IrType, collectionsMethodName: String, paramIdx: Int) =
when(collectionsMethodName) {
"contains", "remove", "containsKey", "containsValue", "get", "indexOf", "lastIndexOf" -> javaLangObjectType
"getOrDefault" -> if (paramIdx == 0) javaLangObjectType else null
"containsAll", "removeAll", "retainAll" -> wildcardCollectionType
// Kotlin defines these like addAll(Collection<E>); Java uses addAll(Collection<? extends E>)
"putAll", "addAll" -> makeArgumentsCovariant(t)
else -> null
} ?: t
private fun overridesFunctionDefinedOn(f: IrFunction, packageName: String, className: String) =
(f as? IrSimpleFunction)?.let {
it.overriddenSymbols.any { overridden ->
overridden.owner.parentClassOrNull?.let { defnClass ->
defnClass.name.asString() == className &&
defnClass.packageFqName?.asString() == packageName
} ?: false
}
} ?: false
@OptIn(ObsoleteDescriptorBasedAPI::class)
fun overridesCollectionsMethodWithAlteredParameterTypes(f: IrFunction) =
BuiltinMethodsWithSpecialGenericSignature.getOverriddenBuiltinFunctionWithErasedValueParametersInJava(f.descriptor) != null ||
(f.name.asString() == "putAll" && overridesFunctionDefinedOn(f, "kotlin.collections", "MutableMap")) ||
(f.name.asString() == "addAll" && overridesFunctionDefinedOn(f, "kotlin.collections", "MutableCollection")) ||
(f.name.asString() == "addAll" && overridesFunctionDefinedOn(f, "kotlin.collections", "MutableList"))
private val jvmWildcardAnnotation = FqName("kotlin.jvm.JvmWildcard")
private val jvmWildcardSuppressionAnnotation = FqName("kotlin.jvm.JvmSuppressWildcards")
private fun arrayExtendsAdditionAllowed(t: IrSimpleType): Boolean =
// Note the array special case includes Array<*>, which does permit adding `? extends ...` (making `? extends Object[]` in that case)
// Surprisingly Array<in X> does permit this as well, though the contravariant array lowers to Object[] so this ends up `? extends Object[]` as well.
t.arguments[0].let {
when (it) {
is IrTypeProjection -> when (it.variance) {
Variance.INVARIANT -> false
Variance.IN_VARIANCE -> !(it.type.isAny() || it.type.isNullableAny())
Variance.OUT_VARIANCE -> extendsAdditionAllowed(it.type)
}
else -> true
}
}
private fun extendsAdditionAllowed(t: IrType) =
if (t.isBoxedArray) {
if (t is IrSimpleType) {
arrayExtendsAdditionAllowed(t)
} else {
logger.warn("Boxed array of unexpected kind ${t.javaClass}")
// Return false, for no particular reason
false
}
} else {
((t as? IrSimpleType)?.classOrNull?.owner?.isFinalClass) != true
}
private fun wildcardAdditionAllowed(v: Variance, t: IrType, addByDefault: Boolean, javaVariance: Variance?) =
when {
t.hasAnnotation(jvmWildcardAnnotation) -> true
// If a Java declaration specifies a variance, introduce it even if it's pointless (e.g. ? extends FinalClass, or ? super Object)
javaVariance == v -> true
!addByDefault -> false
v == Variance.IN_VARIANCE -> !(t.isNullableAny() || t.isAny())
v == Variance.OUT_VARIANCE -> extendsAdditionAllowed(t)
else -> false
}
// Returns true if `t` has `@JvmSuppressWildcards` or `@JvmSuppressWildcards(true)`,
// false if it has `@JvmSuppressWildcards(false)`,
// and null if the annotation is not present.
@Suppress("UNCHECKED_CAST")
private fun getWildcardSuppressionDirective(t: IrAnnotationContainer) =
t.getAnnotation(jvmWildcardSuppressionAnnotation)?.let { (it.getValueArgument(0) as? IrConst<Boolean>)?.value ?: true }
private fun addJavaLoweringArgumentWildcards(p: IrTypeParameter, t: IrTypeArgument, addByDefault: Boolean, javaType: JavaType?): IrTypeArgument =
(t as? IrTypeProjection)?.let {
val newAddByDefault = getWildcardSuppressionDirective(it.type)?.not() ?: addByDefault
val newBase = addJavaLoweringWildcards(it.type, newAddByDefault, javaType)
// Note javaVariance == null means we don't have a Java type to conform to -- for example if this is a Kotlin source definition.
val javaVariance = javaType?.let { jType ->
when (jType) {
is JavaWildcardType -> if (jType.isExtends) Variance.OUT_VARIANCE else Variance.IN_VARIANCE
else -> Variance.INVARIANT
}
}
val newVariance =
if (it.variance == Variance.INVARIANT &&
p.variance != Variance.INVARIANT &&
// The next line forbids inferring a wildcard type when we have a corresponding Java type with conflicting variance.
// For example, Java might declare f(Comparable<CharSequence> cs), in which case we shouldn't add a `? super ...`
// wildcard. Note if javaType is unknown (e.g. this is a Kotlin source element), we assume wildcards should be added.
(javaVariance == null || javaVariance == p.variance) &&
wildcardAdditionAllowed(p.variance, it.type, newAddByDefault, javaVariance))
p.variance
else
it.variance
if (newBase !== it.type || newVariance != it.variance)
makeTypeProjection(newBase, newVariance)
else
null
} ?: t
private fun getJavaTypeArgument(jt: JavaType, idx: Int): JavaType? =
when(jt) {
is JavaWildcardType -> jt.bound?.let { getJavaTypeArgument(it, idx) }
is JavaClassifierType -> jt.typeArguments.getOrNull(idx)
is JavaArrayType -> if (idx == 0) jt.componentType else null
else -> null
}
fun addJavaLoweringWildcards(t: IrType, addByDefault: Boolean, javaType: JavaType?): IrType =
(t as? IrSimpleType)?.let {
val newAddByDefault = getWildcardSuppressionDirective(t)?.not() ?: addByDefault
val typeParams = it.classOrNull?.owner?.typeParameters ?: return t
val newArgs = typeParams.zip(it.arguments).mapIndexed { idx, pair ->
addJavaLoweringArgumentWildcards(
pair.first,
pair.second,
newAddByDefault,
javaType?.let { jt -> getJavaTypeArgument(jt, idx) }
)
}
return if (newArgs.zip(it.arguments).all { pair -> pair.first === pair.second })
t
else
it.toBuilder().also { builder -> builder.arguments = newArgs }.buildSimpleType()
} ?: t
/*
* This is the normal getFunctionLabel function to use. If you want
* to refer to the function in its source class then
* classTypeArgsIncludingOuterClasses should be null. Otherwise, it
* is the list of type arguments that need to be applied to its
* enclosing classes to get the instantiation that this function is
* in.
*/
fun getFunctionLabel(f: IrFunction, classTypeArgsIncludingOuterClasses: List<IrTypeArgument>?) : String {
return getFunctionLabel(f, null, classTypeArgsIncludingOuterClasses)
}
/*
* There are some pairs of classes (e.g. `kotlin.Throwable` and
* `java.lang.Throwable`) which are really just 2 different names
* for the same class. However, we extract them as separate
* classes. When extracting `kotlin.Throwable`'s methods, if we
* looked up the parent ID ourselves, we would get as ID for
* `java.lang.Throwable`, which isn't what we want. So we have to
* allow it to be passed in.
*
* `maybeParameterList` can be supplied to override the function's
* value parameters; this is used for generating labels of overloads
* that omit one or more parameters that has a default value specified.
*/
@OptIn(ObsoleteDescriptorBasedAPI::class)
fun getFunctionLabel(f: IrFunction, maybeParentId: Label<out DbElement>?, classTypeArgsIncludingOuterClasses: List<IrTypeArgument>?, maybeParameterList: List<IrValueParameter>? = null) =
getFunctionLabel(
f.parent,
maybeParentId,
getFunctionShortName(f).nameInDB,
(maybeParameterList ?: f.valueParameters).map { it.type },
getAdjustedReturnType(f),
f.extensionReceiverParameter?.type,
getFunctionTypeParameters(f),
classTypeArgsIncludingOuterClasses,
overridesCollectionsMethodWithAlteredParameterTypes(f),
getJavaCallable(f),
!getInnermostWildcardSupppressionAnnotation(f)
)
/*
* This function actually generates the label for a function.
* Sometimes, a function is only generated by kotlinc when writing a
* class file, so there is no corresponding `IrFunction` for it.
* This function therefore takes all the constituent parts of a
* function instead.
*/
fun getFunctionLabel(
// The parent of the function; normally f.parent.
parent: IrDeclarationParent,
// The ID of the function's parent, or null if we should work it out ourselves.
maybeParentId: Label<out DbElement>?,
// The name of the function; normally f.name.asString().
name: String,
// The types of the value parameters that the functions takes; normally f.valueParameters.map { it.type }.
parameterTypes: List<IrType>,
// The return type of the function; normally f.returnType.
returnType: IrType,
// The extension receiver of the function, if any; normally f.extensionReceiverParameter?.type.
extensionParamType: IrType?,
// The type parameters of the function. This does not include type parameters of enclosing classes.
functionTypeParameters: List<IrTypeParameter>,
// The type arguments of enclosing classes of the function.
classTypeArgsIncludingOuterClasses: List<IrTypeArgument>?,
// If true, this method implements a Java Collections interface (Collection, Map or List) and may need
// parameter erasure to match the way this class will appear to an external consumer of the .class file.
overridesCollectionsMethod: Boolean,
// The Java signature of this callable, if known.
javaSignature: JavaMember?,
// If true, Java wildcards implied by Kotlin type parameter variance should be added by default to this function's value parameters' types.
// (Return-type wildcard addition is always off by default)
addParameterWildcardsByDefault: Boolean,
// The prefix used in the label. "callable", unless a property label is created, then it's "property".
prefix: String = "callable"
): String {
val parentId = maybeParentId ?: useDeclarationParent(parent, false, classTypeArgsIncludingOuterClasses, true)
val allParamTypes = if (extensionParamType == null) parameterTypes else listOf(extensionParamType) + parameterTypes
val substitutionMap = classTypeArgsIncludingOuterClasses?.let { notNullArgs ->
if (notNullArgs.isEmpty()) {
null
} else {
val enclosingClass = getEnclosingClass(parent)
enclosingClass?.let { notNullClass -> makeTypeGenericSubstitutionMap(notNullClass, notNullArgs) }
}
}
val getIdForFunctionLabel = { it: IndexedValue<IrType> ->
// Kotlin rewrites certain Java collections types adding additional generic constraints-- for example,
// Collection.remove(Object) because Collection.remove(Collection::E) in the Kotlin universe.
// If this has happened, erase the type again to get the correct Java signature.
val maybeAmendedForCollections = if (overridesCollectionsMethod) eraseCollectionsMethodParameterType(it.value, name, it.index) else it.value
// Add any wildcard types that the Kotlin compiler would add in the Java lowering of this function:
val withAddedWildcards = addJavaLoweringWildcards(maybeAmendedForCollections, addParameterWildcardsByDefault, javaSignature?.let { sig -> getJavaValueParameterType(sig, it.index) })
// Now substitute any class type parameters in:
val maybeSubbed = withAddedWildcards.substituteTypeAndArguments(substitutionMap, TypeContext.OTHER, pluginContext)
// Finally, mimic the Java extractor's behaviour by naming functions with type parameters for their erased types;
// those without type parameters are named for the generic type.
val maybeErased = if (functionTypeParameters.isEmpty()) maybeSubbed else erase(maybeSubbed)
"{${useType(maybeErased).javaResult.id}}"
}
val paramTypeIds = allParamTypes.withIndex().joinToString(separator = ",", transform = getIdForFunctionLabel)
val labelReturnType =
if (name == "<init>")
pluginContext.irBuiltIns.unitType
else
erase(returnType.substituteTypeAndArguments(substitutionMap, TypeContext.RETURN, pluginContext))
// Note that `addJavaLoweringWildcards` is not required here because the return type used to form the function
// label is always erased.
val returnTypeId = useType(labelReturnType, TypeContext.RETURN).javaResult.id
// This suffix is added to generic methods (and constructors) to match the Java extractor's behaviour.
// Comments in that extractor indicates it didn't want the label of the callable to clash with the raw
// method (and presumably that disambiguation is never needed when the method belongs to a parameterized
// instance of a generic class), but as of now I don't know when the raw method would be referred to.
val typeArgSuffix = if (functionTypeParameters.isNotEmpty() && classTypeArgsIncludingOuterClasses.isNullOrEmpty()) "<${functionTypeParameters.size}>" else "";
return "@\"$prefix;{$parentId}.$name($paramTypeIds){$returnTypeId}${typeArgSuffix}\""
}
val javaLangClass by lazy {
val result = pluginContext.referenceClass(FqName("java.lang.Class"))?.owner
result?.let { extractExternalClassLater(it) }
result
}
fun kClassToJavaClass(t: IrType): IrType {
when(t) {
is IrSimpleType -> {
if (t.classifier == pluginContext.irBuiltIns.kClassClass) {
javaLangClass?.let { jlc ->
return jlc.symbol.typeWithArguments(t.arguments)
}
} else {
t.classOrNull?.let { tCls ->
if (t.isArray() || t.isNullableArray()) {
(t.arguments.singleOrNull() as? IrTypeProjection)?.let { elementTypeArg ->
val elementType = elementTypeArg.type
val replacedElementType = kClassToJavaClass(elementType)
if (replacedElementType !== elementType) {
val newArg = makeTypeProjection(replacedElementType, elementTypeArg.variance)
return tCls.typeWithArguments(listOf(newArg)).codeQlWithHasQuestionMark(t.isNullableArray())
}
}
}
}
}
}
}
return t
}
fun isAnnotationClassField(f: IrField) =
f.correspondingPropertySymbol?.let {
isAnnotationClassProperty(it)
} ?: false
private fun isAnnotationClassProperty(p: IrPropertySymbol) =
p.owner.parentClassOrNull?.kind == ClassKind.ANNOTATION_CLASS
fun getAdjustedReturnType(f: IrFunction) : IrType {
// Replace annotation val accessor types as needed:
(f as? IrSimpleFunction)?.correspondingPropertySymbol?.let {
if (isAnnotationClassProperty(it) && f == it.owner.getter) {
val replaced = kClassToJavaClass(f.returnType)
if (replaced != f.returnType)
return replaced
}
}
// The return type of `java.util.concurrent.ConcurrentHashMap<K,V>.keySet/0` is defined as `Set<K>` in the stubs inside the Android SDK.
// This does not match the Java SDK return type: `ConcurrentHashMap.KeySetView<K,V>`, so it's adjusted here.
// This is a deliberate change in the Android SDK: https://github.com/AndroidSDKSources/android-sdk-sources-for-api-level-31/blob/2c56b25f619575bea12f9c5520ed2259620084ac/java/util/concurrent/ConcurrentHashMap.java#L1244-L1249
// The annotation on the source is not visible in the android.jar, so we can't make the change based on that.
// TODO: there are other instances of `dalvik.annotation.codegen.CovariantReturnType` in the Android SDK, we should handle those too if they cause DB inconsistencies
val parentClass = f.parentClassOrNull
if (parentClass == null ||
parentClass.fqNameWhenAvailable?.asString() != "java.util.concurrent.ConcurrentHashMap" ||
getFunctionShortName(f).nameInDB != "keySet" ||
f.valueParameters.isNotEmpty() ||
f.returnType.classFqName?.asString() != "kotlin.collections.MutableSet") {
return f.returnType
}
val otherKeySet = parentClass.declarations.findSubType<IrFunction> { it.name.asString() == "keySet" && it.valueParameters.size == 1 }
?: return f.returnType
return otherKeySet.returnType.codeQlWithHasQuestionMark(false)
}
@OptIn(ObsoleteDescriptorBasedAPI::class)
fun getJavaCallable(f: IrFunction) = (f.descriptor.source as? JavaSourceElement)?.javaElement as? JavaMember
fun getJavaValueParameterType(m: JavaMember, idx: Int) = when(m) {
is JavaMethod -> m.valueParameters[idx].type
is JavaConstructor -> m.valueParameters[idx].type
else -> null
}
fun getInnermostWildcardSupppressionAnnotation(d: IrDeclaration) =
getWildcardSuppressionDirective(d) ?:
// Note not using `parentsWithSelf` as that only works if `d` is an IrDeclarationParent
d.parents.filterIsInstance<IrAnnotationContainer>().mapNotNull { getWildcardSuppressionDirective(it) }.firstOrNull() ?:
false
/**
* Class to hold labels for generated classes around local functions, lambdas, function references, and property references.
*/
open class GeneratedClassLabels(val type: TypeResults, val constructor: Label<DbConstructor>, val constructorBlock: Label<DbBlock>)
/**
* Class to hold labels generated for locally visible functions, such as
* - local functions,
* - lambdas, and
* - wrappers around function references.
*/
class LocallyVisibleFunctionLabels(type: TypeResults, constructor: Label<DbConstructor>, constructorBlock: Label<DbBlock>, val function: Label<DbMethod>)
: GeneratedClassLabels(type, constructor, constructorBlock)
/**
* Gets the labels for functions belonging to
* - local functions, and
* - lambdas.
*/
fun getLocallyVisibleFunctionLabels(f: IrFunction): LocallyVisibleFunctionLabels {
if (!f.isLocalFunction()){
logger.error("Extracting a non-local function as a local one")
}
var res = tw.lm.locallyVisibleFunctionLabelMapping[f]
if (res == null) {
val javaResult = TypeResult(tw.getFreshIdLabel<DbClass>(), "", "")
val kotlinResult = TypeResult(tw.getFreshIdLabel<DbKt_notnull_type>(), "", "")
tw.writeKt_notnull_types(kotlinResult.id, javaResult.id)
res = LocallyVisibleFunctionLabels(
TypeResults(javaResult, kotlinResult),
tw.getFreshIdLabel(),
tw.getFreshIdLabel(),
tw.getFreshIdLabel()
)
tw.lm.locallyVisibleFunctionLabelMapping[f] = res
}
return res
}
fun getExistingLocallyVisibleFunctionLabel(f: IrFunction): Label<DbMethod>? {
if (!f.isLocalFunction()){
return null
}
return tw.lm.locallyVisibleFunctionLabelMapping[f]?.function
}
private fun kotlinFunctionToJavaEquivalent(f: IrFunction, noReplace: Boolean): IrFunction =
if (noReplace)
f
else
f.parentClassOrNull?.let { parentClass ->
getJavaEquivalentClass(parentClass)?.let { javaClass ->
if (javaClass != parentClass) {
var jvmName = getFunctionShortName(f).nameInDB
if (f.name.asString() == "get" && parentClass.fqNameWhenAvailable?.asString() == "kotlin.String") {
// `kotlin.String.get` has an equivalent `java.lang.String.get`, which in turn will be stored in the DB as `java.lang.String.charAt`.
// Maybe all operators should be handled the same way, but so far I only found this case that needed to be special cased. This is the
// only operator in `JvmNames.specialFunctions`
jvmName = "get"
}
// Look for an exact type match...
javaClass.declarations.findSubType<IrFunction> { decl ->
!decl.isFakeOverride &&
decl.name.asString() == jvmName &&
decl.valueParameters.size == f.valueParameters.size &&
decl.valueParameters.zip(f.valueParameters).all { p -> erase(p.first.type).classifierOrNull == erase(p.second.type).classifierOrNull }
} ?:
// Or check property accessors:
(f.propertyIfAccessor as? IrProperty)?.let { kotlinProp ->
val javaProp = javaClass.declarations.findSubType<IrProperty> { decl ->
decl.name == kotlinProp.name
}
if (javaProp?.getter?.name == f.name)
javaProp.getter
else if (javaProp?.setter?.name == f.name)
javaProp.setter
else null
} ?: run {
val parentFqName = parentClass.fqNameWhenAvailable?.asString()
logger.warn("Couldn't find a Java equivalent function to $parentFqName.${f.name.asString()} in ${javaClass.fqNameWhenAvailable?.asString()}")
null
}
}
else
null
}
} ?: f
fun isPrivate(d: IrDeclaration) =
when(d) {
is IrDeclarationWithVisibility -> d.visibility.let { it == DescriptorVisibilities.PRIVATE || it == DescriptorVisibilities.PRIVATE_TO_THIS }
else -> false
}
fun <T: DbCallable> useFunction(f: IrFunction, classTypeArgsIncludingOuterClasses: List<IrTypeArgument>? = null, noReplace: Boolean = false): Label<out T> {
return useFunction(f, null, classTypeArgsIncludingOuterClasses, noReplace)
}
fun <T: DbCallable> useFunction(f: IrFunction, parentId: Label<out DbElement>?, classTypeArgsIncludingOuterClasses: List<IrTypeArgument>?, noReplace: Boolean = false): Label<out T> {
if (f.isLocalFunction()) {
val ids = getLocallyVisibleFunctionLabels(f)
return ids.function.cast<T>()
}
val javaFun = kotlinFunctionToJavaEquivalent(f, noReplace)
val label = getFunctionLabel(javaFun, parentId, classTypeArgsIncludingOuterClasses)
val id: Label<T> = tw.getLabelFor(label) {
extractPrivateSpecialisedDeclaration(f, classTypeArgsIncludingOuterClasses)
}
if (isExternalDeclaration(javaFun)) {
extractFunctionLaterIfExternalFileMember(javaFun)
extractExternalEnclosingClassLater(javaFun)
}
return id
}
private fun extractPrivateSpecialisedDeclaration(d: IrDeclaration, classTypeArgsIncludingOuterClasses: List<IrTypeArgument>?) {
// Note here `classTypeArgsIncludingOuterClasses` being null doesn't signify a raw receiver type but rather that no type args were supplied.
// This is because a call to a private method can only be observed inside Kotlin code, and Kotlin can't represent raw types.
if (this is KotlinFileExtractor && isPrivate(d) && classTypeArgsIncludingOuterClasses != null && classTypeArgsIncludingOuterClasses.isNotEmpty()) {
d.parent.let {
when(it) {
is IrClass -> this.extractDeclarationPrototype(d, useClassInstance(it, classTypeArgsIncludingOuterClasses).typeResult.id, classTypeArgsIncludingOuterClasses)
else -> logger.warnElement("Unable to extract specialised declaration that isn't a member of a class", d)
}
}
}
}
fun getTypeArgumentLabel(
arg: IrTypeArgument
): TypeResultWithoutSignature<DbReftype> {
fun extractBoundedWildcard(wildcardKind: Int, wildcardLabelStr: String, wildcardShortName: String, boundLabel: Label<out DbReftype>): Label<DbWildcard> =
tw.getLabelFor(wildcardLabelStr) { wildcardLabel ->
tw.writeWildcards(wildcardLabel, wildcardShortName, wildcardKind)
tw.writeHasLocation(wildcardLabel, tw.unknownLocation)
tw.getLabelFor<DbTypebound>("@\"bound;0;{$wildcardLabel}\"") {
tw.writeTypeBounds(it, boundLabel, 0, wildcardLabel)
}
}
// Note this function doesn't return a signature because type arguments are never incorporated into function signatures.
return when (arg) {
is IrStarProjection -> {
val anyTypeLabel = useType(pluginContext.irBuiltIns.anyType).javaResult.id.cast<DbReftype>()
TypeResultWithoutSignature(extractBoundedWildcard(1, "@\"wildcard;\"", "?", anyTypeLabel), Unit, "?")
}
is IrTypeProjection -> {
val boundResults = useType(arg.type, TypeContext.GENERIC_ARGUMENT)
val boundLabel = boundResults.javaResult.id.cast<DbReftype>()
return if(arg.variance == Variance.INVARIANT)
boundResults.javaResult.cast<DbReftype>().forgetSignature()
else {
val keyPrefix = if (arg.variance == Variance.IN_VARIANCE) "super" else "extends"
val wildcardKind = if (arg.variance == Variance.IN_VARIANCE) 2 else 1
val wildcardShortName = "? $keyPrefix ${boundResults.javaResult.shortName}"
TypeResultWithoutSignature(
extractBoundedWildcard(wildcardKind, "@\"wildcard;$keyPrefix{$boundLabel}\"", wildcardShortName, boundLabel),
Unit,
wildcardShortName)
}
}
else -> {
logger.error("Unexpected type argument.")
return extractJavaErrorType().forgetSignature()
}
}
}
data class ClassLabelResults(
val classLabel: String, val shortName: String
)
/**
* This returns the `X` in c's label `@"class;X"`.
*
* `argsIncludingOuterClasses` can be null to describe a raw generic type.
* For non-generic types it will be zero-length list.
*/
private fun getUnquotedClassLabel(c: IrClass, argsIncludingOuterClasses: List<IrTypeArgument>?): ClassLabelResults {
val pkg = c.packageFqName?.asString() ?: ""
val cls = c.name.asString()
val label =
if (c.isAnonymousObject)
"{${useAnonymousClass(c).javaResult.id}}"
else
when (val parent = c.parent) {
is IrClass -> {
"${getUnquotedClassLabel(parent, listOf()).classLabel}\$$cls"
}
is IrFunction -> {
"{${useFunction<DbMethod>(parent)}}.$cls"
}
is IrField -> {
"{${useField(parent)}}.$cls"
}
else -> {
if (pkg.isEmpty()) cls else "$pkg.$cls"
}
}
val reorderedArgs = orderTypeArgsLeftToRight(c, argsIncludingOuterClasses)
val typeArgLabels = reorderedArgs?.map { getTypeArgumentLabel(it) }
val typeArgsShortName =
if (typeArgLabels == null)
"<>"
else if(typeArgLabels.isEmpty())
""
else
typeArgLabels.takeLast(c.typeParameters.size).joinToString(prefix = "<", postfix = ">", separator = ",") { it.shortName }
val shortNamePrefix = if (c.isAnonymousObject) "" else cls
return ClassLabelResults(
label + (typeArgLabels?.joinToString(separator = "") { ";{${it.id}}" } ?: "<>"),
shortNamePrefix + typeArgsShortName
)
}
// `args` can be null to describe a raw generic type.
// For non-generic types it will be zero-length list.
fun getClassLabel(c: IrClass, argsIncludingOuterClasses: List<IrTypeArgument>?): ClassLabelResults {
val unquotedLabel = getUnquotedClassLabel(c, argsIncludingOuterClasses)
return ClassLabelResults(
"@\"class;${unquotedLabel.classLabel}\"",
unquotedLabel.shortName)
}
fun useClassSource(c: IrClass): Label<out DbClassorinterface> {
// For source classes, the label doesn't include any type arguments
val classTypeResult = addClassLabel(c, listOf())
return classTypeResult.id
}
fun getTypeParameterParentLabel(param: IrTypeParameter) =
param.parent.let {
(it as? IrFunction)?.let { fn ->
if (this is KotlinFileExtractor)
this.declarationStack.findOverriddenAttributes(fn)?.id
else
null
} ?:
when (it) {
is IrClass -> useClassSource(it)
is IrFunction -> useFunction(it, noReplace = true)
else -> { logger.error("Unexpected type parameter parent $it"); null }
}
}
fun getTypeParameterLabel(param: IrTypeParameter): String {
// Use this instead of `useDeclarationParent` so we can use useFunction with noReplace = true,
// ensuring that e.g. a method-scoped type variable declared on kotlin.String.transform <R> gets
// a different name to the corresponding java.lang.String.transform <R>, even though useFunction
// will usually replace references to one function with the other.
val parentLabel = getTypeParameterParentLabel(param)
return "@\"typevar;{$parentLabel};${param.name}\""
}
private fun useTypeParameter(param: IrTypeParameter) =
TypeResult(
tw.getLabelFor<DbTypevariable>(getTypeParameterLabel(param)),
useType(eraseTypeParameter(param)).javaResult.signature,
param.name.asString()
)
private fun extractModifier(m: String): Label<DbModifier> {
val modifierLabel = "@\"modifier;$m\""
val id: Label<DbModifier> = tw.getLabelFor(modifierLabel, {
tw.writeModifiers(it, m)
})
return id
}
fun addModifiers(modifiable: Label<out DbModifiable>, vararg modifiers: String) =
modifiers.forEach { tw.writeHasModifier(modifiable, extractModifier(it)) }
sealed class ExtractSupertypesMode {
object Unbound : ExtractSupertypesMode()
object Raw : ExtractSupertypesMode()
data class Specialised(val typeArgs : List<IrTypeArgument>) : ExtractSupertypesMode()
}
/**
* Extracts the supertypes of class `c`, either the unbound version, raw version or a specialisation to particular
* type arguments, depending on the value of `mode`. `id` is the label of this class or class instantiation.
*
* For example, for type `List` if `mode` `Specialised([String])` then we will extract the supertypes
* of `List<String>`, i.e. `Appendable<String>` etc, or if `mode` is `Unbound` we will extract `Appendable<E>`
* where `E` is the type variable declared as `List<E>`. Finally if `mode` is `Raw` we will extract the raw type
* `Appendable`, represented in QL as `Appendable<>`.
*
* Argument `inReceiverContext` will be passed onto the `useClassInstance` invocation for each supertype.
*/
fun extractClassSupertypes(c: IrClass, id: Label<out DbReftype>, mode: ExtractSupertypesMode = ExtractSupertypesMode.Unbound, inReceiverContext: Boolean = false) {
extractClassSupertypes(c.superTypes, c.typeParameters, id, c.isInterfaceLike, mode, inReceiverContext)
}
fun extractClassSupertypes(superTypes: List<IrType>, typeParameters: List<IrTypeParameter>, id: Label<out DbReftype>, isInterface: Boolean, mode: ExtractSupertypesMode = ExtractSupertypesMode.Unbound, inReceiverContext: Boolean = false) {
// Note we only need to substitute type args here because it is illegal to directly extend a type variable.
// (For example, we can't have `class A<E> : E`, but can have `class A<E> : Comparable<E>`)
val subbedSupertypes = when(mode) {
is ExtractSupertypesMode.Specialised -> {
superTypes.map {
it.substituteTypeArguments(typeParameters, mode.typeArgs)
}
}
else -> superTypes
}
for(t in subbedSupertypes) {
when(t) {
is IrSimpleType -> {
when (val owner = t.classifier.owner) {
is IrClass -> {
val typeArgs = if (t.arguments.isNotEmpty() && mode is ExtractSupertypesMode.Raw) null else t.arguments
val l = useClassInstance(owner, typeArgs, inReceiverContext).typeResult.id
if (isInterface || !owner.isInterfaceLike) {
tw.writeExtendsReftype(id, l)
} else {
tw.writeImplInterface(id.cast(), l.cast())
}
}
else -> {
logger.error("Unexpected simple type supertype: " + t.javaClass + ": " + t.render())
}
}
} else -> {
logger.error("Unexpected supertype: " + t.javaClass + ": " + t.render())
}
}
}
}
fun useValueDeclaration(d: IrValueDeclaration): Label<out DbVariable>? =
when(d) {
is IrValueParameter -> useValueParameter(d, null)
is IrVariable -> useVariable(d)
else -> {
logger.error("Unrecognised IrValueDeclaration: " + d.javaClass)
null
}
}
/**
* Returns `t` with generic types replaced by raw types, and type parameters replaced by their first bound.
*
* Note that `Array<T>` is retained (with `T` itself erased) because these are expected to be lowered to Java
* arrays, which are not generic.
*/
fun erase (t: IrType): IrType {
if (t is IrSimpleType) {
val classifier = t.classifier
val owner = classifier.owner
if(owner is IrTypeParameter) {
return eraseTypeParameter(owner)
}
if (owner is IrClass) {
if (t.isArray() || t.isNullableArray()) {
val elementType = t.getArrayElementType(pluginContext.irBuiltIns)
val erasedElementType = erase(elementType)
return owner.typeWith(erasedElementType).codeQlWithHasQuestionMark(t.isNullable())
}
return if (t.arguments.isNotEmpty())
t.addAnnotations(listOf(RawTypeAnnotation.annotationConstructor))
else
t
}
}
return t
}
private fun eraseTypeParameter(t: IrTypeParameter) =
erase(t.superTypes[0])
fun getValueParameterLabel(parentId: Label<out DbElement>?, idx: Int) = "@\"params;{$parentId};$idx\""
/**
* Gets the label for `vp` in the context of function instance `parent`, or in that of its declaring function if
* `parent` is null.
*/
fun getValueParameterLabel(vp: IrValueParameter, parent: Label<out DbCallable>?): String {
val declarationParent = vp.parent
val overriddenParentAttributes = (declarationParent as? IrFunction)?.let {
(this as? KotlinFileExtractor)?.declarationStack?.findOverriddenAttributes(it)
}
val parentId = parent ?: overriddenParentAttributes?.id ?: useDeclarationParent(declarationParent, false)
val idxBase = overriddenParentAttributes?.valueParameters?.indexOf(vp) ?: vp.index
val idxOffset = if (declarationParent is IrFunction && declarationParent.extensionReceiverParameter != null)
// For extension functions increase the index to match what the java extractor sees:
1
else
0
val idx = idxBase + idxOffset
if (idx < 0) {
// We're not extracting this and this@TYPE parameters of functions:
logger.error("Unexpected negative index for parameter")
}
return getValueParameterLabel(parentId, idx)
}
fun useValueParameter(vp: IrValueParameter, parent: Label<out DbCallable>?): Label<out DbParam> =
tw.getLabelFor(getValueParameterLabel(vp, parent))
private fun isDirectlyExposedCompanionObjectField(f: IrField) =
f.hasAnnotation(FqName("kotlin.jvm.JvmField")) ||
f.correspondingPropertySymbol?.owner?.let {
it.isConst || it.isLateinit
} ?: false
fun getFieldParent(f: IrField) =
f.parentClassOrNull?.let {
if (it.isCompanion && isDirectlyExposedCompanionObjectField(f))
it.parent
else
null
} ?: f.parent
// Gets a field's corresponding property's extension receiver type, if any
fun getExtensionReceiverType(f: IrField) =
f.correspondingPropertySymbol?.owner?.let {
(it.getter ?: it.setter)?.extensionReceiverParameter?.type
}
fun getFieldLabel(f: IrField): String {
val parentId = useDeclarationParent(getFieldParent(f), false)
// Distinguish backing fields of properties based on their extension receiver type;
// otherwise two extension properties declared in the same enclosing context will get
// clashing trap labels. These are always private, so we can just make up a label without
// worrying about their names as seen from Java.
val extensionPropertyDiscriminator = getExtensionReceiverType(f)?.let { "extension;${useType(it).javaResult.id}" } ?: ""
return "@\"field;{$parentId};${extensionPropertyDiscriminator}${f.name.asString()}\""
}
fun useField(f: IrField): Label<out DbField> =
tw.getLabelFor<DbField>(getFieldLabel(f)).also { extractFieldLaterIfExternalFileMember(f) }
fun getPropertyLabel(p: IrProperty): String? {
val parentId = useDeclarationParent(p.parent, false)
if (parentId == null) {
return null
} else {
return getPropertyLabel(p, parentId, null)
}
}
private fun getPropertyLabel(p: IrProperty, parentId: Label<out DbElement>, classTypeArgsIncludingOuterClasses: List<IrTypeArgument>?): String {
val getter = p.getter
val setter = p.setter
val func = getter ?: setter
val ext = func?.extensionReceiverParameter
return if (ext == null) {
"@\"property;{$parentId};${p.name.asString()}\""
} else {
val returnType = getter?.returnType ?: setter?.valueParameters?.singleOrNull()?.type ?: pluginContext.irBuiltIns.unitType
val typeParams = getFunctionTypeParameters(func)
getFunctionLabel(p.parent, parentId, p.name.asString(), listOf(), returnType, ext.type, typeParams, classTypeArgsIncludingOuterClasses, overridesCollectionsMethod = false, javaSignature = null, addParameterWildcardsByDefault = false, prefix = "property")
}
}
fun useProperty(p: IrProperty, parentId: Label<out DbElement>, classTypeArgsIncludingOuterClasses: List<IrTypeArgument>?) =
tw.getLabelFor<DbKt_property>(getPropertyLabel(p, parentId, classTypeArgsIncludingOuterClasses)) {
extractPropertyLaterIfExternalFileMember(p)
extractPrivateSpecialisedDeclaration(p, classTypeArgsIncludingOuterClasses)
}
fun getEnumEntryLabel(ee: IrEnumEntry): String {
val parentId = useDeclarationParent(ee.parent, false)
return "@\"field;{$parentId};${ee.name.asString()}\""
}
fun useEnumEntry(ee: IrEnumEntry): Label<out DbField> =
tw.getLabelFor(getEnumEntryLabel(ee))
fun getTypeAliasLabel(ta: IrTypeAlias): String {
val parentId = useDeclarationParent(ta.parent, true)
return "@\"type_alias;{$parentId};${ta.name.asString()}\""
}
fun useTypeAlias(ta: IrTypeAlias): Label<out DbKt_type_alias> =
tw.getLabelFor(getTypeAliasLabel(ta))
fun useVariable(v: IrVariable): Label<out DbLocalvar> {
return tw.getVariableLabelFor<DbLocalvar>(v)
}
}
|
mit
|
22f77d27095b4826ce8de761d7eb89f1
| 48.610951 | 266 | 0.626349 | 4.898139 | false | false | false | false |
TheMrMilchmann/lwjgl3
|
modules/lwjgl/opengles/src/templates/kotlin/opengles/templates/NV_clip_space_w_scaling.kt
|
4
|
5123
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengles.templates
import org.lwjgl.generator.*
import opengles.*
val NV_clip_space_w_scaling = "NVClipSpaceWScaling".nativeClassGLES("NV_clip_space_w_scaling", postfix = NV) {
documentation =
"""
Virtual Reality (VR) applications often involve a post-processing step to apply a "barrel" distortion to the rendered image to correct the "pincushion"
distortion introduced by the optics in a VR device. The barrel distorted image has lower resolution along the edges compared to the center. Since the
original image is rendered at high resolution, which is uniform across the complete image, a lot of pixels towards the edges do not make it to the
final post-processed image.
This extension also provides a mechanism to render VR scenes at a non-uniform resolution, in particular a resolution that falls linearly from the
center towards the edges. This is achieved by scaling the "w" coordinate of the vertices in the clip space before perspective divide. The clip space
"w" coordinate of the vertices may be offset as of a function of "x" and "y" coordinates as follows:
${codeBlock("""
w' = w + Ax + By""")}
In the intended use case for viewport position scaling, an application should use a set of 4 viewports, one for each of the 4 quadrants of a Cartesian
coordinate system. Each viewport is set to the dimension of the image, but is scissored to the quadrant it represents. The application should specify A
and B coefficients of the w-scaling equation above, that have the same value, but different signs, for each of the viewports. The signs of A and B
should match the signs of X and Y for the quadrant that they represent such that the value of "w'" will always be greater than or equal to the original
"w" value for the entire image. Since the offset to "w", (Ax + By), is always positive and increases with the absolute values of "x" and "y", the
effective resolution will fall off linearly from the center of the image to its edges.
Requires ${NV_viewport_array.link} or ${OES_viewport_array.link}.
"""
IntConstant(
"Accepted by the {@code cap} parameter of Enable, Disable, IsEnabled.",
"VIEWPORT_POSITION_W_SCALE_NV"..0x937C
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleani_v, GetDoublei_v, GetIntegeri_v, GetFloati_v, and GetInteger64i_v.",
"VIEWPORT_POSITION_W_SCALE_X_COEFF"..0x937D,
"VIEWPORT_POSITION_W_SCALE_Y_COEFF"..0x937E
)
void(
"ViewportPositionWScaleNV",
"""
If #VIEWPORT_POSITION_W_SCALE_NV is enabled, the w coordinates for each primitive sent to a given viewport will be scaled as a function of its x and y
coordinates using the following equation:
${codeBlock("""
w' = xcoeff * x + ycoeff * y + w;""")}
The coefficients for "x" and "y" used in the above equation depend on the viewport index, and are controlled by this command.
The viewport specified by {@code index} has its coefficients for "x" and "y" set to the {@code xcoeff} and {@code ycoeff} values. Specifying these
coefficients enables rendering images at a non-uniform resolution, in particular a resolution that falls off linearly from the center towards the
edges, which is useful for VR applications. VR applications often involve a post-processing step to apply a "barrel" distortion to the rendered image
to correct the "pincushion" distortion introduced by the optics in a VR device. The barrel distorted image, has lower resolution along the edges
compared to the center. Since the original image is rendered at high resolution, which is uniform across the complete image, a lot of pixels towards
the edges do not make it to the final post-processed image. VR applications may use the w-scaling to minimize the processing of unused fragments. To
achieve the intended effect, applications should use a set of 4 viewports one for each of the 4 quadrants of a Cartesian coordinate system. Each
viewport is set to the dimension of the image, but is scissored to the quadrant it represents. The application should specify the x and y coefficients
of the w-scaling equation above, that have the same value, but different signs, for each of the viewports. The signs of {@code xcoeff} and
{@code ycoeff} should match the signs of X and Y for the quadrant that they represent such that the value of "w'" will always be greater than or equal
to the original "w" value for the entire image. Since the offset to "w", (Ax + By), is always positive and increases with the absolute values of "x"
and "y", the effective resolution will fall off linearly from the center of the image to its edges.
""",
GLuint("index", "the viewport index"),
GLfloat("xcoeff", "the x coefficient"),
GLfloat("ycoeff", "the y coefficient")
)
}
|
bsd-3-clause
|
fa499ca1b062268dd249a076fc2c30be
| 67.32 | 159 | 0.715401 | 4.435498 | false | false | false | false |
laviua/komock
|
komock-core/src/main/kotlin/ua/com/lavi/komock/model/config/http/HttpServerProperties.kt
|
1
|
1660
|
package ua.com.lavi.komock.model.config.http
import ua.com.lavi.komock.model.SslKeyStore
/**
* Created by Oleksandr Loushkin
*/
open class HttpServerProperties {
var enabled: Boolean = true
var contextPath = "/"
var name = "defaultInstanceName" // default name
var virtualHosts: List<String> = ArrayList()
var host = "0.0.0.0" // listen on all interfaces
var port = 8080 // default port;
var routes: List<RouteProperties> = ArrayList()
var ssl: SSLServerProperties = SSLServerProperties()
var capture: CaptureProperties = CaptureProperties()
var minThreads: Int = 10
var maxThreads: Int = 100
var idleTimeout: Int = 60000
fun withName(name: String): HttpServerProperties {
this.name = name
return this
}
fun withHost(host: String): HttpServerProperties {
this.host = host
return this
}
fun withPort(port: Int): HttpServerProperties {
this.port = port
return this
}
fun withSsl(sslServerProperties: SSLServerProperties): HttpServerProperties {
this.ssl = sslServerProperties
return this
}
fun withCapture(captureProperties: CaptureProperties): HttpServerProperties {
this.capture = captureProperties
return this
}
fun withRoutes(routes: List<RouteProperties>): HttpServerProperties {
this.routes = routes
return this
}
fun hasRoutes(): Boolean {
if (routes.isEmpty()) {
return false
}
return true
}
fun keyStore(): SslKeyStore {
return SslKeyStore(ssl.keyStoreLocation, ssl.keyStorePassword)
}
}
|
apache-2.0
|
1f5d388108668b16e8b2928ffd1171aa
| 25.349206 | 81 | 0.653614 | 4.573003 | false | false | false | false |
gituser9/InvoiceManagement
|
app/src/main/java/com/user/invoicemanagement/presenter/MainPresenter.kt
|
1
|
8115
|
package com.user.invoicemanagement.presenter
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.os.Environment
import com.user.invoicemanagement.R
import com.user.invoicemanagement.model.dto.Product
import com.user.invoicemanagement.model.dto.ProductFactory
import com.user.invoicemanagement.other.Constant
import com.user.invoicemanagement.view.interfaces.MainView
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import jxl.Workbook
import jxl.WorkbookSettings
import jxl.write.Label
import jxl.write.WritableWorkbook
import jxl.write.WriteException
import jxl.write.biff.RowsExceededException
import java.io.File
import java.io.IOException
import java.util.*
class MainPresenter(var view: MainView) : BasePresenter() {
fun getAll() {
model.getAll()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { factoryList ->
view.showAll(factoryList)
}
}
fun addNewFactory() {
model.addNewFactory("New")
getAll()
}
fun addNewProduct(factoryId: Long) {
val subscription = model.addNewProduct(factoryId) ?: return
subscription
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
getAll()
}
}
fun deleteProduct(id: Long) {
model.deleteProduct(id)
getAll()
}
fun updateProduct(product: Product) {
val subscription = model.updateProduct(product) ?: return
}
fun deleteFactory(id: Long) {
view.showConfirm(R.string.delete_factory_question, DialogInterface.OnClickListener { _: DialogInterface, _: Int ->
model.deleteFactory(id)
getAll()
})
}
fun updateFactory(newName: String, factoryId: Long) {
model.updateFactory(newName, factoryId)
getAll()
}
fun getSummary() {
model.getSummary()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { summary ->
view.showSummaryDialog(summary)
}
}
fun closeInvoice() {
view.showConfirm(R.string.close_invoice_question, DialogInterface.OnClickListener { _: DialogInterface, _: Int ->
model.closeInvoice()
getAll()
view.showToast(R.string.invoice_closed)
})
}
fun filter(name: String) {
model.filterProducts(name)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { factoryList ->
view.showAll(factoryList)
}
}
fun exportToExcel(context: Context) {
val preferences = context.getSharedPreferences(Constant.settingsName, Context.MODE_PRIVATE)
val email = preferences.getString(Constant.emailForReportsKey, "")
if (email.isEmpty()) {
view.showAlert(R.string.email_is_required)
return
}
view.showWait()
model.getAll()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { factoryList ->
if (!createExcel(factoryList)) {
view.hideWait()
return@subscribe
}
sendEmail(context)
view.hideWait()
}
}
private fun createExcel(factories: List<ProductFactory>): Boolean {
val filename = "Invoice.xls"
//Saving file in external storage
val sdCard = Environment.getExternalStorageDirectory()
val directory = File(sdCard.absolutePath + "/invoices")
//create directory if not exist
if (!directory.isDirectory) {
directory.mkdirs()
}
val file = File(directory, filename)
val wbSettings = WorkbookSettings()
wbSettings.locale = Locale("en", "EN")
val workbook: WritableWorkbook
try {
workbook = Workbook.createWorkbook(file, wbSettings)
val sheet = workbook.createSheet("Invoice", 0)
var currentRow = 0
try {
for (factory in factories) {
sheet.addCell(Label(0, currentRow, factory.name))
sheet.addCell(Label(8, currentRow, "Продажная"))
sheet.addCell(Label(9, currentRow, "Закупочная"))
++currentRow
if (factory.products == null || factory.products!!.isEmpty()) {
currentRow += 2
continue
}
for (product in factory.products!!) {
sheet.addCell(Label(0, currentRow, product.name))
sheet.addCell(Label(1, currentRow, product.weightOnStore.toString()))
sheet.addCell(Label(2, currentRow, product.weightInFridge.toString()))
sheet.addCell(Label(3, currentRow, product.weightInStorage.toString()))
sheet.addCell(Label(4, currentRow, product.weight4.toString()))
sheet.addCell(Label(5, currentRow, product.weight5.toString()))
sheet.addCell(Label(6, currentRow, Constant.priceFormat.format(product.sellingPrice)))
sheet.addCell(Label(7, currentRow, Constant.priceFormat.format(product.purchasePrice)))
sheet.addCell(Label(8, currentRow, Constant.priceFormat.format(product.sellingPriceSummary)))
sheet.addCell(Label(9, currentRow, Constant.priceFormat.format(product.purchasePriceSummary)))
++currentRow
}
++currentRow
}
} catch (e: RowsExceededException) {
return false
} catch (e: WriteException) {
return false
}
workbook.write()
try {
workbook.close()
} catch (e: WriteException) {
return false
}
} catch (e: IOException) {
return false
}
return true
}
private fun sendEmail(context: Context) {
val filename = "Invoice.xls"
val sdCard = Environment.getExternalStorageDirectory()
val directory = File(sdCard.absolutePath + "/invoices")
if (!directory.isDirectory) {
directory.mkdirs()
}
val file = File(directory, filename)
val path = Uri.fromFile(file)
val emailIntent = Intent(Intent.ACTION_SEND)
emailIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
// set the type to 'email'
emailIntent.type = "vnd.android.cursor.dir/email"
val preferences = context.getSharedPreferences(Constant.settingsName, Context.MODE_PRIVATE)
val email = preferences.getString(Constant.emailForReportsKey, "")
val to = arrayOf(email)
emailIntent.putExtra(Intent.EXTRA_EMAIL, to)
// the attachment
emailIntent.putExtra(Intent.EXTRA_STREAM, path)
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject")
context.startActivity(Intent.createChooser(emailIntent, "Send email..."))
}
fun saveAll(products: List<Product>, successMessage: String, showMessage: Boolean) {
Observable.fromArray(products)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { list: List<Product> ->
model.saveAll(list)
if (showMessage) {
view.showToast(successMessage)
}
}
}
}
|
mit
|
2740241d7ec41bf4d121525539ae34d5
| 32.320988 | 122 | 0.581892 | 5.095028 | false | false | false | false |
auricgoldfinger/Memento-Namedays
|
android_mobile/src/main/java/com/alexstyl/specialdates/dailyreminder/actions/ContactActionsPresenter.kt
|
3
|
1867
|
package com.alexstyl.specialdates.dailyreminder.actions
import com.alexstyl.specialdates.contact.Contact
import com.alexstyl.specialdates.person.ContactActions
import com.alexstyl.specialdates.person.ContactActionsProvider
import io.reactivex.Observable
import io.reactivex.Scheduler
import io.reactivex.disposables.Disposable
class ContactActionsPresenter(
private val personActionsProvider: ContactActionsProvider,
private val workScheduler: Scheduler,
private val resultScheduler: Scheduler) {
private var disposable: Disposable? = null
fun startPresentingCallsInto(view: ContactActionsView, contactActions: ContactActions) {
disposable =
callActionsFor(contactActions, view.contact())
.observeOn(resultScheduler)
.subscribeOn(workScheduler)
.subscribe { viewModels ->
view.display(viewModels)
}
}
private fun callActionsFor(contactActions: ContactActions, contact: Contact) =
Observable.fromCallable { personActionsProvider.callActionsFor(contact, contactActions) }
fun startPresentingMessagingInto(view: ContactActionsView, contactActions: ContactActions) {
disposable =
messagingActionsFor(contactActions, view.contact())
.observeOn(resultScheduler)
.subscribeOn(workScheduler)
.subscribe { viewModels ->
view.display(viewModels)
}
}
private fun messagingActionsFor(contactActions: ContactActions, contact: Contact) =
Observable.fromCallable { personActionsProvider.messagingActionsFor(contact, contactActions) }
fun stopPresenting() {
disposable?.dispose()
}
}
|
mit
|
583a2aa133685c25e68523d205361798
| 37.102041 | 106 | 0.664167 | 5.762346 | false | false | false | false |
CAD97/AndensMountain
|
AdventureDataFormat/src/cad97/anden/data/TextScene.kt
|
1
|
1485
|
package cad97.anden.data
data class TextScene(val prompt: List<String>,
val actions: List<Action>)
data class Action(val requirement: Requirement,
val description: String,
val consequences: List<Consequence>)
data class Requirement(val qualifiers: List<Qualification>) {
fun qualifies(player: Player) = qualifiers.fold(true) { running, qualifier ->
running && with(qualifier) {
when (type) {
QualificationType.STAT ->
if (amount > 0)
player.stats[StatType.valueOf(target)] >= amount
else
player.stats[StatType.valueOf(target)] < -amount
QualificationType.ITEM ->
if (amount > 0)
player.inventory[target] >= amount
else
player.inventory[target] < -amount
QualificationType.FLAG ->
player.flags[target] == (amount == 1)
}
}
}
}
enum class QualificationType { STAT, ITEM, FLAG }
data class Qualification(val type: QualificationType,
val target: String,
val amount: Int)
enum class ConsequenceType { MOD_ITEM, MOD_STAT, MOD_FLAG, GOTO_TEXT_SCENE }
data class Consequence(val type: ConsequenceType,
val target: String,
val amount: Int = 1)
|
gpl-3.0
|
baaccd9ed2efe60e211a61c3fedaa2bf
| 37.076923 | 81 | 0.529293 | 4.90099 | false | false | false | false |
chrislo27/Tickompiler
|
src/main/kotlin/rhmodding/tickompiler/gameextractor/GameExtractor.kt
|
2
|
13233
|
package rhmodding.tickompiler.gameextractor
import com.github.salomonbrys.kotson.fromJson
import com.google.gson.Gson
import java.nio.ByteBuffer
import java.util.*
import kotlin.math.pow
import kotlin.math.roundToLong
class GameExtractor(val allSubs: Boolean) {
private var engine = -1
private var isRemix = false
private var ustrings = mutableListOf<Pair<Int, String>>()
private var astrings = mutableListOf<Pair<Int, String>>()
private val USTRING_OPS = mutableMapOf(
0x31 to 0 to arrayOf(1),
0x35 to 0 to arrayOf(1),
0x39 to 0 to arrayOf(1),
0x3E to 0 to arrayOf(1),
0x5D to 0 to arrayOf(1),
0x5D to 2 to arrayOf(0),
0x61 to 2 to arrayOf(0)
)
private val ASTRING_OPS = mutableMapOf(
0x3B to 0 to arrayOf(2),
0x67 to 1 to arrayOf(1),
0x93 to 0 to arrayOf(2, 3),
0x94 to 0 to arrayOf(1, 2, 3),
0x95 to 0 to arrayOf(1),
0xB0 to 4 to arrayOf(1),
0xB0 to 5 to arrayOf(1),
0xB0 to 6 to arrayOf(1),
0x66 to 0 to arrayOf(1),
0x65 to 1 to arrayOf(1),
0x68 to 1 to arrayOf(1),
0xAF to 2 to arrayOf(2),
0xB5 to 0 to arrayOf(0)
)
companion object {
val LOCATIONS: List<List<Int>> by lazy {
Gson().fromJson<List<List<Int>>>(
GameExtractor::class.java.getResource("/locations.json").readText())
}
private const val TEMPO_TABLE = 0x53EF54
private const val DECIMALS: Int = 3
private fun correctlyRoundDouble(value: Double, places: Int): String {
if (places < 0)
error("Places $places cannot be negative")
if (places == 0)
return "$value"
val long: Long = (value * 10.0.pow(places.toDouble())).roundToLong()
val longString = long.toString()
val str = longString.substring(0, longString.length - places) + "." + longString.substring(longString.length - places).trimEnd('0')
return if (str.endsWith('.')) "${str}0" else str
}
fun extractTempo(buffer: ByteBuffer, index: Int): Pair<String, String> {
val ids = mutableListOf(buffer.getIntAdj(TEMPO_TABLE + 16 * index),
buffer.getIntAdj(TEMPO_TABLE + 16 * index + 4))
.filter { it != -1 }
val name = (if (ids[0] != -1) ids[0] else ids[1]).toString(16)
var s: String = ids.joinToString(" ") { it.toString(16) } + "\n"
var addr = buffer.getIntAdj(TEMPO_TABLE + 16 * index + 12)
while (true) {
val beats = buffer.getFloat(addr - 0x100000)
val seconds = buffer.getInt(addr - 0x100000 + 4) / 32000.0 // will not work with unsigned but not important
val bpm = 60 * beats / seconds
s += "${correctlyRoundDouble(bpm, DECIMALS)} ${correctlyRoundDouble(beats.toDouble(), DECIMALS)}\n"
if (buffer.getIntAdj(addr + 8) != 0)
break
addr += 12
}
return name.toUpperCase(Locale.ROOT) to s.toUpperCase(Locale.ROOT)
}
}
fun unicodeStringToInts(str: String): List<Int> {
val result = mutableListOf<Int>()
var i = 0
while (i <= str.length) {
var int = 0
if (i < str.length)
int += str[i].toByte().toInt() shl 0
if (i + 1 < str.length)
int += str[i + 1].toByte().toInt() shl 16
i += 2
result.add(int)
}
return result
}
fun stringToInts(str: String): List<Int> {
val result = mutableListOf<Int>()
var i = 0
while (i <= str.length) {
var int = 0
if (i < str.length)
int += str[i].toByte().toInt() shl 0
if (i + 1 < str.length)
int += str[i + 1].toByte().toInt() shl 8
if (i + 2 < str.length)
int += str[i + 2].toByte().toInt() shl 16
if (i + 3 < str.length)
int += str[i + 3].toByte().toInt() shl 24
i += 4
result.add(int)
}
return result
}
fun extractGateGame(buffer: ByteBuffer, index: Int): Pair<Map<Int, Int>, List<Int>> {
val start = buffer.getGateStart(index)
engine = -1
val funcs = firstPass(buffer, start, buffer.getIntAdj(GATE_TABLE + 36 * index + 8))
val sorted = listOf(funcs[0]) + funcs.drop(1).sortedBy { it.first }
val returnMap = mutableMapOf<Int, Int>()
val map = mutableMapOf<Int, Int>()
var i = 0
for ((first, second) in sorted) {
map[first] = i
if (!isRemix && first in LOCATIONS[engine]) {
returnMap[i] = LOCATIONS[engine].indexOf(first) + 0x56
}
i += second.size * 4
}
for ((first, second) in ustrings) {
map[first] = i
i += unicodeStringToInts(second).size * 4
}
for ((first, second) in astrings) {
map[first] = i
i += stringToInts(second).size * 4
}
val meta = mutableListOf<Int>()
meta.add(index + 0x100)
meta.add(0)
meta.add(map[buffer.getIntAdj(GATE_TABLE + 36 * index + 8)] ?: 0)
return returnMap to (meta + secondPass(sorted.map { it.second }, map))
}
fun extractGame(buffer: ByteBuffer, index: Int): Pair<Map<Int, Int>, List<Int>> {
val start = buffer.getStart(index)
engine = -1
val funcs = firstPass(buffer, start)
val sorted = listOf(funcs[0]) + funcs.drop(1).sortedBy { it.first }
val returnMap = mutableMapOf<Int, Int>()
val map = mutableMapOf<Int, Int>()
var i = 0
for ((first, second) in sorted) {
map[first] = i
if (!isRemix && first in LOCATIONS[engine]) {
returnMap[i] = LOCATIONS[engine].indexOf(first) + 0x56
}
i += second.size * 4
}
for ((first, second) in ustrings) {
map[first] = i
i += unicodeStringToInts(second).size * 4
}
for ((first, second) in astrings) {
map[first] = i
i += stringToInts(second).size * 4
}
val meta = mutableListOf<Int>()
meta.add(index)
meta.add(0)
meta.add(map[buffer.getIntAdj(TABLE_OFFSET + 52 * index + 8)] ?: 0)
return returnMap to (meta + secondPass(sorted.map { it.second }, map))
}
fun extractArbitrary(buffer: ByteBuffer, index: Int): List<Int> {
isRemix = true
engine = -1
val funcs = firstPass(buffer, index, nongame=true)
val sorted = listOf(funcs[0]) + funcs.drop(1).sortedBy {it.first}
val map = mutableMapOf<Int, Int>()
var i = 0
for ((first, second) in sorted) {
map[first] = i
i += second.size * 4
}
for ((first, second) in ustrings) {
map[first] = i
i += unicodeStringToInts(second).size * 4
}
for ((first, second) in astrings) {
map[first] = i
i += stringToInts(second).size * 4
}
val meta = mutableListOf<Int>()
meta.add(-1)
meta.add(0)
meta.add(-1)
return meta + secondPass(sorted.map {it.second}, map)
}
fun secondPass(funcs: List<List<Int>>, map: Map<Int, Int>): List<Int> {
val result = mutableListOf<Int>()
for (l in funcs) {
var i = 0
while (i < l.size) {
val opint = l[i]
val opcode = opint and 0b1111111111
val special = (opint ushr 14)
val argCount = (opint ushr 10) and 0b1111
val args = l.slice(i + 1..i + argCount).toMutableList()
val annotations = mutableListOf<Int>()
i += argCount + 1
if (opcode == 2 || opcode == 6) {
annotations.add(0)
args[0] = map[args[0]] ?: 0
}
if (opcode == 3 && special == 2) {
annotations.add(0)
args[0] = map[args[0]] ?: 0
}
if (opcode == 1 && special == 1) {
annotations.add(0x100)
args[1] = map[args[1]] ?: 0
}
if (opcode to special in USTRING_OPS) {
val n = USTRING_OPS[opcode to special] ?: arrayOf()
for (arg in n) {
annotations.add(1 or (arg shl 8))
args[arg] = map[args[arg]] ?: args[arg]
}
}
if (opcode to special in ASTRING_OPS) {
val n = ASTRING_OPS[opcode to special] ?: arrayOf()
for (arg in n) {
annotations.add(2 or (arg shl 8))
args[arg] = map[args[arg]] ?: args[arg]
}
}
if (annotations.size > 0) {
result.add(-1)
result.add(annotations.size)
result.addAll(annotations)
}
result.add(opint)
result.addAll(args)
}
}
result.add(-2)
result.addAll(ustrings.map { unicodeStringToInts(it.second) }.flatten())
result.addAll(astrings.map { stringToInts(it.second) }.flatten())
return result
}
fun firstPass(buf: ByteBuffer, start: Int, assets: Int? = null, nongame: Boolean = false): List<Pair<Int, List<Int>>> {
val result = mutableListOf<Pair<Int, List<Int>>>()
ustrings = mutableListOf()
isRemix = buf.getIntAdj(start) and 0b1111111111 == 1 || nongame
val q = ArrayDeque<Int>()
q.add(start)
if (assets != null) {
q.add(assets)
}
while (q.isNotEmpty()) {
// compute the size of the function.
val s = q.remove()
var pc = s
var depth = 0
val ints = mutableListOf<Int>()
while (true) {
var opint = buf.getIntAdj(pc)
val opcode = opint and 0b1111111111
val special = (opint ushr 14)
val argCount = (opint ushr 10) and 0b1111
val args = mutableListOf<Int>()
pc += 4
for (i in 1..argCount) {
args.add(buf.getIntAdj(pc))
pc += 4
}
if (opcode to special in USTRING_OPS) {
val n = USTRING_OPS[opcode to special] ?: arrayOf()
n
.filter { args[it] > 0x100000 }
.forEach { ustrings.add(args[it] to buf.getUnicodeString(args[it])) }
}
if (opcode to special in ASTRING_OPS) {
val n = ASTRING_OPS[opcode to special] ?: arrayOf()
n
.filter { args[it] > 0x100000 }
.forEach { astrings.add(args[it] to buf.getASCIIString(args[it])) }
}
if (!isRemix && opcode == 0x28 && special == 0 && engine == -1) {
engine = args[0]
if (allSubs) {
q.addAll(
LOCATIONS[engine].filter { it > 0x100000 })
}
}
if (!isRemix && (opcode == 0 || opcode == 4 || (opcode == 3 && special == 3)) && args[0] >= 0x56 && args[0] < 0x56 + LOCATIONS[engine].size) {
// macro/sub detected.
val location = LOCATIONS[engine][args[0] - 0x56]
if (!q.contains(location) && !result.any { it.first == location }) {
q.add(location)
}
args[0] = location
if (opcode == 0) {
opint = 2 or (2 shl 10)
args.removeAt(2)
} else if (opcode == 4) {
opint = 6 or (1 shl 10)
} else {
opint = 3 or (1 shl 10) or (2 shl 14)
}
}
if (opcode == 2 || opcode == 6) {
val location = args[0]
if (!q.contains(location) && !result.any { it.first == location }) {
q.add(location)
}
}
if (opcode == 1 && special == 1) {
val location = args[1]
if (!q.contains(location) && !result.any { it.first == location }) {
q.add(location)
}
}
if (opcode == 0x16 || opcode == 0x19) {
depth++
}
if (opcode == 0x18 || opcode == 0x1D) {
depth--
}
ints.add(opint)
ints.addAll(args)
if (opcode in 7..8 && depth == 0) {
break
}
}
result.add(Pair(s, ints))
}
return result
}
}
|
mit
|
4a425849803981ff15935e858fdd6ed2
| 35.65928 | 158 | 0.474798 | 3.965538 | false | false | false | false |
google/intellij-community
|
platform/platform-impl/src/com/intellij/ide/startup/impl/StartupManagerImpl.kt
|
1
|
20827
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("OVERRIDE_DEPRECATION")
package com.intellij.ide.startup.impl
import com.intellij.diagnostic.*
import com.intellij.diagnostic.telemetry.TraceManager
import com.intellij.diagnostic.telemetry.useWithScope
import com.intellij.ide.IdeEventQueue
import com.intellij.ide.lightEdit.LightEdit
import com.intellij.ide.lightEdit.LightEditCompatible
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.plugins.cl.PluginAwareClassLoader
import com.intellij.ide.startup.StartupManagerEx
import com.intellij.idea.processExtensions
import com.intellij.openapi.application.*
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.ExtensionPointListener
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl
import com.intellij.openapi.progress.*
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbAwareRunnable
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.impl.isCorePlugin
import com.intellij.openapi.startup.InitProjectActivity
import com.intellij.openapi.startup.ProjectPostStartupActivity
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.util.registry.Registry
import com.intellij.serviceContainer.AlreadyDisposedException
import com.intellij.util.ModalityUiUtil
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.api.common.Attributes
import io.opentelemetry.api.trace.Span
import io.opentelemetry.context.Context
import io.opentelemetry.extension.kotlin.asContextElement
import kotlinx.coroutines.*
import org.intellij.lang.annotations.MagicConstant
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
import org.jetbrains.annotations.VisibleForTesting
import java.awt.event.InvocationEvent
import java.util.*
import java.util.concurrent.CancellationException
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReference
import kotlin.coroutines.coroutineContext
private val LOG = logger<StartupManagerImpl>()
private val tracer by lazy { TraceManager.getTracer("startupManager") }
/**
* Acts as [StartupActivity.POST_STARTUP_ACTIVITY], but executed with 5 seconds delay after project opening.
*/
private val BACKGROUND_POST_STARTUP_ACTIVITY = ExtensionPointName<StartupActivity>("com.intellij.backgroundPostStartupActivity")
private val EDT_WARN_THRESHOLD_IN_NANO = TimeUnit.MILLISECONDS.toNanos(100)
private const val DUMB_AWARE_PASSED = 1
private const val ALL_PASSED = 2
@ApiStatus.Internal
open class StartupManagerImpl(private val project: Project) : StartupManagerEx() {
companion object {
@VisibleForTesting
fun addActivityEpListener(project: Project) {
StartupActivity.POST_STARTUP_ACTIVITY.addExtensionPointListener(object : ExtensionPointListener<StartupActivity> {
override fun extensionAdded(extension: StartupActivity, pluginDescriptor: PluginDescriptor) {
if (project is LightEditCompatible && extension !is LightEditCompatible) {
return
}
val startupManager = getInstance(project) as StartupManagerImpl
val pluginId = pluginDescriptor.pluginId
@Suppress("SSBasedInspection")
if (extension is DumbAware) {
project.coroutineScope.launch {
if (extension is ProjectPostStartupActivity) {
extension.execute(project)
}
else {
startupManager.runActivityAndMeasureDuration(extension, pluginId)
}
}
}
else {
DumbService.getInstance(project).unsafeRunWhenSmart {
startupManager.runActivityAndMeasureDuration(extension, pluginId)
}
}
}
}, project)
}
}
private val lock = Any()
private val initProjectStartupActivities = ArrayDeque<Runnable>()
private val postStartupActivities = ArrayDeque<Runnable>()
@MagicConstant(intValues = [0, DUMB_AWARE_PASSED.toLong(), ALL_PASSED.toLong()])
@Volatile
private var postStartupActivitiesPassed = 0
private val allActivitiesPassed = CompletableDeferred<Any?>()
@Volatile
private var isInitProjectActivitiesPassed = false
private fun checkNonDefaultProject() {
LOG.assertTrue(!project.isDefault, "Please don't register startup activities for the default project: they won't ever be run")
}
override fun registerStartupActivity(runnable: Runnable) {
checkNonDefaultProject()
LOG.assertTrue(!isInitProjectActivitiesPassed, "Registering startup activity that will never be run")
synchronized(lock) {
initProjectStartupActivities.add(runnable)
}
}
override fun registerPostStartupActivity(runnable: Runnable) {
Span.current().addEvent("register startup activity", Attributes.of(AttributeKey.stringKey("runnable"), runnable.toString()))
@Suppress("SSBasedInspection")
if (runnable is DumbAware) {
runAfterOpened(runnable)
}
else {
LOG.error("Activities registered via registerPostStartupActivity must be dumb-aware: $runnable")
}
}
private fun checkThatPostActivitiesNotPassed() {
if (postStartupActivityPassed()) {
LOG.error("Registering post-startup activity that will never be run (" +
" disposed=${project.isDisposed}" +
", open=${project.isOpen}" +
", passed=$isInitProjectActivitiesPassed"
+ ")")
}
}
override fun startupActivityPassed() = isInitProjectActivitiesPassed
override fun postStartupActivityPassed(): Boolean {
return when (postStartupActivitiesPassed) {
ALL_PASSED -> true
-1 -> throw RuntimeException("Aborted; check the log for a reason")
else -> false
}
}
override fun getAllActivitiesPassedFuture() = allActivitiesPassed
suspend fun initProject(indicator: ProgressIndicator?) {
// see https://github.com/JetBrains/intellij-community/blob/master/platform/service-container/overview.md#startup-activity
LOG.assertTrue(!isInitProjectActivitiesPassed)
runActivity("project startup") {
tracer.spanBuilder("run init project activities").useWithScope {
runInitProjectActivities(indicator)
isInitProjectActivitiesPassed = true
}
}
}
suspend fun runStartupActivities() {
// opened on startup
StartUpMeasurer.compareAndSetCurrentState(LoadingState.COMPONENTS_LOADED, LoadingState.PROJECT_OPENED)
// opened from the welcome screen
StartUpMeasurer.compareAndSetCurrentState(LoadingState.APP_STARTED, LoadingState.PROJECT_OPENED)
coroutineContext.ensureActive()
val app = ApplicationManager.getApplication()
if (app.isUnitTestMode && !app.isDispatchThread) {
runPostStartupActivities(async = false)
}
else {
// doesn't block project opening
project.coroutineScope.launch {
runPostStartupActivities(async = true)
}
if (app.isUnitTestMode) {
LOG.assertTrue(app.isDispatchThread)
waitAndProcessInvocationEventsInIdeEventQueue(this)
}
}
}
private suspend fun runInitProjectActivities(indicator: ProgressIndicator?) {
runActivities(initProjectStartupActivities)
val app = ApplicationManager.getApplication()
val extensionPoint = (app.extensionArea as ExtensionsAreaImpl).getExtensionPoint<StartupActivity>("com.intellij.startupActivity")
// do not create extension if not allow-listed
for (adapter in extensionPoint.sortedAdapters) {
coroutineContext.ensureActive()
val pluginId = adapter.pluginDescriptor.pluginId
if (!isCorePlugin(adapter.pluginDescriptor) && pluginId.idString != "com.jetbrains.performancePlugin"
&& pluginId.idString != "com.intellij.clion-makefile"
&& pluginId.idString != "com.intellij.clion-swift"
&& pluginId.idString != "com.intellij.appcode"
&& pluginId.idString != "com.intellij.clion-compdb"
&& pluginId.idString != "com.intellij.kmm") {
LOG.error("Only bundled plugin can define ${extensionPoint.name}: ${adapter.pluginDescriptor}")
continue
}
val activity = adapter.createInstance<InitProjectActivity>(project) ?: continue
indicator?.pushState()
val startTime = StartUpMeasurer.getCurrentTime()
try {
tracer.spanBuilder("run activity")
.setAttribute(AttributeKey.stringKey("class"), activity.javaClass.name)
.setAttribute(AttributeKey.stringKey("plugin"), pluginId.idString)
.useWithScope {
if (project !is LightEditCompatible || activity is LightEditCompatible) {
activity.run(project)
}
}
}
finally {
indicator?.popState()
}
addCompletedActivity(startTime = startTime, runnableClass = activity.javaClass, pluginId = pluginId)
}
}
// Must be executed in a pooled thread outside of project loading modal task. The only exclusion - test mode.
private suspend fun runPostStartupActivities(async: Boolean) {
try {
LOG.assertTrue(isInitProjectActivitiesPassed)
val snapshot = PerformanceWatcher.takeSnapshot()
// strictly speaking, the activity is not sequential, because sub-activities are performed in different threads
// (depending on dumb-awareness), but because there is no other concurrent phase, we measure it as a sequential activity
// to put it on the timeline and make clear what's going at the end (avoiding the last "unknown" phase)
val dumbAwareActivity = StartUpMeasurer.startActivity(StartUpMeasurer.Activities.PROJECT_DUMB_POST_START_UP_ACTIVITIES)
val edtActivity = AtomicReference<Activity?>()
val uiFreezeWarned = AtomicBoolean()
val counter = AtomicInteger()
val dumbService = DumbService.getInstance(project)
val isProjectLightEditCompatible = project is LightEditCompatible
val traceContext = Context.current()
StartupActivity.POST_STARTUP_ACTIVITY.processExtensions { activity, pluginDescriptor ->
if (isProjectLightEditCompatible && activity !is LightEditCompatible) {
return@processExtensions
}
if (activity is ProjectPostStartupActivity) {
val pluginId = pluginDescriptor.pluginId
if (async) {
project.coroutineScope.launch {
val startTime = StartUpMeasurer.getCurrentTime()
val span = tracer.spanBuilder("run activity")
.setAttribute(AttributeKey.stringKey("class"), activity.javaClass.name)
.setAttribute(AttributeKey.stringKey("plugin"), pluginId.idString)
.startSpan()
withContext(traceContext.with(span).asContextElement()) {
activity.execute(project)
}
addCompletedActivity(startTime = startTime, runnableClass = activity.javaClass, pluginId = pluginId)
}
}
else {
activity.execute(project)
}
return@processExtensions
}
@Suppress("SSBasedInspection")
if (activity is DumbAware) {
dumbService.runWithWaitForSmartModeDisabled().use {
blockingContext {
runActivityAndMeasureDuration(activity, pluginDescriptor.pluginId)
}
}
return@processExtensions
}
else {
if (edtActivity.get() == null) {
edtActivity.set(StartUpMeasurer.startActivity("project post-startup edt activities"))
}
// DumbService.unsafeRunWhenSmart throws an assertion in LightEdit mode, see LightEditDumbService.unsafeRunWhenSmart
if (!isProjectLightEditCompatible) {
counter.incrementAndGet()
blockingContext {
dumbService.unsafeRunWhenSmart {
traceContext.makeCurrent()
val duration = runActivityAndMeasureDuration(activity, pluginDescriptor.pluginId)
if (duration > EDT_WARN_THRESHOLD_IN_NANO) {
reportUiFreeze(uiFreezeWarned)
}
dumbUnawarePostActivitiesPassed(edtActivity, counter.decrementAndGet())
}
}
}
}
}
dumbUnawarePostActivitiesPassed(edtActivity, counter.get())
runPostStartupActivitiesRegisteredDynamically()
dumbAwareActivity.end()
snapshot.logResponsivenessSinceCreation("Post-startup activities under progress")
coroutineContext.ensureActive()
if (!ApplicationManager.getApplication().isUnitTestMode) {
scheduleBackgroundPostStartupActivities()
addActivityEpListener(project)
}
}
catch (e: CancellationException) {
throw e
}
catch (e: Throwable) {
if (ApplicationManager.getApplication().isUnitTestMode) {
postStartupActivitiesPassed = -1
}
else {
throw e
}
}
}
private fun runActivityAndMeasureDuration(activity: StartupActivity, pluginId: PluginId): Long {
val startTime = StartUpMeasurer.getCurrentTime()
try {
tracer.spanBuilder("run activity")
.setAttribute(AttributeKey.stringKey("class"), activity.javaClass.name)
.setAttribute(AttributeKey.stringKey("plugin"), pluginId.idString)
.useWithScope {
if (project !is LightEditCompatible || activity is LightEditCompatible) {
activity.runActivity(project)
}
}
}
catch (e: Throwable) {
if (e is ControlFlowException || e is CancellationException) {
throw e
}
LOG.error(e)
}
return addCompletedActivity(startTime = startTime, runnableClass = activity.javaClass, pluginId = pluginId)
}
private suspend fun runPostStartupActivitiesRegisteredDynamically() {
tracer.spanBuilder("run post-startup dynamically registered activities").useWithScope {
runActivities(postStartupActivities, activityName = "project post-startup")
}
postStartupActivitiesPassed = DUMB_AWARE_PASSED
postStartupActivitiesPassed = ALL_PASSED
allActivitiesPassed.complete(value = null)
}
private suspend fun runActivities(activities: Deque<Runnable>, activityName: String? = null) {
synchronized(lock) {
if (activities.isEmpty()) {
return
}
}
val activity = activityName?.let {
StartUpMeasurer.startActivity(it)
}
while (true) {
coroutineContext.ensureActive()
val runnable = synchronized(lock, activities::pollFirst) ?: break
val startTime = StartUpMeasurer.getCurrentTime()
val runnableClass = runnable.javaClass
val pluginId = (runnableClass.classLoader as? PluginAwareClassLoader)?.pluginId ?: PluginManagerCore.CORE_ID
try {
tracer.spanBuilder("run activity")
.setAttribute(AttributeKey.stringKey("class"), runnableClass.name)
.setAttribute(AttributeKey.stringKey("plugin"), pluginId.idString)
.useWithScope {
blockingContext {
runnable.run()
}
}
}
catch (e: CancellationException) {
throw e
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
LOG.error(e)
}
addCompletedActivity(startTime = startTime, runnableClass = runnableClass, pluginId = pluginId)
}
activity?.end()
}
private fun scheduleBackgroundPostStartupActivities() {
project.coroutineScope.launch {
delay(Registry.intValue("ide.background.post.startup.activity.delay", 5_000).toLong())
// read action - dynamic plugin loading executed as a write action
// readActionBlocking because maybe called several times, but addExtensionPointListener must be added only once
readActionBlocking {
BACKGROUND_POST_STARTUP_ACTIVITY.addExtensionPointListener(
object : ExtensionPointListener<StartupActivity> {
override fun extensionAdded(extension: StartupActivity, pluginDescriptor: PluginDescriptor) {
project.coroutineScope.runBackgroundPostStartupActivities(listOf(extension))
}
}, project)
BACKGROUND_POST_STARTUP_ACTIVITY.extensionList
}
if (!isActive) {
return@launch
}
runBackgroundPostStartupActivities(readAction { BACKGROUND_POST_STARTUP_ACTIVITY.extensionList })
}
}
private fun CoroutineScope.runBackgroundPostStartupActivities(activities: List<StartupActivity>) {
for (activity in activities) {
try {
if (project !is LightEditCompatible || activity is LightEditCompatible) {
if (activity is ProjectPostStartupActivity) {
launch {
activity.execute(project)
}
}
else {
activity.runActivity(project)
}
}
}
catch (e: CancellationException) {
throw e
}
catch (e: AlreadyDisposedException) {
coroutineContext.ensureActive()
}
catch (e: Throwable) {
if (e is ControlFlowException) {
throw e
}
LOG.error(e)
}
}
}
override fun runWhenProjectIsInitialized(action: Runnable) {
if (DumbService.isDumbAware(action)) {
runAfterOpened { ModalityUiUtil.invokeLaterIfNeeded(ModalityState.NON_MODAL, project.disposed, action) }
}
else if (!LightEdit.owns(project)) {
runAfterOpened { DumbService.getInstance(project).unsafeRunWhenSmart(action) }
}
}
override fun runAfterOpened(runnable: Runnable) {
checkNonDefaultProject()
if (postStartupActivitiesPassed < DUMB_AWARE_PASSED) {
synchronized(lock) {
if (postStartupActivitiesPassed < DUMB_AWARE_PASSED) {
postStartupActivities.add(runnable)
return
}
}
}
runnable.run()
}
@TestOnly
@Synchronized
fun prepareForNextTest() {
synchronized(lock) {
initProjectStartupActivities.clear()
postStartupActivities.clear()
}
}
@TestOnly
@Synchronized
fun checkCleared() {
try {
synchronized(lock) {
assert(initProjectStartupActivities.isEmpty()) { "Activities: $initProjectStartupActivities" }
assert(postStartupActivities.isEmpty()) { "DumbAware Post Activities: $postStartupActivities" }
}
}
finally {
prepareForNextTest()
}
}
}
private fun addCompletedActivity(startTime: Long, runnableClass: Class<*>, pluginId: PluginId): Long {
return StartUpMeasurer.addCompletedActivity(
startTime,
runnableClass,
ActivityCategory.POST_STARTUP_ACTIVITY,
pluginId.idString,
StartUpMeasurer.MEASURE_THRESHOLD,
)
}
private fun dumbUnawarePostActivitiesPassed(edtActivity: AtomicReference<Activity?>, count: Int) {
if (count == 0) {
edtActivity.getAndSet(null)?.end()
}
}
private fun reportUiFreeze(uiFreezeWarned: AtomicBoolean) {
val app = ApplicationManager.getApplication()
if (!app.isUnitTestMode && app.isDispatchThread && uiFreezeWarned.compareAndSet(false, true)) {
LOG.info("Some post-startup activities freeze UI for noticeable time. " +
"Please consider making them DumbAware to run them in background under modal progress," +
" or just making them faster to speed up project opening.")
}
}
// allow `invokeAndWait` inside startup activities
private suspend fun waitAndProcessInvocationEventsInIdeEventQueue(startupManager: StartupManagerImpl) {
ApplicationManager.getApplication().assertIsDispatchThread()
val eventQueue = IdeEventQueue.getInstance()
if (startupManager.postStartupActivityPassed()) {
withContext(Dispatchers.EDT) {
}
}
else {
// make sure eventQueue.nextEvent will unblock
startupManager.runAfterOpened(DumbAwareRunnable { ApplicationManager.getApplication().invokeLater { } })
}
while (true) {
val event = eventQueue.nextEvent
if (event is InvocationEvent) {
eventQueue.dispatchEvent(event)
}
if (startupManager.postStartupActivityPassed() && eventQueue.peekEvent() == null) {
break
}
}
}
|
apache-2.0
|
d3effe6e7d347fbc776550249507c0e5
| 36.800363 | 133 | 0.695587 | 5.362255 | false | false | false | false |
google/intellij-community
|
platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/roots/ModifiableModuleLibraryTableBridge.kt
|
1
|
9728
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots
import com.google.common.collect.HashBiMap
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.ProjectModelExternalSource
import com.intellij.openapi.roots.impl.ModuleLibraryTableBase
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.PersistentLibraryKind
import com.intellij.openapi.util.Disposer
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.ide.impl.legacyBridge.LegacyBridgeModifiableBase
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryBridge
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryBridgeImpl
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryNameGenerator
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.findLibraryEntity
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.libraryMap
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.mutableLibraryMap
import com.intellij.workspaceModel.storage.bridgeEntities.addLibraryEntity
import com.intellij.workspaceModel.storage.bridgeEntities.addLibraryPropertiesEntity
import com.intellij.workspaceModel.storage.bridgeEntities.api.LibraryEntity
import com.intellij.workspaceModel.storage.bridgeEntities.api.LibraryId
import com.intellij.workspaceModel.storage.bridgeEntities.api.LibraryTableId
import com.intellij.workspaceModel.storage.bridgeEntities.api.ModuleDependencyItem
import org.jetbrains.jps.model.serialization.library.JpsLibraryTableSerializer
internal class ModifiableModuleLibraryTableBridge(private val modifiableModel: ModifiableRootModelBridgeImpl)
: ModuleLibraryTableBase(), ModuleLibraryTableBridge {
private val copyToOriginal = HashBiMap.create<LibraryBridge, LibraryBridge>()
init {
val storage = modifiableModel.moduleBridge.entityStorage.current
libraryEntities()
.forEach { libraryEntry ->
val originalLibrary = storage.libraryMap.getDataByEntity(libraryEntry)
if (originalLibrary != null) {
//if a module-level library from ModifiableRootModel is changed, the changes must not be committed to the model until
//ModifiableRootModel is committed. So we place copies of LibraryBridge instances to the modifiable model. If the model is disposed
//these copies are disposed; if the model is committed they'll be included to the model, and the original instances will be disposed.
val modifiableCopy = LibraryBridgeImpl(this, modifiableModel.project, libraryEntry.persistentId,
modifiableModel.entityStorageOnDiff,
modifiableModel.diff)
copyToOriginal[modifiableCopy] = originalLibrary
modifiableModel.diff.mutableLibraryMap.addMapping(libraryEntry, modifiableCopy)
}
}
}
private fun libraryEntities(): Sequence<LibraryEntity> {
val moduleLibraryTableId = getTableId()
return modifiableModel.entityStorageOnDiff.current
.entities(LibraryEntity::class.java)
.filter { it.tableId == moduleLibraryTableId }
}
override fun getLibraryIterator(): Iterator<Library> {
val storage = modifiableModel.entityStorageOnDiff.current
return libraryEntities().mapNotNull { storage.libraryMap.getDataByEntity(it) }.iterator()
}
override fun createLibrary(name: String?,
type: PersistentLibraryKind<*>?,
externalSource: ProjectModelExternalSource?): Library {
modifiableModel.assertModelIsLive()
val tableId = getTableId()
val libraryEntityName = LibraryNameGenerator.generateLibraryEntityName(name) { existsName ->
LibraryId(existsName, tableId) in modifiableModel.diff
}
val libraryEntity = modifiableModel.diff.addLibraryEntity(
roots = emptyList(),
tableId = tableId,
name = libraryEntityName,
excludedRoots = emptyList(),
source = modifiableModel.moduleEntity.entitySource
)
if (type != null) {
modifiableModel.diff.addLibraryPropertiesEntity(
library = libraryEntity,
libraryType = type.kindId,
propertiesXmlTag = LegacyBridgeModifiableBase.serializeComponentAsString(JpsLibraryTableSerializer.PROPERTIES_TAG,
type.createDefaultProperties())
)
}
return createAndAddLibrary(libraryEntity, false, ModuleDependencyItem.DependencyScope.COMPILE)
}
private fun createAndAddLibrary(libraryEntity: LibraryEntity, exported: Boolean,
scope: ModuleDependencyItem.DependencyScope): LibraryBridgeImpl {
val libraryId = libraryEntity.persistentId
modifiableModel.appendDependency(ModuleDependencyItem.Exportable.LibraryDependency(library = libraryId, exported = exported,
scope = scope))
val library = LibraryBridgeImpl(
libraryTable = ModuleRootComponentBridge.getInstance(modifiableModel.module).moduleLibraryTable,
project = modifiableModel.project,
initialId = libraryEntity.persistentId,
initialEntityStorage = modifiableModel.entityStorageOnDiff,
targetBuilder = modifiableModel.diff
)
modifiableModel.diff.mutableLibraryMap.addMapping(libraryEntity, library)
return library
}
private fun getTableId() = LibraryTableId.ModuleLibraryTableId(modifiableModel.moduleEntity.persistentId)
internal fun addLibraryCopy(original: LibraryBridgeImpl,
exported: Boolean,
scope: ModuleDependencyItem.DependencyScope): LibraryBridgeImpl {
val tableId = getTableId()
val libraryEntityName = LibraryNameGenerator.generateLibraryEntityName(original.name) { existsName ->
LibraryId(existsName, tableId) in modifiableModel.diff
}
val originalEntity = original.librarySnapshot.libraryEntity
val libraryEntity = modifiableModel.diff.addLibraryEntity(
roots = originalEntity.roots,
tableId = tableId,
name = libraryEntityName,
excludedRoots = originalEntity.excludedRoots,
source = modifiableModel.moduleEntity.entitySource
)
val originalProperties = originalEntity.libraryProperties
if (originalProperties != null) {
modifiableModel.diff.addLibraryPropertiesEntity(
library = libraryEntity,
libraryType = originalProperties.libraryType,
propertiesXmlTag = originalProperties.propertiesXmlTag
)
}
return createAndAddLibrary(libraryEntity, exported, scope)
}
override fun removeLibrary(library: Library) {
modifiableModel.assertModelIsLive()
library as LibraryBridge
val libraryEntity = modifiableModel.diff.findLibraryEntity(library) ?: run {
copyToOriginal.inverse()[library]?.let { libraryCopy -> modifiableModel.diff.findLibraryEntity(libraryCopy) }
}
if (libraryEntity == null) {
LOG.error("Cannot find entity for library ${library.name}")
return
}
val libraryId = libraryEntity.persistentId
modifiableModel.removeDependencies { _, item ->
item is ModuleDependencyItem.Exportable.LibraryDependency && item.library == libraryId
}
modifiableModel.diff.removeEntity(libraryEntity)
Disposer.dispose(library)
}
internal fun restoreLibraryMappingsAndDisposeCopies() {
libraryIterator.forEach {
val originalLibrary = copyToOriginal[it]
//originalLibrary may be null if the library was added after the table was created
if (originalLibrary != null) {
val mutableLibraryMap = modifiableModel.diff.mutableLibraryMap
mutableLibraryMap.addMapping(mutableLibraryMap.getEntities(it as LibraryBridge).single(), originalLibrary)
}
Disposer.dispose(it)
}
}
internal fun restoreMappingsForUnchangedLibraries(changedLibs: Set<LibraryId>) {
if (copyToOriginal.isEmpty()) return
libraryIterator.forEach {
val originalLibrary = copyToOriginal[it]
//originalLibrary may be null if the library was added after the table was created
if (originalLibrary != null && !changedLibs.contains(originalLibrary.libraryId) && originalLibrary.hasSameContent(it)) {
val mutableLibraryMap = modifiableModel.diff.mutableLibraryMap
mutableLibraryMap.addMapping(mutableLibraryMap.getEntities(it as LibraryBridge).single(), originalLibrary)
Disposer.dispose(it)
}
}
}
internal fun disposeOriginalLibrariesAndUpdateCopies() {
if (copyToOriginal.isEmpty()) return
val storage = WorkspaceModel.getInstance(modifiableModel.project).entityStorage
libraryIterator.forEach { copy ->
copy as LibraryBridgeImpl
copy.entityStorage = storage
copy.libraryTable = ModuleRootComponentBridge.getInstance(module).moduleLibraryTable
copy.clearTargetBuilder()
val original = copyToOriginal[copy]
if (original != null) {
Disposer.dispose(original)
}
}
}
override fun isChanged(): Boolean {
return modifiableModel.isChanged
}
override val module: Module
get() = modifiableModel.module
companion object {
private val LOG = logger<ModifiableModuleLibraryTableBridge>()
}
}
|
apache-2.0
|
654605a608f2cb4cda686f52d45325c2
| 44.041667 | 143 | 0.74301 | 5.616628 | false | false | false | false |
spacecowboy/Feeder
|
app/src/main/java/com/nononsenseapps/feeder/util/SystemUtils.kt
|
1
|
2295
|
package com.nononsenseapps.feeder.util
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.os.BatteryManager
import android.os.Build
import java.net.URLEncoder
/**
* Note that cellular typically is metered - it is NOT the same as hotspot
*/
private fun currentlyMetered(context: Context): Boolean {
val connManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
return connManager?.isActiveNetworkMetered ?: false
}
fun currentlyUnmetered(context: Context): Boolean = !currentlyMetered(context)
fun currentlyCharging(context: Context): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val batteryManager = context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager?
batteryManager?.isCharging ?: false
} else {
// Sticky intent
val ifilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
val batteryStatus = context.registerReceiver(null, ifilter)
val status = batteryStatus!!.getIntExtra(BatteryManager.EXTRA_STATUS, -1)
status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL
}
}
fun currentlyConnected(context: Context): Boolean {
val connManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val net = connManager?.activeNetwork
@Suppress("DEPRECATION")
val netInfo = connManager?.getNetworkInfo(net)
@Suppress("DEPRECATION")
return netInfo != null && netInfo.isConnected
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
@Suppress("DEPRECATION")
return connManager?.allNetworks?.map { connManager.getNetworkInfo(it)?.isConnected }
?.fold(false) { result, connected ->
result || (connected ?: false)
} ?: false
}
@Suppress("DEPRECATION")
return connManager?.allNetworkInfo?.map { it?.isConnected }
?.fold(false) { result, connected ->
result || (connected ?: false)
} ?: false
}
fun String.urlEncode(): String =
URLEncoder.encode(this, "UTF-8")
|
gpl-3.0
|
d8f58268bdde24551f5abf4d6b8bf3a1
| 37.898305 | 104 | 0.703704 | 4.517717 | false | false | false | false |
allotria/intellij-community
|
plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/open/GradleOpenProjectProvider.kt
|
3
|
4837
|
// 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 org.jetbrains.plugins.gradle.service.project.open
import com.intellij.ide.impl.isTrusted
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.externalSystem.importing.AbstractOpenProjectProvider
import com.intellij.openapi.externalSystem.importing.ImportSpecBuilder
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.internal.InternalExternalProjectInfo
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.externalSystem.service.execution.ProgressExecutionMode.MODAL_SYNC
import com.intellij.openapi.externalSystem.service.project.ExternalProjectRefreshCallback
import com.intellij.openapi.externalSystem.service.project.ProjectDataManager
import com.intellij.openapi.externalSystem.service.project.manage.ExternalProjectsManagerImpl
import com.intellij.openapi.externalSystem.service.ui.ExternalProjectDataSelectorDialog
import com.intellij.openapi.externalSystem.settings.ExternalProjectSettings
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.externalSystem.util.ExternalSystemUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.plugins.gradle.settings.GradleProjectSettings
import org.jetbrains.plugins.gradle.settings.GradleSettings
import org.jetbrains.plugins.gradle.util.GradleConstants.BUILD_FILE_EXTENSIONS
import org.jetbrains.plugins.gradle.util.GradleConstants.SYSTEM_ID
import org.jetbrains.plugins.gradle.util.setupGradleJvm
import org.jetbrains.plugins.gradle.util.updateGradleJvm
import org.jetbrains.plugins.gradle.util.validateJavaHome
import java.nio.file.Path
internal class GradleOpenProjectProvider : AbstractOpenProjectProvider() {
override val systemId = SYSTEM_ID
override fun isProjectFile(file: VirtualFile): Boolean {
return !file.isDirectory && BUILD_FILE_EXTENSIONS.any { file.name.endsWith(it) }
}
override fun linkAndRefreshProject(projectDirectory: Path, project: Project) {
val gradleProjectSettings = createLinkSettings(projectDirectory, project)
attachGradleProjectAndRefresh(gradleProjectSettings, project)
validateJavaHome(project, projectDirectory, gradleProjectSettings.resolveGradleVersion())
}
private fun attachGradleProjectAndRefresh(settings: ExternalProjectSettings, project: Project) {
val externalProjectPath = settings.externalProjectPath
ExternalSystemApiUtil.getSettings(project, SYSTEM_ID).linkProject(settings)
if (Registry.`is`("external.system.auto.import.disabled")) return
ExternalSystemUtil.refreshProject(
externalProjectPath,
ImportSpecBuilder(project, SYSTEM_ID)
.usePreviewMode()
.use(MODAL_SYNC)
)
ExternalProjectsManagerImpl.getInstance(project).runWhenInitialized {
ExternalSystemUtil.ensureToolWindowInitialized(project, SYSTEM_ID)
ExternalSystemUtil.refreshProject(
externalProjectPath,
ImportSpecBuilder(project, SYSTEM_ID)
.callback(createFinalImportCallback(project, externalProjectPath))
)
}
}
private fun createFinalImportCallback(project: Project, externalProjectPath: String): ExternalProjectRefreshCallback {
return object : ExternalProjectRefreshCallback {
override fun onSuccess(externalProject: DataNode<ProjectData>?) {
if (externalProject == null) return
selectDataToImport(project, externalProjectPath, externalProject)
importData(project, externalProject)
updateGradleJvm(project, externalProjectPath)
}
}
}
private fun selectDataToImport(project: Project, externalProjectPath: String, externalProject: DataNode<ProjectData>) {
val settings = GradleSettings.getInstance(project)
val showSelectiveImportDialog = settings.showSelectiveImportDialogOnInitialImport()
val application = ApplicationManager.getApplication()
if (showSelectiveImportDialog && !application.isHeadlessEnvironment) {
application.invokeAndWait {
val projectInfo = InternalExternalProjectInfo(SYSTEM_ID, externalProjectPath, externalProject)
val dialog = ExternalProjectDataSelectorDialog(project, projectInfo)
if (dialog.hasMultipleDataToSelect()) {
dialog.showAndGet()
}
else {
Disposer.dispose(dialog.disposable)
}
}
}
}
private fun importData(project: Project, externalProject: DataNode<ProjectData>) {
ProjectDataManager.getInstance().importData(externalProject, project, false)
}
}
|
apache-2.0
|
f0ae3f37823038dca9a194ab6911bfc2
| 47.38 | 140 | 0.804011 | 5.173262 | false | false | false | false |
genonbeta/TrebleShot
|
app/src/main/java/org/monora/uprotocol/client/android/viewmodel/TransfersViewModel.kt
|
1
|
4922
|
/*
* Copyright (C) 2021 Veli Tasalı
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.monora.uprotocol.client.android.viewmodel
import android.content.Context
import android.text.format.DateUtils
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import androidx.lifecycle.map
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import org.monora.uprotocol.client.android.data.ClientRepository
import org.monora.uprotocol.client.android.data.SharedTextRepository
import org.monora.uprotocol.client.android.data.TaskRepository
import org.monora.uprotocol.client.android.data.TransferRepository
import org.monora.uprotocol.client.android.data.WebDataRepository
import org.monora.uprotocol.client.android.database.model.SharedText
import org.monora.uprotocol.client.android.database.model.Transfer
import org.monora.uprotocol.client.android.database.model.TransferDetail
import org.monora.uprotocol.client.android.database.model.UClient
import org.monora.uprotocol.client.android.database.model.WebTransfer
import org.monora.uprotocol.client.android.model.DateSectionContentModel
import org.monora.uprotocol.client.android.model.ListItem
import org.monora.uprotocol.client.android.task.transfer.TransferParams
import org.monora.uprotocol.client.android.viewmodel.content.TransferStateContentViewModel
import javax.inject.Inject
@HiltViewModel
class TransfersViewModel @Inject internal constructor(
@ApplicationContext context: Context,
private val clientRepository: ClientRepository,
private val sharedTextRepository: SharedTextRepository,
private val taskRepository: TaskRepository,
private val transferRepository: TransferRepository,
private val webDataRepository: WebDataRepository,
) : ViewModel() {
val transfers = liveData {
val merger = MediatorLiveData<List<ListItem>>()
val texts = sharedTextRepository.getSharedTexts()
val details = transferRepository.getTransferDetails()
val webTransfers = webDataRepository.getReceivedContents()
val observer = Observer<List<ListItem>> {
val mergedList = mutableListOf<ListItem>().apply {
texts.value?.let { addAll(it) }
details.value?.let { addAll(it) }
webTransfers.value?.let { addAll(it) }
sortByDescending {
when (it) {
is TransferDetail -> it.dateCreated
is SharedText -> it.created
is WebTransfer -> it.dateCreated
else -> throw IllegalStateException()
}
}
}
val resultList = mutableListOf<ListItem>()
var previous: DateSectionContentModel? = null
mergedList.forEach {
val date = when (it) {
is TransferDetail -> it.dateCreated
is SharedText -> it.created
is WebTransfer -> it.dateCreated
else -> throw IllegalStateException()
}
val dateText = DateUtils.formatDateTime(context, date, DateUtils.FORMAT_SHOW_DATE)
if (dateText != previous?.dateText) {
resultList.add(DateSectionContentModel(dateText, date).also { model -> previous = model })
}
resultList.add(it)
}
merger.value = resultList
}
merger.addSource(texts, observer)
merger.addSource(details, observer)
merger.addSource(webTransfers, observer)
emitSource(merger)
}
suspend fun getTransfer(groupId: Long): Transfer? = transferRepository.getTransfer(groupId)
suspend fun getClient(clientUid: String): UClient? = clientRepository.getDirect(clientUid)
fun subscribe(transferDetail: TransferDetail) = taskRepository.subscribeToTask {
if (it.params is TransferParams && it.params.transfer.id == transferDetail.id) it.params else null
}.map {
TransferStateContentViewModel.from(it)
}
}
|
gpl-2.0
|
f7384e2ea105d130fd1f85864657a79d
| 42.9375 | 110 | 0.705344 | 4.862648 | false | false | false | false |
Kotlin/kotlinx.coroutines
|
ui/kotlinx-coroutines-android/src/AndroidExceptionPreHandler.kt
|
1
|
2297
|
/*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.android
import android.os.*
import kotlinx.coroutines.*
import java.lang.reflect.*
import kotlin.coroutines.*
internal class AndroidExceptionPreHandler :
AbstractCoroutineContextElement(CoroutineExceptionHandler), CoroutineExceptionHandler
{
@Volatile
private var _preHandler: Any? = this // uninitialized marker
// Reflectively lookup pre-handler.
private fun preHandler(): Method? {
val current = _preHandler
if (current !== this) return current as Method?
val declared = try {
Thread::class.java.getDeclaredMethod("getUncaughtExceptionPreHandler").takeIf {
Modifier.isPublic(it.modifiers) && Modifier.isStatic(it.modifiers)
}
} catch (e: Throwable) {
null /* not found */
}
_preHandler = declared
return declared
}
override fun handleException(context: CoroutineContext, exception: Throwable) {
/*
* Android Oreo introduced private API for a global pre-handler for uncaught exceptions, to ensure that the
* exceptions are logged even if the default uncaught exception handler is replaced by the app. The pre-handler
* is invoked from the Thread's private dispatchUncaughtException() method, so our manual invocation of the
* Thread's uncaught exception handler bypasses the pre-handler in Android Oreo, and uncaught coroutine
* exceptions are not logged. This issue was addressed in Android Pie, which added a check in the default
* uncaught exception handler to invoke the pre-handler if it was not invoked already (see
* https://android-review.googlesource.com/c/platform/frameworks/base/+/654578/). So the issue is present only
* in Android Oreo.
*
* We're fixing this by manually invoking the pre-handler using reflection, if running on an Android Oreo SDK
* version (26 and 27).
*/
if (Build.VERSION.SDK_INT in 26..27) {
(preHandler()?.invoke(null) as? Thread.UncaughtExceptionHandler)
?.uncaughtException(Thread.currentThread(), exception)
}
}
}
|
apache-2.0
|
64223cf554db050db104f653a8c8ba99
| 43.173077 | 119 | 0.679147 | 4.856237 | false | false | false | false |
udevbe/westford
|
compositor/src/main/kotlin/org/westford/nativ/libbcm_host/VC_DISPMANX_ALPHA_T.kt
|
3
|
1147
|
/*
* Westford Wayland Compositor.
* Copyright (C) 2016 Erik De Rijcke
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.westford.nativ.libbcm_host
import org.freedesktop.jaccall.CType
import org.freedesktop.jaccall.Field
import org.freedesktop.jaccall.Struct
@Struct(Field(name = "flags",
type = CType.INT),
Field(name = "opacity",
type = CType.INT),
Field(name = "mask",
type = CType.INT)) class VC_DISPMANX_ALPHA_T : Struct_VC_DISPMANX_ALPHA_T()
|
agpl-3.0
|
9bc4c09a9eadf80566e0106cd17eac27
| 38.551724 | 89 | 0.708806 | 3.968858 | false | false | false | false |
zdary/intellij-community
|
plugins/settings-repository/src/IcsBundle.kt
|
12
|
872
|
// 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.settingsRepository
import com.intellij.DynamicBundle
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.PropertyKey
internal const val BUNDLE = "messages.IcsBundle"
object IcsBundle : DynamicBundle(BUNDLE) {
@Nls
@JvmStatic
fun message(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): String = getMessage(key, *params)
@JvmStatic
fun messagePointer(@PropertyKey(resourceBundle = BUNDLE) key: String,
vararg params: Any): java.util.function.Supplier<String> = getLazyMessage(key, *params)
}
@Nls
fun icsMessage(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): String {
return IcsBundle.message(key, *params)
}
|
apache-2.0
|
b111e0d0fa29997262be54d744f2bd30
| 36.913043 | 140 | 0.761468 | 4.152381 | false | false | false | false |
zdary/intellij-community
|
platform/analysis-impl/src/com/intellij/codeInspection/ex/ApplicationInspectionProfileManagerBase.kt
|
4
|
6018
|
// 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.codeInspection.ex
import com.intellij.configurationStore.BundledSchemeEP
import com.intellij.configurationStore.SchemeDataHolder
import com.intellij.ide.DataManager
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.service
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.options.SchemeManagerFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ProjectManagerListener
import com.intellij.profile.ProfileChangeAdapter
import com.intellij.profile.codeInspection.BaseInspectionProfileManager
import com.intellij.profile.codeInspection.InspectionProfileLoadUtil
import com.intellij.profile.codeInspection.InspectionProfileManager
import com.intellij.profile.codeInspection.InspectionProfileProcessor
import com.intellij.psi.search.scope.packageSet.NamedScopeManager
import com.intellij.psi.search.scope.packageSet.NamedScopesHolder
import com.intellij.serviceContainer.NonInjectable
import org.jdom.JDOMException
import org.jetbrains.annotations.TestOnly
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Paths
import java.util.*
import java.util.function.BiConsumer
import java.util.function.Function
open class ApplicationInspectionProfileManagerBase @TestOnly @NonInjectable constructor(schemeManagerFactory: SchemeManagerFactory) :
BaseInspectionProfileManager(ApplicationManager.getApplication().messageBus) {
init {
val app = ApplicationManager.getApplication()
app.messageBus.connect().subscribe(ProjectManager.TOPIC, object : ProjectManagerListener {
override fun projectOpened(project: Project) {
val appScopeListener = NamedScopesHolder.ScopeListener {
profiles.forEach { it.scopesChanged() }
}
NamedScopeManager.getInstance(project).addScopeListener(appScopeListener, project)
}
})
}
override val schemeManager = schemeManagerFactory.create(InspectionProfileManager.INSPECTION_DIR, object : InspectionProfileProcessor() {
override fun getSchemeKey(attributeProvider: Function<String, String?>, fileNameWithoutExtension: String) = fileNameWithoutExtension
override fun createScheme(dataHolder: SchemeDataHolder<InspectionProfileImpl>,
name: String,
attributeProvider: Function<in String, String?>,
isBundled: Boolean): InspectionProfileImpl {
return InspectionProfileImpl(name,
InspectionToolRegistrar.getInstance(),
this@ApplicationInspectionProfileManagerBase,
dataHolder)
}
override fun onSchemeAdded(scheme: InspectionProfileImpl) {
fireProfileChanged(scheme)
}
override fun onCurrentSchemeSwitched(oldScheme: InspectionProfileImpl?,
newScheme: InspectionProfileImpl?,
processChangeSynchronously: Boolean) {
DataManager.getInstance().dataContextFromFocusAsync.onSuccess {
CommonDataKeys.PROJECT.getData(it)?.messageBus?.syncPublisher(ProfileChangeAdapter.TOPIC)?.profileActivated(oldScheme, newScheme)
}
}
})
protected val profilesAreInitialized by lazy {
val app = ApplicationManager.getApplication()
if (!(app.isUnitTestMode || app.isHeadlessEnvironment)) {
BUNDLED_EP_NAME.processWithPluginDescriptor(BiConsumer { ep, pluginDescriptor ->
schemeManager.loadBundledScheme(ep.path!! + ".xml", null, pluginDescriptor)
})
}
schemeManager.loadSchemes()
if (schemeManager.isEmpty) {
schemeManager.addScheme(InspectionProfileImpl(
DEFAULT_PROFILE_NAME,
InspectionToolRegistrar.getInstance(), this))
}
}
@Volatile
protected var LOAD_PROFILES = !ApplicationManager.getApplication().isUnitTestMode
override fun getProfiles(): Collection<InspectionProfileImpl> {
initProfiles()
return Collections.unmodifiableList(schemeManager.allSchemes)
}
fun initProfiles() {
if (LOAD_PROFILES) {
profilesAreInitialized
}
}
@Throws(JDOMException::class, IOException::class)
open fun loadProfile(path: String): InspectionProfileImpl? {
val file = Paths.get(path)
if (Files.isRegularFile(file)) {
return InspectionProfileLoadUtil.load(file, InspectionToolRegistrar.getInstance(), this)
}
return getProfile(path, false)
}
override fun setRootProfile(profileName: String?) {
schemeManager.setCurrentSchemeName(profileName, true)
}
override fun getProfile(name: String, returnRootProfileIfNamedIsAbsent: Boolean): InspectionProfileImpl? {
val found = schemeManager.findSchemeByName(name)
if (found != null) {
return found
}
// profile was deleted
return if (returnRootProfileIfNamedIsAbsent) currentProfile else null
}
override fun getCurrentProfile(): InspectionProfileImpl {
initProfiles()
val current = schemeManager.activeScheme
if (current != null) {
return current
}
// use default as base, not random custom profile
val result = schemeManager.findSchemeByName(DEFAULT_PROFILE_NAME)
if (result == null) {
val profile = InspectionProfileImpl(DEFAULT_PROFILE_NAME)
addProfile(profile)
return profile
}
return result
}
override fun fireProfileChanged(profile: InspectionProfileImpl) {
}
companion object {
private val BUNDLED_EP_NAME = ExtensionPointName<BundledSchemeEP>("com.intellij.bundledInspectionProfile")
@JvmStatic
fun getInstanceBase() = service<InspectionProfileManager>() as ApplicationInspectionProfileManagerBase
}
}
|
apache-2.0
|
798ecde44f57f8963d3ac2f1215c8798
| 38.077922 | 140 | 0.7446 | 5.46594 | false | false | false | false |
leafclick/intellij-community
|
platform/platform-impl/src/com/intellij/ui/colorpicker/ColorValuePanel.kt
|
1
|
18755
|
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui.colorpicker
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.util.text.StringUtil
import com.intellij.ui.picker.ColorListener
import com.intellij.util.Alarm
import com.intellij.util.ui.JBUI
import org.jetbrains.annotations.TestOnly
import java.awt.*
import java.awt.event.*
import javax.swing.*
import javax.swing.event.DocumentEvent
import javax.swing.event.DocumentListener
import javax.swing.text.AttributeSet
import javax.swing.text.PlainDocument
import kotlin.math.roundToInt
import kotlin.properties.Delegates
private val PANEL_BORDER = JBUI.Borders.empty(0, HORIZONTAL_MARGIN_TO_PICKER_BORDER, 0, HORIZONTAL_MARGIN_TO_PICKER_BORDER)
private val PREFERRED_PANEL_SIZE = JBUI.size(PICKER_PREFERRED_WIDTH, 50)
private const val TEXT_FIELDS_UPDATING_DELAY = 300
private val COLOR_RANGE = 0..255
private val HUE_RANGE = 0..360
private val PERCENT_RANGE = 0..100
enum class AlphaFormat {
BYTE,
PERCENTAGE;
fun next() : AlphaFormat = when (this) {
BYTE -> PERCENTAGE
PERCENTAGE -> BYTE
}
}
enum class ColorFormat {
RGB,
HSB;
fun next() : ColorFormat = when (this) {
RGB -> HSB
HSB -> RGB
}
}
class ColorValuePanel(private val model: ColorPickerModel)
: JPanel(GridBagLayout()), DocumentListener, ColorListener {
/**
* Used to update the color of picker when color text fields are edited.
*/
@get:TestOnly
val updateAlarm = Alarm(Alarm.ThreadToUse.SWING_THREAD)
@get:TestOnly
val alphaField = ColorValueField()
private val alphaHexDocument = DigitColorDocument(alphaField, COLOR_RANGE).apply { addDocumentListener(this@ColorValuePanel) }
private val alphaPercentageDocument = DigitColorDocument(alphaField, PERCENT_RANGE).apply { addDocumentListener(this@ColorValuePanel) }
@get:TestOnly
val hexField = ColorValueField(hex = true)
private val alphaLabel = ColorLabel()
private val colorLabel1 = ColorLabel()
private val colorLabel2 = ColorLabel()
private val colorLabel3 = ColorLabel()
@TestOnly
val alphaButtonPanel = createAlphaLabel(alphaLabel) {
currentAlphaFormat = currentAlphaFormat.next()
}
@TestOnly
val colorFormatButtonPanel = createFormatLabels(colorLabel1, colorLabel2, colorLabel3) {
currentColorFormat = currentColorFormat.next()
}
@get:TestOnly
val colorField1 = ColorValueField()
private val redDocument = DigitColorDocument(colorField1, COLOR_RANGE).apply { addDocumentListener(this@ColorValuePanel) }
private val hueDocument = DigitColorDocument(colorField1, HUE_RANGE).apply { addDocumentListener(this@ColorValuePanel) }
@get:TestOnly
val colorField2 = ColorValueField()
private val greenDocument = DigitColorDocument(colorField2, COLOR_RANGE).apply { addDocumentListener(this@ColorValuePanel) }
private val saturationDocument = DigitColorDocument(colorField2, PERCENT_RANGE).apply { addDocumentListener(this@ColorValuePanel) }
@get:TestOnly
val colorField3 = ColorValueField()
private val blueDocument = DigitColorDocument(colorField3, COLOR_RANGE).apply { addDocumentListener(this@ColorValuePanel) }
private val brightnessDocument = DigitColorDocument(colorField3, PERCENT_RANGE).apply { addDocumentListener(this@ColorValuePanel) }
var currentAlphaFormat by Delegates.observable(loadAlphaFormatProperty()) { _, _, newValue ->
updateAlphaFormat()
saveAlphaFormatProperty(newValue)
repaint()
}
var currentColorFormat by Delegates.observable(loadColorFormatProperty()) { _, _, newValue ->
updateColorFormat()
saveColorFormatProperty(newValue)
repaint()
}
init {
border = PANEL_BORDER
preferredSize = PREFERRED_PANEL_SIZE
background = PICKER_BACKGROUND_COLOR
isFocusable = false
val c = GridBagConstraints()
c.fill = GridBagConstraints.HORIZONTAL
c.weightx = 0.12
c.gridx = 0
c.gridy = 0
add(alphaButtonPanel, c)
c.gridy = 1
add(alphaField, c)
c.weightx = 0.36
c.gridwidth = 3
c.gridx = 1
c.gridy = 0
add(colorFormatButtonPanel, c)
c.gridwidth = 1
c.weightx = 0.12
c.gridx = 1
c.gridy = 1
add(colorField1, c)
c.gridx = 2
c.gridy = 1
add(colorField2, c)
c.gridx = 3
c.gridy = 1
add(colorField3, c)
// Hex should be longer
c.gridheight = 1
c.weightx = 0.51
c.gridx = 4
c.gridy = 0
add(ColorLabel("Hex"), c)
c.gridy = 1
add(hexField, c)
hexField.document = HexColorDocument(hexField)
hexField.document.addDocumentListener(this)
updateAlphaFormat()
updateColorFormat()
model.addListener(this)
}
override fun requestFocusInWindow() = alphaField.requestFocusInWindow()
private fun updateAlphaFormat() {
when (currentAlphaFormat) {
AlphaFormat.BYTE -> {
alphaLabel.text = "A"
alphaField.document = alphaHexDocument
alphaField.text = model.alpha.toString()
}
AlphaFormat.PERCENTAGE -> {
alphaLabel.text = "A%"
alphaField.document = alphaPercentageDocument
alphaField.text = (model.alpha * 100f / 0xFF).roundToInt().toString()
}
}
// change the text in document trigger the listener, but it doesn't to update the color in Model in this case.
updateAlarm.cancelAllRequests()
repaint()
}
private fun updateColorFormat() {
when (currentColorFormat) {
ColorFormat.RGB -> {
colorLabel1.text = "R"
colorLabel2.text = "G"
colorLabel3.text = "B"
colorField1.document = redDocument
colorField2.document = greenDocument
colorField3.document = blueDocument
colorField1.text = model.red.toString()
colorField2.text = model.green.toString()
colorField3.text = model.blue.toString()
}
ColorFormat.HSB -> {
colorLabel1.text = "H°"
colorLabel2.text = "S%"
colorLabel3.text = "B%"
colorField1.document = hueDocument
colorField2.document = saturationDocument
colorField3.document = brightnessDocument
colorField1.text = (model.hue * 360).roundToInt().toString()
colorField2.text = (model.saturation * 100).roundToInt().toString()
colorField3.text = (model.brightness * 100).roundToInt().toString()
}
}
// change the text in document trigger the listener, but it doesn't to update the color in Model in this case.
updateAlarm.cancelAllRequests()
repaint()
}
override fun colorChanged(color: Color, source: Any?) = updateTextField(color, source)
private fun updateTextField(color: Color, source: Any?) {
if (currentAlphaFormat == AlphaFormat.BYTE) {
alphaField.setTextIfNeeded(color.alpha.toString(), source)
}
else {
alphaField.setTextIfNeeded((color.alpha * 100f / 0xFF).roundToInt().toString(), source)
}
if (currentColorFormat == ColorFormat.RGB) {
colorField1.setTextIfNeeded(color.red.toString(), source)
colorField2.setTextIfNeeded(color.green.toString(), source)
colorField3.setTextIfNeeded(color.blue.toString(), source)
}
else {
val hsb = Color.RGBtoHSB(color.red, color.green, color.blue, null)
colorField1.setTextIfNeeded((hsb[0] * 360).roundToInt().toString(), source)
colorField2.setTextIfNeeded((hsb[1] * 100).roundToInt().toString(), source)
colorField3.setTextIfNeeded((hsb[2] * 100).roundToInt().toString(), source)
}
hexField.setTextIfNeeded(String.format("%08X", color.rgb), source)
// Cleanup the update requests which triggered by setting text in this function
updateAlarm.cancelAllRequests()
}
private fun JTextField.setTextIfNeeded(newText: String?, source: Any?) {
if (text != newText && (source != this@ColorValuePanel || !isFocusOwner)) {
text = newText
}
}
override fun insertUpdate(e: DocumentEvent) = update((e.document as ColorDocument).src)
override fun removeUpdate(e: DocumentEvent) = update((e.document as ColorDocument).src)
override fun changedUpdate(e: DocumentEvent) = Unit
private fun update(src: JTextField) {
updateAlarm.cancelAllRequests()
updateAlarm.addRequest({ updateColorToColorModel(src) }, TEXT_FIELDS_UPDATING_DELAY)
}
private fun updateColorToColorModel(src: JTextField?) {
val color = if (src == hexField) {
convertHexToColor(hexField.text)
}
else {
val a = if (currentAlphaFormat == AlphaFormat.BYTE) alphaField.colorValue else (alphaField.colorValue * 0xFF / 100f).roundToInt()
when (currentColorFormat) {
ColorFormat.RGB -> {
val r = colorField1.colorValue
val g = colorField2.colorValue
val b = colorField3.colorValue
Color(r, g, b, a)
}
ColorFormat.HSB -> {
val h = colorField1.colorValue / 360f
val s = colorField2.colorValue / 100f
val b = colorField3.colorValue / 100f
Color((a shl 24) or (0x00FFFFFF and Color.HSBtoRGB(h, s, b)), true)
}
}
}
model.setColor(color, this)
}
companion object {
private fun createAlphaLabel(alphaLabel: ColorLabel, onClick: () -> Unit) = object : ButtonPanel() {
init {
layout = GridLayout(1, 1)
add(alphaLabel)
}
override fun clicked() {
onClick.invoke()
}
}
private fun createFormatLabels(label1: ColorLabel,
label2: ColorLabel,
label3: ColorLabel,
onClick: () -> Unit) = object : ButtonPanel() {
init {
layout = GridLayout(1, 3)
add(label1)
add(label2)
add(label3)
}
override fun clicked() {
onClick.invoke()
}
}
}
}
private const val HOVER_BORDER_LEFT = 0
private const val HOVER_BORDER_TOP = 0
private const val HOVER_BORDER_WIDTH = 1
private val HOVER_BORDER_STROKE = BasicStroke(1f)
private val HOVER_BORDER_COLOR = Color.GRAY.brighter()
private const val PRESSED_BORDER_LEFT = 1
private const val PRESSED_BORDER_TOP = 1
private const val PRESSED_BORDER_WIDTH = 2
private val PRESSED_BORDER_STROKE = BasicStroke(1.2f)
private val PRESSED_BORDER_COLOR = Color.GRAY
private const val BORDER_CORNER_ARC = 7
private const val ACTION_PRESS_BUTTON_PANEL = "pressButtonPanel"
private const val ACTION_RELEASE_BUTTON_PANEL = "releaseButtonPanel"
abstract class ButtonPanel : JPanel() {
companion object {
private enum class Status { NORMAL, HOVER, PRESSED }
}
private var mouseStatus by Delegates.observable(Status.NORMAL) { _, _, _ ->
repaint()
}
private val mouseAdapter = object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent?) = clicked()
override fun mouseEntered(e: MouseEvent?) {
if (!isFocusOwner) {
mouseStatus = Status.HOVER
}
}
override fun mouseExited(e: MouseEvent?) {
if (!isFocusOwner) {
mouseStatus = Status.NORMAL
}
}
override fun mousePressed(e: MouseEvent?) {
if (!isFocusOwner) {
mouseStatus = Status.PRESSED
}
}
override fun mouseReleased(e: MouseEvent?) {
if (!isFocusOwner) {
mouseStatus = if (mouseStatus == Status.PRESSED) Status.HOVER else Status.NORMAL
}
}
}
private val focusAdapter = object : FocusAdapter() {
override fun focusGained(e: FocusEvent?) {
mouseStatus = Status.HOVER
}
override fun focusLost(e: FocusEvent?) {
mouseStatus = Status.NORMAL
}
}
init {
border = BorderFactory.createEmptyBorder()
background = PICKER_BACKGROUND_COLOR
addMouseListener(mouseAdapter)
addFocusListener(focusAdapter)
with (getInputMap(JComponent.WHEN_FOCUSED)) {
put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false), ACTION_PRESS_BUTTON_PANEL)
put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true), ACTION_RELEASE_BUTTON_PANEL)
}
with (actionMap) {
put(ACTION_PRESS_BUTTON_PANEL, object : AbstractAction() {
override fun actionPerformed(e: ActionEvent) {
mouseStatus = Status.PRESSED
}
})
put(ACTION_RELEASE_BUTTON_PANEL, object : AbstractAction() {
override fun actionPerformed(e: ActionEvent) {
mouseStatus = Status.HOVER
clicked()
}
})
}
}
// Needs to be final to be used in init block
final override fun addMouseListener(l: MouseListener?) = super.addMouseListener(l)
// Needs to be final to be used in init block
final override fun addFocusListener(l: FocusListener?) = super.addFocusListener(l)
override fun isFocusable() = true
abstract fun clicked()
override fun paintBorder(g: Graphics) {
g as? Graphics2D ?: return
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
val originalStroke = g.stroke
when (mouseStatus) {
Status.HOVER -> {
g.stroke = HOVER_BORDER_STROKE
g.color = HOVER_BORDER_COLOR
g.drawRoundRect(HOVER_BORDER_LEFT,HOVER_BORDER_TOP,
width - HOVER_BORDER_WIDTH, height - HOVER_BORDER_WIDTH,
BORDER_CORNER_ARC, BORDER_CORNER_ARC)
}
Status.PRESSED -> {
g.stroke = PRESSED_BORDER_STROKE
g.color = PRESSED_BORDER_COLOR
g.drawRoundRect(PRESSED_BORDER_LEFT, PRESSED_BORDER_TOP,
width - PRESSED_BORDER_WIDTH, height - PRESSED_BORDER_WIDTH,
BORDER_CORNER_ARC, BORDER_CORNER_ARC)
}
else -> return
}
g.stroke = originalStroke
}
}
private class ColorLabel(text: String = ""): JLabel(text, SwingConstants.CENTER) {
init {
foreground = PICKER_TEXT_COLOR
}
}
private const val ACTION_UP = "up"
private const val ACTION_DOWN = "down"
class ColorValueField(private val hex: Boolean = false): JTextField(if (hex) 8 else 3) {
init {
horizontalAlignment = JTextField.CENTER
isEnabled = true
isEditable = true
addFocusListener(object : FocusAdapter() {
override fun focusGained(e: FocusEvent?) {
selectAll()
}
override fun focusLost(e: FocusEvent?) {
val size = document?.length ?: return
selectionStart = size
selectionEnd = size
}
})
if (!hex) {
// Don't increase value for hex field.
with(getInputMap(JComponent.WHEN_FOCUSED)) {
put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), ACTION_UP)
put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), ACTION_DOWN)
}
with(actionMap) {
put(ACTION_UP, object : AbstractAction() {
override fun actionPerformed(e: ActionEvent) = increaseValue(1)
})
put(ACTION_DOWN, object : AbstractAction() {
override fun actionPerformed(e: ActionEvent) = increaseValue(-1)
})
}
}
}
private fun increaseValue(diff: Int) {
assert(!hex)
val doc = document as DigitColorDocument
val newValue = doc.getText(0, doc.length).toInt() + diff
val valueInRange = Math.max(doc.valueRange.start, Math.min(newValue, doc.valueRange.endInclusive))
text = valueInRange.toString()
}
override fun isFocusable() = true
val colorValue: Int
get() {
val rawText = text
return if (rawText.isBlank()) 0 else Integer.parseInt(rawText, if (hex) 16 else 10)
}
}
private abstract class ColorDocument(internal val src: JTextField) : PlainDocument() {
override fun insertString(offs: Int, str: String, a: AttributeSet?) {
val source = str.toCharArray()
val selected = src.selectionEnd - src.selectionStart
val newLen = src.text.length - selected + str.length
if (newLen > src.columns) {
return
}
val charsToInsert = source
.filter { isLegalCharacter(it) }
.map { it.toUpperCase() }
.joinToString("")
val res = StringBuilder(src.text).insert(offs, charsToInsert).toString()
if (!isLegalValue(res)) {
return
}
super.insertString(offs, charsToInsert, a)
}
abstract fun isLegalCharacter(c: Char): Boolean
abstract fun isLegalValue(str: String): Boolean
}
private class DigitColorDocument(src: JTextField, val valueRange: IntRange) : ColorDocument(src) {
override fun isLegalCharacter(c: Char) = c.isDigit()
override fun isLegalValue(str: String) = try { str.toInt() in valueRange } catch (_: NumberFormatException) { false }
}
private class HexColorDocument(src: JTextField) : ColorDocument(src) {
override fun isLegalCharacter(c: Char) = StringUtil.isHexDigit(c)
override fun isLegalValue(str: String) = true
}
private fun convertHexToColor(hex: String): Color {
val s = if (hex == "") "0" else hex
val i = s.toLong(16)
val a = if (hex.length > 6) i shr 24 and 0xFF else 0xFF
val r = i shr 16 and 0xFF
val g = i shr 8 and 0xFF
val b = i and 0xFF
return Color(r.toInt(), g.toInt(), b.toInt(), a.toInt())
}
private const val PROPERTY_PREFIX = "colorValuePanel_"
private const val PROPERTY_NAME_ALPHA_FORMAT = PROPERTY_PREFIX + "alphaFormat"
private val DEFAULT_ALPHA_FORMAT = AlphaFormat.PERCENTAGE
private const val PROPERTY_NAME_COLOR_FORMAT = PROPERTY_PREFIX + "colorFormat"
private val DEFAULT_COLOR_FORMAT = ColorFormat.RGB
private fun loadAlphaFormatProperty(): AlphaFormat {
val alphaFormatName = PropertiesComponent.getInstance().getValue(PROPERTY_NAME_ALPHA_FORMAT, DEFAULT_ALPHA_FORMAT.name)
return try {
AlphaFormat.valueOf(alphaFormatName)
}
catch (e: IllegalArgumentException) {
DEFAULT_ALPHA_FORMAT
}
}
private fun saveAlphaFormatProperty(alphaFormat: AlphaFormat) {
PropertiesComponent.getInstance().setValue(PROPERTY_NAME_ALPHA_FORMAT, alphaFormat.name)
}
private fun loadColorFormatProperty(): ColorFormat {
val colorFormatName = PropertiesComponent.getInstance().getValue(PROPERTY_NAME_COLOR_FORMAT, DEFAULT_COLOR_FORMAT.name)
return try {
ColorFormat.valueOf(colorFormatName)
}
catch (e: IllegalArgumentException) {
DEFAULT_COLOR_FORMAT
}
}
private fun saveColorFormatProperty(colorFormat: ColorFormat) {
PropertiesComponent.getInstance().setValue(PROPERTY_NAME_COLOR_FORMAT, colorFormat.name)
}
|
apache-2.0
|
be6d351f940b8fb069fcedd6e4310d3f
| 30.308848 | 137 | 0.683374 | 4.068113 | false | false | false | false |
alibaba/transmittable-thread-local
|
ttl2-compatible/src/test/java/com/alibaba/demo/forkjoinpool/ForkJoinPoolDemo.kt
|
2
|
12934
|
package com.alibaba.demo.forkjoinpool
import java.util.concurrent.ForkJoinPool
import java.util.concurrent.RecursiveTask
/**
* ForkJoinPool use demo.
*
* @author Jerry Lee (oldratlee at gmail dot com)
*/
fun main() {
val pool = ForkJoinPool.commonPool()
val result = pool.invoke(SumTask(1..1000))
println("computed result: $result") // result is 500500
}
internal class SumTask(private val numbers: IntRange, private val forkLevel: Int = 0) : RecursiveTask<Int>() {
override fun compute(): Int =
if (numbers.count() <= 16) {
println(String.format("direct compute %9s[%4s] at fork level %2s @ thread ${Thread.currentThread().name}",
numbers, numbers.count(), forkLevel))
// compute directly
numbers.sum()
} else {
println(String.format("fork compute %9s[%4s] at fork level %2s @ thread ${Thread.currentThread().name}",
numbers, numbers.count(), forkLevel))
// split task
val middle = numbers.first + numbers.count() / 2
val nextForkLevel = forkLevel + 1
val taskLeft = SumTask(numbers.first until middle, nextForkLevel)
val taskRight = SumTask(middle..numbers.last, nextForkLevel)
// fork-join compute
taskLeft.fork()
taskRight.fork()
taskLeft.join() + taskRight.join()
}
}
/*
Output:
fork compute 1..1000[1000] at fork level 0 @ thread main
fork compute 1..500[ 500] at fork level 1 @ thread ForkJoinPool.commonPool-worker-19
fork compute 501..1000[ 500] at fork level 1 @ thread ForkJoinPool.commonPool-worker-5
fork compute 501..750[ 250] at fork level 2 @ thread ForkJoinPool.commonPool-worker-23
fork compute 751..1000[ 250] at fork level 2 @ thread ForkJoinPool.commonPool-worker-13
fork compute 251..500[ 250] at fork level 2 @ thread ForkJoinPool.commonPool-worker-27
fork compute 501..625[ 125] at fork level 3 @ thread ForkJoinPool.commonPool-worker-17
fork compute 1..250[ 250] at fork level 2 @ thread ForkJoinPool.commonPool-worker-9
fork compute 751..875[ 125] at fork level 3 @ thread ForkJoinPool.commonPool-worker-13
fork compute 876..1000[ 125] at fork level 3 @ thread ForkJoinPool.commonPool-worker-3
fork compute 251..375[ 125] at fork level 3 @ thread ForkJoinPool.commonPool-worker-27
fork compute 376..500[ 125] at fork level 3 @ thread ForkJoinPool.commonPool-worker-7
fork compute 751..812[ 62] at fork level 4 @ thread ForkJoinPool.commonPool-worker-13
fork compute 1..125[ 125] at fork level 3 @ thread ForkJoinPool.commonPool-worker-9
fork compute 376..437[ 62] at fork level 4 @ thread ForkJoinPool.commonPool-worker-7
fork compute 876..937[ 62] at fork level 4 @ thread ForkJoinPool.commonPool-worker-3
fork compute 626..750[ 125] at fork level 3 @ thread ForkJoinPool.commonPool-worker-31
fork compute 376..406[ 31] at fork level 5 @ thread ForkJoinPool.commonPool-worker-7
fork compute 1..62[ 62] at fork level 4 @ thread ForkJoinPool.commonPool-worker-9
fork compute 751..781[ 31] at fork level 5 @ thread ForkJoinPool.commonPool-worker-13
fork compute 501..562[ 62] at fork level 4 @ thread ForkJoinPool.commonPool-worker-17
fork compute 251..312[ 62] at fork level 4 @ thread ForkJoinPool.commonPool-worker-27
fork compute 626..687[ 62] at fork level 4 @ thread ForkJoinPool.commonPool-worker-31
direct compute 751..765[ 15] at fork level 6 @ thread ForkJoinPool.commonPool-worker-13
fork compute 876..906[ 31] at fork level 5 @ thread ForkJoinPool.commonPool-worker-3
fork compute 563..625[ 63] at fork level 4 @ thread ForkJoinPool.commonPool-worker-21
fork compute 501..531[ 31] at fork level 5 @ thread ForkJoinPool.commonPool-worker-17
fork compute 1..31[ 31] at fork level 5 @ thread ForkJoinPool.commonPool-worker-9
direct compute 876..890[ 15] at fork level 6 @ thread ForkJoinPool.commonPool-worker-3
direct compute 376..390[ 15] at fork level 6 @ thread ForkJoinPool.commonPool-worker-7
fork compute 563..593[ 31] at fork level 5 @ thread ForkJoinPool.commonPool-worker-21
direct compute 1..15[ 15] at fork level 6 @ thread ForkJoinPool.commonPool-worker-9
direct compute 766..781[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-13
fork compute 626..656[ 31] at fork level 5 @ thread ForkJoinPool.commonPool-worker-31
direct compute 391..406[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-7
fork compute 251..281[ 31] at fork level 5 @ thread ForkJoinPool.commonPool-worker-27
direct compute 16..31[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-9
direct compute 563..577[ 15] at fork level 6 @ thread ForkJoinPool.commonPool-worker-21
direct compute 891..906[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-3
fork compute 407..437[ 31] at fork level 5 @ thread ForkJoinPool.commonPool-worker-7
fork compute 32..62[ 31] at fork level 5 @ thread ForkJoinPool.commonPool-worker-9
direct compute 578..593[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-21
direct compute 501..515[ 15] at fork level 6 @ thread ForkJoinPool.commonPool-worker-17
direct compute 407..421[ 15] at fork level 6 @ thread ForkJoinPool.commonPool-worker-7
fork compute 907..937[ 31] at fork level 5 @ thread ForkJoinPool.commonPool-worker-3
direct compute 251..265[ 15] at fork level 6 @ thread ForkJoinPool.commonPool-worker-27
direct compute 626..640[ 15] at fork level 6 @ thread ForkJoinPool.commonPool-worker-31
fork compute 782..812[ 31] at fork level 5 @ thread ForkJoinPool.commonPool-worker-13
direct compute 907..921[ 15] at fork level 6 @ thread ForkJoinPool.commonPool-worker-3
direct compute 266..281[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-27
direct compute 516..531[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-17
direct compute 422..437[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-7
fork compute 594..625[ 32] at fork level 5 @ thread ForkJoinPool.commonPool-worker-21
direct compute 922..937[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-3
direct compute 32..46[ 15] at fork level 6 @ thread ForkJoinPool.commonPool-worker-9
fork compute 532..562[ 31] at fork level 5 @ thread ForkJoinPool.commonPool-worker-17
fork compute 282..312[ 31] at fork level 5 @ thread ForkJoinPool.commonPool-worker-27
direct compute 782..796[ 15] at fork level 6 @ thread ForkJoinPool.commonPool-worker-13
direct compute 47..62[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-9
direct compute 641..656[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-31
direct compute 797..812[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-13
fork compute 63..125[ 63] at fork level 4 @ thread ForkJoinPool.commonPool-worker-9
direct compute 282..296[ 15] at fork level 6 @ thread ForkJoinPool.commonPool-worker-27
direct compute 532..546[ 15] at fork level 6 @ thread ForkJoinPool.commonPool-worker-17
fork compute 938..1000[ 63] at fork level 4 @ thread ForkJoinPool.commonPool-worker-3
fork compute 63..93[ 31] at fork level 5 @ thread ForkJoinPool.commonPool-worker-9
direct compute 594..609[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-21
fork compute 438..500[ 63] at fork level 4 @ thread ForkJoinPool.commonPool-worker-7
direct compute 547..562[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-17
direct compute 297..312[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-27
fork compute 813..875[ 63] at fork level 4 @ thread ForkJoinPool.commonPool-worker-13
fork compute 657..687[ 31] at fork level 5 @ thread ForkJoinPool.commonPool-worker-31
fork compute 438..468[ 31] at fork level 5 @ thread ForkJoinPool.commonPool-worker-7
fork compute 313..375[ 63] at fork level 4 @ thread ForkJoinPool.commonPool-worker-27
direct compute 610..625[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-21
direct compute 63..77[ 15] at fork level 6 @ thread ForkJoinPool.commonPool-worker-9
direct compute 438..452[ 15] at fork level 6 @ thread ForkJoinPool.commonPool-worker-7
fork compute 938..968[ 31] at fork level 5 @ thread ForkJoinPool.commonPool-worker-3
fork compute 344..375[ 32] at fork level 5 @ thread ForkJoinPool.commonPool-worker-21
direct compute 78..93[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-9
fork compute 688..750[ 63] at fork level 4 @ thread ForkJoinPool.commonPool-worker-17
fork compute 94..125[ 32] at fork level 5 @ thread ForkJoinPool.commonPool-worker-9
direct compute 938..952[ 15] at fork level 6 @ thread ForkJoinPool.commonPool-worker-3
fork compute 688..718[ 31] at fork level 5 @ thread ForkJoinPool.commonPool-worker-17
direct compute 94..109[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-9
fork compute 313..343[ 31] at fork level 5 @ thread ForkJoinPool.commonPool-worker-27
direct compute 657..671[ 15] at fork level 6 @ thread ForkJoinPool.commonPool-worker-31
fork compute 813..843[ 31] at fork level 5 @ thread ForkJoinPool.commonPool-worker-13
direct compute 110..125[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-9
direct compute 672..687[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-23
fork compute 719..750[ 32] at fork level 5 @ thread ForkJoinPool.commonPool-worker-31
direct compute 813..827[ 15] at fork level 6 @ thread ForkJoinPool.commonPool-worker-13
direct compute 688..702[ 15] at fork level 6 @ thread ForkJoinPool.commonPool-worker-17
direct compute 953..968[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-3
direct compute 453..468[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-7
direct compute 344..359[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-21
direct compute 703..718[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-17
direct compute 828..843[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-13
direct compute 719..734[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-31
fork compute 126..250[ 125] at fork level 3 @ thread ForkJoinPool.commonPool-worker-9
direct compute 313..327[ 15] at fork level 6 @ thread ForkJoinPool.commonPool-worker-27
fork compute 844..875[ 32] at fork level 5 @ thread ForkJoinPool.commonPool-worker-13
direct compute 735..750[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-17
direct compute 360..375[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-21
fork compute 469..500[ 32] at fork level 5 @ thread ForkJoinPool.commonPool-worker-7
fork compute 969..1000[ 32] at fork level 5 @ thread ForkJoinPool.commonPool-worker-3
direct compute 860..875[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-31
fork compute 188..250[ 63] at fork level 4 @ thread ForkJoinPool.commonPool-worker-17
direct compute 485..500[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-23
direct compute 969..984[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-3
direct compute 844..859[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-13
fork compute 126..187[ 62] at fork level 4 @ thread ForkJoinPool.commonPool-worker-9
direct compute 328..343[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-27
fork compute 219..250[ 32] at fork level 5 @ thread ForkJoinPool.commonPool-worker-23
fork compute 188..218[ 31] at fork level 5 @ thread ForkJoinPool.commonPool-worker-17
fork compute 126..156[ 31] at fork level 5 @ thread ForkJoinPool.commonPool-worker-9
direct compute 985..1000[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-31
direct compute 469..484[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-21
direct compute 188..202[ 15] at fork level 6 @ thread ForkJoinPool.commonPool-worker-17
direct compute 219..234[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-23
direct compute 203..218[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-3
fork compute 157..187[ 31] at fork level 5 @ thread ForkJoinPool.commonPool-worker-31
direct compute 126..140[ 15] at fork level 6 @ thread ForkJoinPool.commonPool-worker-9
direct compute 141..156[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-13
direct compute 235..250[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-5
direct compute 172..187[ 16] at fork level 6 @ thread ForkJoinPool.commonPool-worker-3
direct compute 157..171[ 15] at fork level 6 @ thread ForkJoinPool.commonPool-worker-31
computed result: 500500
*/
|
apache-2.0
|
47c4f1d764ad7f1f0ce7608291714112
| 72.488636 | 118 | 0.729937 | 3.485314 | false | false | false | false |
JuliusKunze/kotlin-native
|
backend.native/tests/external/codegen/box/localClasses/innerClassInLocalClass.kt
|
5
|
337
|
class A {
val a = 1
fun calc () : Int {
class B() {
val b = 2
inner class C {
val c = 3
fun calc() = [email protected] + [email protected] + this.c
}
}
return B().C().calc()
}
}
fun box() : String {
return if (A().calc() == 6) "OK" else "fail"
}
|
apache-2.0
|
6fbe0bde49c662f14c903d0597705f5c
| 18.882353 | 57 | 0.356083 | 3.37 | false | false | false | false |
AndroidX/androidx
|
compose/material/material/integration-tests/material-catalog/src/main/java/androidx/compose/material/catalog/library/ui/common/Border.kt
|
3
|
2424
|
/*
* 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.material.catalog.library.ui.common
import androidx.compose.material.LocalContentColor
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.compositeOver
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
/**
* Draws a stroke border on the inner edges of grid items i.e. bottom as well as end (if not the
* last item in a row).
*
* @param itemIndex The zero-based index of the grid item.
* @param cellsCount The number of cells (columns for vertical, rows for horizontal) in the grid.
* @param color The color of the border.
* @param width The width of the border.
*/
fun Modifier.gridItemBorder(
itemIndex: Int,
cellsCount: Int,
color: Color,
width: Dp = BorderWidth
) = drawBehind {
val end = itemIndex.inc().rem(cellsCount) == 0
drawLine(
color = color,
strokeWidth = width.toPx(),
cap = StrokeCap.Square,
start = Offset(0f, size.height),
end = Offset(size.width, size.height)
)
if (!end) drawLine(
color = color,
strokeWidth = width.toPx(),
cap = StrokeCap.Square,
start = Offset(size.width, size.height),
end = Offset(size.width, 0f)
)
}
/**
* Composite of local content color at 12% alpha over background color, used by borders.
*/
@Composable
fun compositeBorderColor(): Color = LocalContentColor.current.copy(alpha = BorderAlpha)
.compositeOver(MaterialTheme.colors.background)
val BorderWidth = 1.dp
private const val BorderAlpha = 0.12f
|
apache-2.0
|
999a1bea9722786b5f319a2dbacbbd5b
| 33.140845 | 97 | 0.724835 | 3.99341 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/rest/PackageSearchRestService.kt
|
1
|
5460
|
package com.jetbrains.packagesearch.intellij.plugin.rest
import com.google.gson.GsonBuilder
import com.intellij.ide.impl.ProjectUtil
import com.intellij.notification.NotificationType
import com.intellij.notification.impl.NotificationGroupManagerImpl
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream
import com.intellij.util.io.origin
import com.intellij.util.net.NetUtils
import com.intellij.util.text.nullize
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.PluginEnvironment
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.PackageSearchToolWindowFactory
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.http.FullHttpRequest
import io.netty.handler.codec.http.HttpMethod
import io.netty.handler.codec.http.HttpRequest
import io.netty.handler.codec.http.HttpResponseStatus
import io.netty.handler.codec.http.HttpUtil
import io.netty.handler.codec.http.QueryStringDecoder
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import org.jetbrains.ide.RestService
import java.net.URI
import java.net.URISyntaxException
internal class PackageSearchRestService : RestService() {
override fun getServiceName() = "packageSearch"
override fun isMethodSupported(method: HttpMethod) = method === HttpMethod.GET || method === HttpMethod.POST
override fun execute(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext): String? {
when (getStringParameter("action", urlDecoder)) {
"projects" -> listProjects(request, context)
"install" -> installPackage(request, context)
else -> sendStatus(HttpResponseStatus.NOT_FOUND, HttpUtil.isKeepAlive(request), context.channel())
}
return null
}
private fun listProjects(request: FullHttpRequest, context: ChannelHandlerContext) {
val out = BufferExposingByteArrayOutputStream()
val name = ApplicationNamesInfo.getInstance().productName
val build = ApplicationInfo.getInstance().build
createJsonWriter(out).apply {
beginObject()
name("name").value(name)
name("buildNumber").value(build.asString())
name("projects")
beginArray()
ProjectManager.getInstance().openProjects.forEach { value(it.name) }
endArray()
endObject()
close()
}
send(out, request, context)
}
private fun installPackage(
request: FullHttpRequest,
context: ChannelHandlerContext
) {
val gson = GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create()
val data = gson.fromJson<InstallPackageRequest>(createJsonReader(request), InstallPackageRequest::class.java)
val project = ProjectManager.getInstance().openProjects.find { it.name.equals(data.project, ignoreCase = true) }
val pkg = data.`package`
val query = data.query.nullize(true)
if (project == null || pkg == null) {
sendStatus(HttpResponseStatus.BAD_REQUEST, HttpUtil.isKeepAlive(request), context.channel())
return
}
AppUIExecutor.onUiThread().execute {
ProjectUtil.focusProjectWindow(project, true)
PackageSearchToolWindowFactory.activateToolWindow(project) {
// project.packageSearchDataService.programmaticSearchQueryStateFlow.tryEmit(query ?: pkg.replace(':', ' '))
// rootModel.setSelectedPackage(pkg) // TODO preselect proper package
notify(project, pkg)
}
}
sendOk(request, context)
}
override fun isAccessible(request: HttpRequest) = true
override fun isHostTrusted(request: FullHttpRequest, urlDecoder: QueryStringDecoder): Boolean {
val origin = request.origin
val originHost = try {
if (origin == null) null else URI(origin).host.nullize()
} catch (ignored: URISyntaxException) {
return false
}
val isTrusted = originHost?.let {
it == "package-search.jetbrains.com" ||
it.endsWith("package-search.services.jetbrains.com") ||
NetUtils.isLocalhost(it)
} ?: false
return isTrusted || super.isHostTrusted(request, urlDecoder)
}
@Suppress("DialogTitleCapitalization") // It's the Package Search plugin name...
private fun notify(project: Project, @Nls pkg: String) =
NotificationGroupManagerImpl()
.getNotificationGroup(PluginEnvironment.PACKAGE_SEARCH_NOTIFICATION_GROUP_ID)
.createNotification(
PackageSearchBundle.message("packagesearch.title"),
PackageSearchBundle.message("packagesearch.restService.readyForInstallation"),
NotificationType.INFORMATION
)
.setSubtitle(pkg)
.notify(project)
}
internal class InstallPackageRequest {
var project: String? = null
@NlsSafe var `package`: String? = null
@NonNls var query: String? = null
}
|
apache-2.0
|
c179e9c5380f483a4d6ecd0e503904ea
| 39.147059 | 125 | 0.705495 | 5.022999 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/references/GrConstructorInvocationReference.kt
|
13
|
1566
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve.references
import com.intellij.psi.PsiSubstitutor
import com.intellij.psi.ResolveState
import com.intellij.psi.util.TypeConversionUtil.getSuperClassSubstitutor
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrConstructorInvocation
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil
import org.jetbrains.plugins.groovy.lang.resolve.BaseGroovyResolveResult
import org.jetbrains.plugins.groovy.lang.resolve.api.Arguments
import org.jetbrains.plugins.groovy.lang.resolve.impl.getArguments
class GrConstructorInvocationReference(element: GrConstructorInvocation) : GrConstructorReference<GrConstructorInvocation>(element) {
override fun doResolveClass(): GroovyResolveResult? {
val invocation = element
val clazz = invocation.delegatedClass ?: return null
val state = if (invocation.isThisCall) {
ResolveState.initial()
}
else {
val enclosing = PsiUtil.getContextClass(invocation) ?: return null
val substitutor = getSuperClassSubstitutor(clazz, enclosing, PsiSubstitutor.EMPTY)
ResolveState.initial().put(PsiSubstitutor.KEY, substitutor)
}
return BaseGroovyResolveResult(clazz, invocation, state)
}
override val arguments: Arguments? get() = element.getArguments()
override val supportsMapInvocation: Boolean get() = false
}
|
apache-2.0
|
c3ad7637a52ca6db15685e8682499673
| 46.454545 | 140 | 0.800128 | 4.565598 | false | false | false | false |
kickstarter/android-oss
|
app/src/main/java/com/kickstarter/libs/utils/RewardItemDecorator.kt
|
1
|
1640
|
package com.kickstarter.libs.utils
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.view.View
import androidx.recyclerview.widget.RecyclerView
class RewardItemDecorator(private val divider: Drawable) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val pos = parent.getChildAdapterPosition(view)
val itemCount = parent.layoutManager?.itemCount?.let { it } ?: return
val lastPosition = itemCount - 1
if (pos != 0 && pos != lastPosition) {
outRect.bottom = divider.intrinsicHeight
}
}
override fun onDraw(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) {
val dividerLeft = parent.paddingLeft
val dividerRight = parent.width - parent.paddingRight
val childCount = parent.childCount
for (i in 0 until childCount) {
val child = parent.getChildAt(i)
val pos = parent.getChildAdapterPosition(child)
val itemCount = parent.layoutManager?.itemCount?.let { it } ?: continue
val lastPosition = itemCount - 1
if (pos != lastPosition) {
val params = child.layoutParams as RecyclerView.LayoutParams
val dividerTop = child.bottom + params.bottomMargin
val dividerBottom = dividerTop + divider.intrinsicHeight
divider.setBounds(dividerLeft, dividerTop, dividerRight, dividerBottom)
divider.draw(canvas)
}
}
}
}
|
apache-2.0
|
bedb454d6e8b8a0555e22de2d0043fe6
| 37.139535 | 109 | 0.664634 | 5.093168 | false | false | false | false |
leafclick/intellij-community
|
plugins/changeReminder/src/com/jetbrains/changeReminder/plugin/UserSettings.kt
|
1
|
1409
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.changeReminder.plugin
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.util.EventDispatcher
import java.util.*
@State(name = "ChangeReminderUserStorage", storages = [Storage(file = "changeReminder.user.storage.xml")])
class UserSettings : PersistentStateComponent<UserSettings.Companion.State> {
companion object {
data class State(var isPluginEnabled: Boolean = true)
}
interface PluginStatusListener : EventListener {
fun statusChanged(isEnabled: Boolean)
}
private val eventDispatcher = EventDispatcher.create(PluginStatusListener::class.java)
private var currentState = State()
var isPluginEnabled: Boolean
get() = currentState.isPluginEnabled
set(value) {
currentState.isPluginEnabled = value
eventDispatcher.multicaster.statusChanged(value)
}
override fun loadState(state: State) {
currentState = state
}
override fun getState(): State = currentState
fun addPluginStatusListener(listener: PluginStatusListener, parentDisposable: Disposable) {
eventDispatcher.addListener(listener, parentDisposable)
}
}
|
apache-2.0
|
115559500bf93425f8af19f7eda06dba
| 34.25 | 140 | 0.782825 | 4.825342 | false | false | false | false |
leafclick/intellij-community
|
plugins/stats-collector/src/com/intellij/completion/ml/common/TextReferencesFeature.kt
|
1
|
2047
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.completion.ml.common
import com.intellij.codeInsight.completion.CompletionLocation
import com.intellij.codeInsight.completion.ml.ContextFeatures
import com.intellij.codeInsight.completion.ml.ElementFeatureProvider
import com.intellij.codeInsight.completion.ml.MLFeatureValue
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.impl.cache.impl.id.IdIndex
import com.intellij.psi.impl.cache.impl.id.IdIndexEntry
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.UsageSearchContext
import com.intellij.util.indexing.FileBasedIndex
import com.intellij.util.indexing.FileBasedIndexImpl
import java.util.concurrent.atomic.AtomicInteger
class TextReferencesFeature : ElementFeatureProvider {
override fun getName(): String = "references"
override fun calculateFeatures(element: LookupElement,
location: CompletionLocation,
contextFeatures: ContextFeatures): MutableMap<String, MLFeatureValue> {
if (element.psiElement == null || !StringUtil.isJavaIdentifier(element.lookupString)) return mutableMapOf()
val project = location.project
val index = FileBasedIndex.getInstance() as FileBasedIndexImpl
val filter = index.projectIndexableFiles(project) ?: return mutableMapOf()
val referencingFiles = AtomicInteger(0)
index.ensureUpToDate(IdIndex.NAME, project, GlobalSearchScope.allScope(project))
index
.getIndex(IdIndex.NAME)
.getData(IdIndexEntry(element.lookupString, true))
.forEach { fileId, value ->
if (value and UsageSearchContext.IN_CODE.toInt() != 0 && filter.containsFileId(fileId)) {
referencingFiles.incrementAndGet()
}
true
}
return mutableMapOf("file_count" to MLFeatureValue.float(referencingFiles.get()))
}
}
|
apache-2.0
|
993c429cbcdaf98859f35e24560c47d7
| 46.627907 | 140 | 0.763556 | 4.727483 | false | false | false | false |
siosio/intellij-community
|
platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/library/ProjectLibraryTableBridgeImpl.kt
|
1
|
10298
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide.impl.legacyBridge.library
import com.intellij.openapi.Disposable
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.LibraryTable
import com.intellij.openapi.roots.libraries.LibraryTablePresentation
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar
import com.intellij.openapi.util.Disposer
import com.intellij.projectModel.ProjectModelBundle
import com.intellij.util.EventDispatcher
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.ide.WorkspaceModelChangeListener
import com.intellij.workspaceModel.ide.WorkspaceModelTopics
import com.intellij.workspaceModel.ide.impl.executeOrQueueOnDispatchThread
import com.intellij.workspaceModel.ide.legacyBridge.ProjectLibraryTableBridge
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.bridgeEntities.LibraryEntity
import com.intellij.workspaceModel.storage.bridgeEntities.LibraryId
import com.intellij.workspaceModel.storage.bridgeEntities.LibraryTableId
class ProjectLibraryTableBridgeImpl(
private val parentProject: Project
) : ProjectLibraryTableBridge, Disposable {
private val LOG = Logger.getInstance(javaClass)
private val entityStorage: VersionedEntityStorage = WorkspaceModel.getInstance(parentProject).entityStorage
private val dispatcher = EventDispatcher.create(LibraryTable.Listener::class.java)
private val libraryArrayValue = CachedValue<Array<Library>> { storage ->
storage.entities(LibraryEntity::class.java).filter { it.tableId == LibraryTableId.ProjectLibraryTableId }
.mapNotNull { storage.libraryMap.getDataByEntity(it) }
.toList().toTypedArray()
}
init {
val messageBusConnection = project.messageBus.connect(this)
WorkspaceModelTopics.getInstance(project).subscribeAfterModuleLoading(messageBusConnection, object : WorkspaceModelChangeListener {
override fun beforeChanged(event: VersionedStorageChange) {
val changes = event.getChanges(LibraryEntity::class.java).filterProjectLibraryChanges()
.filterIsInstance<EntityChange.Removed<LibraryEntity>>()
if (changes.isEmpty()) return
executeOrQueueOnDispatchThread {
for (change in changes) {
val library = event.storageBefore.libraryMap.getDataByEntity(change.entity)
LOG.debug { "Fire 'beforeLibraryRemoved' event for ${change.entity.name}, library = $library" }
if (library != null) {
dispatcher.multicaster.beforeLibraryRemoved(library)
}
}
}
}
override fun changed(event: VersionedStorageChange) {
val changes = event.getChanges(LibraryEntity::class.java).filterProjectLibraryChanges()
if (changes.isEmpty()) return
executeOrQueueOnDispatchThread {
for (change in changes) {
LOG.debug { "Process library change $change" }
when (change) {
is EntityChange.Added -> {
val alreadyCreatedLibrary = event.storageAfter.libraryMap.getDataByEntity(change.entity) as LibraryBridgeImpl?
val library = if (alreadyCreatedLibrary != null) {
alreadyCreatedLibrary.entityStorage = entityStorage
alreadyCreatedLibrary
}
else {
var newLibrary: LibraryBridge? = null
WorkspaceModel.getInstance(project).updateProjectModelSilent {
newLibrary = it.mutableLibraryMap.getOrPutDataByEntity(change.entity) {
LibraryBridgeImpl(
libraryTable = this@ProjectLibraryTableBridgeImpl,
project = project,
initialId = change.entity.persistentId(),
initialEntityStorage = entityStorage,
targetBuilder = null
)
}
}
newLibrary!!
}
dispatcher.multicaster.afterLibraryAdded(library)
}
is EntityChange.Removed -> {
val library = event.storageBefore.libraryMap.getDataByEntity(change.entity)
if (library != null) {
// TODO There won't be any content in libraryImpl as EntityStore's current was already changed
dispatcher.multicaster.afterLibraryRemoved(library)
Disposer.dispose(library)
}
}
is EntityChange.Replaced -> {
val idBefore = change.oldEntity.persistentId()
val idAfter = change.newEntity.persistentId()
if (idBefore != idAfter) {
val library = event.storageBefore.libraryMap.getDataByEntity(change.oldEntity) as? LibraryBridgeImpl
if (library != null) {
library.entityId = idAfter
dispatcher.multicaster.afterLibraryRenamed(library, LibraryNameGenerator.getLegacyLibraryName(idBefore))
}
}
}
}
}
}
}
})
}
fun loadLibraries() {
val storage = entityStorage.current
val libraries = storage
.entities(LibraryEntity::class.java)
.filter { it.tableId is LibraryTableId.ProjectLibraryTableId }
.filter { storage.libraryMap.getDataByEntity(it) == null }
.map { libraryEntity ->
Pair(libraryEntity, LibraryBridgeImpl(
libraryTable = this@ProjectLibraryTableBridgeImpl,
project = project,
initialId = libraryEntity.persistentId(),
initialEntityStorage = entityStorage,
targetBuilder = null
))
}
.toList()
LOG.debug("Initial load of project-level libraries")
if (libraries.isNotEmpty()) {
WorkspaceModel.getInstance(project).updateProjectModelSilent {
libraries.forEach { (entity, library) ->
it.mutableLibraryMap.addIfAbsent(entity, library)
}
}
libraries.forEach { (_, library) ->
dispatcher.multicaster.afterLibraryAdded(library)
}
}
}
override fun getProject(): Project = parentProject
override fun getLibraries(): Array<Library> = entityStorage.cachedValue(libraryArrayValue)
override fun createLibrary(): Library = createLibrary(null)
override fun createLibrary(name: String?): Library {
if (name == null) error("Creating unnamed project libraries is unsupported")
if (getLibraryByName(name) != null) {
error("Project library named $name already exists")
}
val modifiableModel = modifiableModel
modifiableModel.createLibrary(name)
modifiableModel.commit()
val newLibrary = getLibraryByName(name)
if (newLibrary == null) {
error("Library $name was not created")
}
return newLibrary
}
override fun removeLibrary(library: Library) {
val modifiableModel = modifiableModel
modifiableModel.removeLibrary(library)
modifiableModel.commit()
}
override fun getLibraryIterator(): Iterator<Library> = libraries.iterator()
override fun getLibraryByName(name: String): Library? {
val entity = entityStorage.current.resolve(LibraryId(name, LibraryTableId.ProjectLibraryTableId)) ?: return null
return entityStorage.current.libraryMap.getDataByEntity(entity)
}
override fun getTableLevel(): String = LibraryTablesRegistrar.PROJECT_LEVEL
override fun getPresentation(): LibraryTablePresentation = PROJECT_LIBRARY_TABLE_PRESENTATION
override fun getModifiableModel(): LibraryTable.ModifiableModel =
ProjectModifiableLibraryTableBridgeImpl(
libraryTable = this,
project = project,
originalStorage = entityStorage.current
)
override fun getModifiableModel(diff: WorkspaceEntityStorageBuilder): LibraryTable.ModifiableModel =
ProjectModifiableLibraryTableBridgeImpl(
libraryTable = this,
project = project,
originalStorage = entityStorage.current,
diff = diff,
cacheStorageResult = false
)
override fun addListener(listener: LibraryTable.Listener) = dispatcher.addListener(listener)
override fun addListener(listener: LibraryTable.Listener, parentDisposable: Disposable) =
dispatcher.addListener(listener, parentDisposable)
override fun removeListener(listener: LibraryTable.Listener) = dispatcher.removeListener(listener)
override fun dispose() {
for (library in libraries) {
Disposer.dispose(library)
}
}
companion object {
private fun List<EntityChange<LibraryEntity>>.filterProjectLibraryChanges() =
filter {
when (it) {
is EntityChange.Added -> it.entity.tableId is LibraryTableId.ProjectLibraryTableId
is EntityChange.Removed -> it.entity.tableId is LibraryTableId.ProjectLibraryTableId
is EntityChange.Replaced -> it.oldEntity.tableId is LibraryTableId.ProjectLibraryTableId
}
}
internal val PROJECT_LIBRARY_TABLE_PRESENTATION = object : LibraryTablePresentation() {
override fun getDisplayName(plural: Boolean) = ProjectModelBundle.message("project.library.display.name", if (plural) 2 else 1)
override fun getDescription() = ProjectModelBundle.message("libraries.node.text.project")
override fun getLibraryTableEditorTitle() = ProjectModelBundle.message("library.configure.project.title")
}
private const val LIBRARY_BRIDGE_MAPPING_ID = "intellij.libraries.bridge"
val WorkspaceEntityStorage.libraryMap: ExternalEntityMapping<LibraryBridge>
get() = getExternalMapping(LIBRARY_BRIDGE_MAPPING_ID)
val WorkspaceEntityStorageDiffBuilder.mutableLibraryMap: MutableExternalEntityMapping<LibraryBridge>
get() = getMutableExternalMapping(LIBRARY_BRIDGE_MAPPING_ID)
fun WorkspaceEntityStorage.findLibraryEntity(library: LibraryBridge) =
libraryMap.getEntities(library).firstOrNull() as LibraryEntity?
}
}
|
apache-2.0
|
4030121ecc1d0ba1319d0b3773a6b34b
| 40.692308 | 140 | 0.699748 | 5.45734 | false | false | false | false |
siosio/intellij-community
|
plugins/kotlin/common/src/org/jetbrains/kotlin/idea/util/CallType.kt
|
1
|
17189
|
// 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.util
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.resolve.frontendService
import org.jetbrains.kotlin.idea.resolve.getDataFlowValueFactory
import org.jetbrains.kotlin.idea.resolve.getLanguageVersionSettings
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getReceiverExpression
import org.jetbrains.kotlin.psi.psiUtil.isImportDirectiveExpression
import org.jetbrains.kotlin.psi.psiUtil.isPackageDirectiveExpression
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore
import org.jetbrains.kotlin.resolve.calls.DslMarkerUtils
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactory
import org.jetbrains.kotlin.resolve.calls.smartcasts.SmartCastManager
import org.jetbrains.kotlin.resolve.descriptorUtil.classValueType
import org.jetbrains.kotlin.resolve.descriptorUtil.parentsWithSelf
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindExclude
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.resolve.scopes.receivers.*
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.expressions.DoubleColonLHS
import org.jetbrains.kotlin.util.isJavaDescriptor
import org.jetbrains.kotlin.util.supertypesWithAny
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import java.util.*
sealed class CallType<TReceiver : KtElement?>(val descriptorKindFilter: DescriptorKindFilter) {
object UNKNOWN : CallType<Nothing?>(DescriptorKindFilter.ALL)
object DEFAULT : CallType<Nothing?>(DescriptorKindFilter.ALL)
object DOT : CallType<KtExpression>(DescriptorKindFilter.ALL)
object SAFE : CallType<KtExpression>(DescriptorKindFilter.ALL)
object SUPER_MEMBERS : CallType<KtSuperExpression>(
DescriptorKindFilter.CALLABLES exclude DescriptorKindExclude.Extensions exclude AbstractMembersExclude
)
object INFIX : CallType<KtExpression>(DescriptorKindFilter.FUNCTIONS exclude NonInfixExclude)
object OPERATOR : CallType<KtExpression>(DescriptorKindFilter.FUNCTIONS exclude NonOperatorExclude)
object CALLABLE_REFERENCE : CallType<KtExpression?>(DescriptorKindFilter.CALLABLES exclude CallableReferenceExclude)
object IMPORT_DIRECTIVE : CallType<KtExpression?>(DescriptorKindFilter.ALL)
object PACKAGE_DIRECTIVE : CallType<KtExpression?>(DescriptorKindFilter.PACKAGES)
object TYPE : CallType<KtExpression?>(
DescriptorKindFilter(DescriptorKindFilter.CLASSIFIERS_MASK or DescriptorKindFilter.PACKAGES_MASK)
exclude DescriptorKindExclude.EnumEntry
)
object DELEGATE : CallType<KtExpression?>(DescriptorKindFilter.FUNCTIONS exclude NonOperatorExclude)
object ANNOTATION : CallType<KtExpression?>(
DescriptorKindFilter(DescriptorKindFilter.CLASSIFIERS_MASK or DescriptorKindFilter.PACKAGES_MASK)
exclude NonAnnotationClassifierExclude
)
private object NonInfixExclude : DescriptorKindExclude() {
override fun excludes(descriptor: DeclarationDescriptor) =
!(descriptor is SimpleFunctionDescriptor && descriptor.isInfix)
override val fullyExcludedDescriptorKinds: Int
get() = 0
}
private object NonOperatorExclude : DescriptorKindExclude() {
override fun excludes(descriptor: DeclarationDescriptor) =
!(descriptor is SimpleFunctionDescriptor && descriptor.isOperator)
override val fullyExcludedDescriptorKinds: Int
get() = 0
}
private object CallableReferenceExclude : DescriptorKindExclude() {
override fun excludes(descriptor: DeclarationDescriptor) /* currently not supported for locals and synthetic */ =
descriptor !is CallableMemberDescriptor || descriptor.kind == CallableMemberDescriptor.Kind.SYNTHESIZED
override val fullyExcludedDescriptorKinds: Int
get() = 0
}
private object NonAnnotationClassifierExclude : DescriptorKindExclude() {
override fun excludes(descriptor: DeclarationDescriptor): Boolean {
if (descriptor !is ClassifierDescriptor) return false
return descriptor !is ClassDescriptor || descriptor.kind != ClassKind.ANNOTATION_CLASS
}
override val fullyExcludedDescriptorKinds: Int get() = 0
}
private object AbstractMembersExclude : DescriptorKindExclude() {
override fun excludes(descriptor: DeclarationDescriptor) =
descriptor is CallableMemberDescriptor && descriptor.modality == Modality.ABSTRACT
override val fullyExcludedDescriptorKinds: Int
get() = 0
}
}
sealed class CallTypeAndReceiver<TReceiver : KtElement?, out TCallType : CallType<TReceiver>>(
val callType: TCallType,
val receiver: TReceiver
) {
object UNKNOWN : CallTypeAndReceiver<Nothing?, CallType.UNKNOWN>(CallType.UNKNOWN, null)
object DEFAULT : CallTypeAndReceiver<Nothing?, CallType.DEFAULT>(CallType.DEFAULT, null)
class DOT(receiver: KtExpression) : CallTypeAndReceiver<KtExpression, CallType.DOT>(CallType.DOT, receiver)
class SAFE(receiver: KtExpression) : CallTypeAndReceiver<KtExpression, CallType.SAFE>(CallType.SAFE, receiver)
class SUPER_MEMBERS(receiver: KtSuperExpression) : CallTypeAndReceiver<KtSuperExpression, CallType.SUPER_MEMBERS>(
CallType.SUPER_MEMBERS, receiver
)
class INFIX(receiver: KtExpression) : CallTypeAndReceiver<KtExpression, CallType.INFIX>(CallType.INFIX, receiver)
class OPERATOR(receiver: KtExpression) : CallTypeAndReceiver<KtExpression, CallType.OPERATOR>(CallType.OPERATOR, receiver)
class CALLABLE_REFERENCE(receiver: KtExpression?) : CallTypeAndReceiver<KtExpression?, CallType.CALLABLE_REFERENCE>(
CallType.CALLABLE_REFERENCE, receiver
)
class IMPORT_DIRECTIVE(receiver: KtExpression?) : CallTypeAndReceiver<KtExpression?, CallType.IMPORT_DIRECTIVE>(
CallType.IMPORT_DIRECTIVE, receiver
)
class PACKAGE_DIRECTIVE(receiver: KtExpression?) :
CallTypeAndReceiver<KtExpression?, CallType.PACKAGE_DIRECTIVE>(CallType.PACKAGE_DIRECTIVE, receiver)
class TYPE(receiver: KtExpression?) : CallTypeAndReceiver<KtExpression?, CallType.TYPE>(CallType.TYPE, receiver)
class DELEGATE(receiver: KtExpression?) : CallTypeAndReceiver<KtExpression?, CallType.DELEGATE>(CallType.DELEGATE, receiver)
class ANNOTATION(receiver: KtExpression?) : CallTypeAndReceiver<KtExpression?, CallType.ANNOTATION>(CallType.ANNOTATION, receiver)
companion object {
fun detect(expression: KtSimpleNameExpression): CallTypeAndReceiver<*, *> {
val parent = expression.parent
if (parent is KtCallableReferenceExpression && expression == parent.callableReference) {
return CALLABLE_REFERENCE(parent.receiverExpression)
}
val receiverExpression = expression.getReceiverExpression()
if (expression.isImportDirectiveExpression()) {
return IMPORT_DIRECTIVE(receiverExpression)
}
if (expression.isPackageDirectiveExpression()) {
return PACKAGE_DIRECTIVE(receiverExpression)
}
if (parent is KtUserType) {
val constructorCallee = (parent.parent as? KtTypeReference)?.parent as? KtConstructorCalleeExpression
if (constructorCallee != null && constructorCallee.parent is KtAnnotationEntry) {
return ANNOTATION(receiverExpression)
}
return TYPE(receiverExpression)
}
when (expression) {
is KtOperationReferenceExpression -> {
if (receiverExpression == null) {
return UNKNOWN // incomplete code
}
return when (parent) {
is KtBinaryExpression -> {
if (parent.operationToken == KtTokens.IDENTIFIER)
INFIX(receiverExpression)
else
OPERATOR(receiverExpression)
}
is KtUnaryExpression -> OPERATOR(receiverExpression)
else -> error("Unknown parent for JetOperationReferenceExpression: $parent with text '${parent.text}'")
}
}
is KtNameReferenceExpression -> {
if (receiverExpression == null) {
return DEFAULT
}
if (receiverExpression is KtSuperExpression) {
return SUPER_MEMBERS(receiverExpression)
}
return when (parent) {
is KtCallExpression -> {
if ((parent.parent as KtQualifiedExpression).operationSign == KtTokens.SAFE_ACCESS)
SAFE(receiverExpression)
else
DOT(receiverExpression)
}
is KtQualifiedExpression -> {
if (parent.operationSign == KtTokens.SAFE_ACCESS)
SAFE(receiverExpression)
else
DOT(receiverExpression)
}
else -> error("Unknown parent for JetNameReferenceExpression with receiver: $parent")
}
}
else -> return UNKNOWN
}
}
}
}
data class ReceiverType(
val type: KotlinType,
val receiverIndex: Int,
val implicitValue: ReceiverValue? = null
) {
val implicit: Boolean get() = implicitValue != null
fun extractDslMarkers() =
implicitValue?.let(DslMarkerUtils::extractDslMarkerFqNames)?.all()
?: DslMarkerUtils.extractDslMarkerFqNames(type)
}
fun CallTypeAndReceiver<*, *>.receiverTypes(
bindingContext: BindingContext,
contextElement: PsiElement,
moduleDescriptor: ModuleDescriptor,
resolutionFacade: ResolutionFacade,
stableSmartCastsOnly: Boolean
): List<KotlinType>? {
return receiverTypesWithIndex(bindingContext, contextElement, moduleDescriptor, resolutionFacade, stableSmartCastsOnly)?.map { it.type }
}
fun CallTypeAndReceiver<*, *>.receiverTypesWithIndex(
bindingContext: BindingContext,
contextElement: PsiElement,
moduleDescriptor: ModuleDescriptor,
resolutionFacade: ResolutionFacade,
stableSmartCastsOnly: Boolean,
withImplicitReceiversWhenExplicitPresent: Boolean = false
): List<ReceiverType>? {
val languageVersionSettings = resolutionFacade.getLanguageVersionSettings()
val receiverExpression: KtExpression?
when (this) {
is CallTypeAndReceiver.CALLABLE_REFERENCE -> {
if (receiver != null) {
return when (val lhs = bindingContext[BindingContext.DOUBLE_COLON_LHS, receiver] ?: return emptyList()) {
is DoubleColonLHS.Type -> listOf(ReceiverType(lhs.type, 0))
is DoubleColonLHS.Expression -> {
val receiverValue = ExpressionReceiver.create(receiver, lhs.type, bindingContext)
receiverValueTypes(
receiverValue, lhs.dataFlowInfo, bindingContext,
moduleDescriptor, stableSmartCastsOnly,
resolutionFacade
).map { ReceiverType(it, 0) }
}
}
} else {
return emptyList()
}
}
is CallTypeAndReceiver.DEFAULT -> receiverExpression = null
is CallTypeAndReceiver.DOT -> receiverExpression = receiver
is CallTypeAndReceiver.SAFE -> receiverExpression = receiver
is CallTypeAndReceiver.INFIX -> receiverExpression = receiver
is CallTypeAndReceiver.OPERATOR -> receiverExpression = receiver
is CallTypeAndReceiver.DELEGATE -> receiverExpression = receiver
is CallTypeAndReceiver.SUPER_MEMBERS -> {
val qualifier = receiver.superTypeQualifier
return if (qualifier != null) {
listOfNotNull(bindingContext.getType(receiver)).map { ReceiverType(it, 0) }
} else {
val resolutionScope = contextElement.getResolutionScope(bindingContext, resolutionFacade)
val classDescriptor =
resolutionScope.ownerDescriptor.parentsWithSelf.firstIsInstanceOrNull<ClassDescriptor>() ?: return emptyList()
classDescriptor.typeConstructor.supertypesWithAny().map { ReceiverType(it, 0) }
}
}
is CallTypeAndReceiver.IMPORT_DIRECTIVE,
is CallTypeAndReceiver.PACKAGE_DIRECTIVE,
is CallTypeAndReceiver.TYPE,
is CallTypeAndReceiver.ANNOTATION,
is CallTypeAndReceiver.UNKNOWN ->
return null
}
val resolutionScope = contextElement.getResolutionScope(bindingContext, resolutionFacade)
fun extractReceiverTypeFrom(descriptor: ClassDescriptor): KotlinType? = // companion object type or class itself
descriptor.classValueType ?: (if (descriptor.isFinalOrEnum || descriptor.isJavaDescriptor) null else descriptor.defaultType)
fun tryExtractReceiver(context: BindingContext) = context.get(BindingContext.QUALIFIER, receiverExpression)
fun tryExtractClassDescriptor(context: BindingContext): ClassDescriptor? =
(tryExtractReceiver(context) as? ClassQualifier)?.descriptor
fun tryExtractClassDescriptorFromAlias(context: BindingContext): ClassDescriptor? =
(tryExtractReceiver(context) as? TypeAliasQualifier)?.classDescriptor
fun extractReceiverTypeFrom(context: BindingContext, receiverExpression: KtExpression): KotlinType? {
return context.getType(receiverExpression) ?: tryExtractClassDescriptor(context)?.let { extractReceiverTypeFrom(it) }
?: tryExtractClassDescriptorFromAlias(context)?.let { extractReceiverTypeFrom(it) }
}
val expressionReceiver = receiverExpression?.let {
val receiverType = extractReceiverTypeFrom(bindingContext, receiverExpression) ?: return emptyList()
ExpressionReceiver.create(receiverExpression, receiverType, bindingContext)
}
val implicitReceiverValues = resolutionScope.getImplicitReceiversWithInstance(
excludeShadowedByDslMarkers = languageVersionSettings.supportsFeature(LanguageFeature.DslMarkersSupport)
).map { it.value }
val dataFlowInfo = bindingContext.getDataFlowInfoBefore(contextElement)
val result = ArrayList<ReceiverType>()
var receiverIndex = 0
fun addReceiverType(receiverValue: ReceiverValue, implicit: Boolean) {
val types = receiverValueTypes(
receiverValue, dataFlowInfo, bindingContext, moduleDescriptor, stableSmartCastsOnly,
resolutionFacade
)
types.mapTo(result) { type -> ReceiverType(type, receiverIndex, receiverValue.takeIf { implicit }) }
receiverIndex++
}
if (withImplicitReceiversWhenExplicitPresent || expressionReceiver == null) {
implicitReceiverValues.forEach { addReceiverType(it, true) }
}
if (expressionReceiver != null) {
addReceiverType(expressionReceiver, false)
}
return result
}
@OptIn(FrontendInternals::class)
private fun receiverValueTypes(
receiverValue: ReceiverValue,
dataFlowInfo: DataFlowInfo,
bindingContext: BindingContext,
moduleDescriptor: ModuleDescriptor,
stableSmartCastsOnly: Boolean,
resolutionFacade: ResolutionFacade
): List<KotlinType> {
val languageVersionSettings = resolutionFacade.getLanguageVersionSettings()
val dataFlowValueFactory = resolutionFacade.getDataFlowValueFactory()
val smartCastManager = resolutionFacade.frontendService<SmartCastManager>()
val dataFlowValue = dataFlowValueFactory.createDataFlowValue(receiverValue, bindingContext, moduleDescriptor)
return if (dataFlowValue.isStable || !stableSmartCastsOnly) { // we don't include smart cast receiver types for "unstable" receiver value to mark members grayed
smartCastManager.getSmartCastVariantsWithLessSpecificExcluded(
receiverValue,
bindingContext,
moduleDescriptor,
dataFlowInfo,
languageVersionSettings,
dataFlowValueFactory
)
} else {
listOf(receiverValue.type)
}
}
|
apache-2.0
|
a02c9cf3c9cba91004d090c6c76847c9
| 44.234211 | 164 | 0.697539 | 6.250545 | false | false | false | false |
chemouna/Nearby
|
app/src/main/kotlin/com/mounacheikhna/nearby/transition/VenueSharedEnter.kt
|
1
|
996
|
package com.mounacheikhna.nearby.transition
import android.content.Context
import android.graphics.Rect
import android.transition.ChangeBounds
import android.transition.TransitionValues
import android.util.AttributeSet
import android.view.View
/**
* Enter transition for clicking in a venue to expand into venue's detail.
*/
class VenueSharedEnter(context: Context, attrs: AttributeSet) : ChangeBounds(context, attrs) {
override fun captureEndValues(transitionValues: TransitionValues) {
super.captureEndValues(transitionValues)
val width = (transitionValues.values[PROPNAME_PARENT] as View).width
val bounds = transitionValues.values[PROPNAME_BOUNDS] as Rect
bounds.right = width
bounds.bottom = width * 3 / 4
transitionValues.values.put(PROPNAME_BOUNDS, bounds)
}
companion object {
private val PROPNAME_BOUNDS = "android:changeBounds:bounds"
private val PROPNAME_PARENT = "android:changeBounds:parent"
}
}
|
apache-2.0
|
0de322d7efbb25e9c65ba698480e3f8d
| 33.344828 | 94 | 0.746988 | 4.311688 | false | false | false | false |
siosio/intellij-community
|
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/JavaAnnotationsConversion.kt
|
2
|
3524
|
// 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.nj2k.conversions
import org.jetbrains.kotlin.load.java.JvmAnnotationNames
import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext
import org.jetbrains.kotlin.nj2k.tree.*
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class JavaAnnotationsConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) {
override fun applyToElement(element: JKTreeElement): JKTreeElement {
if (element is JKAnnotationList) {
for (annotation in element.annotations) {
if (annotation.classSymbol.fqName == "java.lang.SuppressWarnings") {
element.annotations -= annotation
} else {
processAnnotation(annotation)
}
}
}
return recurse(element)
}
private fun processAnnotation(annotation: JKAnnotation) {
if (annotation.classSymbol.fqName == "java.lang.Deprecated") {
annotation.classSymbol = symbolProvider.provideClassSymbol("kotlin.Deprecated")
annotation.arguments = listOf(JKAnnotationParameterImpl(JKLiteralExpression("\"\"", JKLiteralExpression.LiteralType.STRING)))
}
if (annotation.classSymbol.fqName == JvmAnnotationNames.TARGET_ANNOTATION.asString()) {
annotation.classSymbol = symbolProvider.provideClassSymbol("kotlin.annotation.Target")
val arguments = annotation.arguments.singleOrNull()?.let { parameter ->
when (val value = parameter.value) {
is JKKtAnnotationArrayInitializerExpression -> value.initializers
else -> listOf(value)
}
}
if (arguments != null) {
val newArguments =
arguments.flatMap { value ->
value.fieldAccessFqName()
?.let { targetMappings[it] }
?.map { fqName ->
JKFieldAccessExpression(symbolProvider.provideFieldSymbol(fqName))
} ?: listOf(value.copyTreeAndDetach())
}
annotation.arguments = newArguments.map { JKAnnotationParameterImpl(it) }
}
}
}
private fun JKAnnotationMemberValue.fieldAccessFqName(): String? =
(safeAs<JKQualifiedExpression>()?.selector ?: this)
.safeAs<JKFieldAccessExpression>()
?.identifier
?.fqName
companion object {
private val targetMappings =
listOf(
"ANNOTATION_TYPE" to listOf("ANNOTATION_CLASS"),
"CONSTRUCTOR" to listOf("CONSTRUCTOR"),
"FIELD" to listOf("FIELD"),
"LOCAL_VARIABLE" to listOf("LOCAL_VARIABLE"),
"METHOD" to listOf("FUNCTION", "PROPERTY_GETTER", "PROPERTY_SETTER"),
"PACKAGE" to listOf("FILE"),
"PARAMETER" to listOf("VALUE_PARAMETER"),
"TYPE_PARAMETER" to listOf("TYPE_PARAMETER"),
"TYPE" to listOf("ANNOTATION_CLASS", "CLASS"),
"TYPE_USE" to listOf("TYPE_USE")
).map { (java, kotlins) ->
"java.lang.annotation.ElementType.$java" to kotlins.map { "kotlin.annotation.AnnotationTarget.$it" }
}.toMap()
}
}
|
apache-2.0
|
cb952be3ca93cc2b3c4f84fe2ad6f744
| 44.179487 | 158 | 0.596481 | 5.347496 | false | false | false | false |
3sidedcube/react-native-navigation
|
lib/android/app/src/main/java/com/reactnativenavigation/views/element/animators/RotationAnimator.kt
|
2
|
869
|
package com.reactnativenavigation.views.element.animators
import android.animation.Animator
import android.animation.ObjectAnimator
import android.view.View
import com.facebook.react.views.image.ReactImageView
import com.reactnativenavigation.options.SharedElementTransitionOptions
class RotationAnimator(from: View, to: View) : PropertyAnimatorCreator<ReactImageView>(from, to) {
private val fromRotation = from.rotation
private val toRotation = to.rotation
override fun shouldAnimateProperty(fromChild: ReactImageView, toChild: ReactImageView): Boolean {
return fromRotation != toRotation
}
override fun create(options: SharedElementTransitionOptions): Animator {
to.rotation = fromRotation
to.pivotX = 0f
to.pivotY = 0f
return ObjectAnimator.ofFloat(to, View.ROTATION, fromRotation, toRotation)
}
}
|
mit
|
51068db1ce017ba76b950abc15aeed89
| 36.826087 | 101 | 0.773303 | 4.854749 | false | false | false | false |
siosio/intellij-community
|
python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyProtocols.kt
|
1
|
3273
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.codeInsight.typing
import com.jetbrains.python.PyNames
import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider.PROTOCOL
import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider.PROTOCOL_EXT
import com.jetbrains.python.psi.AccessDirection
import com.jetbrains.python.psi.PyClass
import com.jetbrains.python.psi.PyPossibleClassMember
import com.jetbrains.python.psi.PyTypedElement
import com.jetbrains.python.psi.impl.PyCallExpressionHelper.resolveImplicitlyInvokedMethods
import com.jetbrains.python.psi.resolve.PyResolveContext
import com.jetbrains.python.psi.resolve.RatedResolveResult
import com.jetbrains.python.psi.types.PyClassLikeType
import com.jetbrains.python.psi.types.PyClassType
import com.jetbrains.python.psi.types.PyType
import com.jetbrains.python.psi.types.TypeEvalContext
fun isProtocol(classLikeType: PyClassLikeType, context: TypeEvalContext): Boolean = containsProtocol(classLikeType.getSuperClassTypes(context))
fun isProtocol(cls: PyClass, context: TypeEvalContext): Boolean = containsProtocol(cls.getSuperClassTypes(context))
fun matchingProtocolDefinitions(expected: PyType?, actual: PyType?, context: TypeEvalContext): Boolean = expected is PyClassLikeType &&
actual is PyClassLikeType &&
expected.isDefinition &&
actual.isDefinition &&
isProtocol(expected, context) &&
isProtocol(actual, context)
typealias ProtocolAndSubclassElements = Pair<PyTypedElement, List<RatedResolveResult>?>
fun inspectProtocolSubclass(protocol: PyClassType, subclass: PyClassType, context: TypeEvalContext): List<ProtocolAndSubclassElements> {
val resolveContext = PyResolveContext.defaultContext(context)
val result = mutableListOf<Pair<PyTypedElement, List<RatedResolveResult>?>>()
protocol.toInstance().visitMembers(
{ e ->
if (e is PyTypedElement) {
if (e is PyPossibleClassMember) {
val cls = e.containingClass
if (cls != null && !isProtocol(cls, context)) {
return@visitMembers true
}
}
val name = e.name ?: return@visitMembers true
if (name == PyNames.CALL) {
result.add(Pair(e, resolveImplicitlyInvokedMethods(subclass, null, resolveContext)))
}
else {
result.add(Pair(e, subclass.resolveMember(name, null, AccessDirection.READ, resolveContext)))
}
}
true
},
true,
context
)
return result
}
private fun containsProtocol(types: List<PyClassLikeType?>) = types.any { type ->
val classQName = type?.classQName
PROTOCOL == classQName || PROTOCOL_EXT == classQName
}
|
apache-2.0
|
4e0ce2aa5acea32a8e5652436be8ec64
| 45.757143 | 143 | 0.642224 | 5.339315 | false | false | false | false |
Briseus/Lurker
|
app/src/main/java/torille/fi/lurkforreddit/di/modules/RedditModule.kt
|
1
|
4333
|
package torille.fi.lurkforreddit.di.modules
import dagger.Module
import dagger.Provides
import okhttp3.*
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import timber.log.Timber
import torille.fi.lurkforreddit.data.RedditService
import torille.fi.lurkforreddit.utils.NetworkHelper
import torille.fi.lurkforreddit.utils.Store
import java.io.IOException
import javax.inject.Named
import javax.inject.Singleton
/**
* Provides retrofit for Reddit API
*/
@Module
class RedditModule(private val baseUrl: String) {
@Provides
@Singleton
@Named("rawJson")
internal fun providesRawJsonInterceptor(): Interceptor {
return Interceptor { chain ->
val originalRequest = chain.request()
val originalHttpUrl = originalRequest.url()
val url = originalHttpUrl.newBuilder()
.addQueryParameter("raw_json", "1")
.build()
val requestBuilder = originalRequest.newBuilder()
.url(url)
val request = requestBuilder.build()
chain.proceed(request)
}
}
@Provides
@Singleton
@Named("tokenInterceptor")
internal fun providesTokenInterceptor(
store: Store,
networkHelper: NetworkHelper
): Interceptor {
return Interceptor { chain ->
val original = chain.request()
if (original.header("Authorization").isNullOrBlank()) {
var token: String = store.token
if (token.isEmpty()) {
Timber.d("Token was not set, going to get token")
token = networkHelper.getToken()
Timber.d("Got new token $token")
}
val requestBuilder = original.newBuilder()
.header("Authorization", "bearer " + token)
.method(original.method(), original.body())
val request = requestBuilder.build()
chain.proceed(request)
} else {
chain.proceed(original)
}
}
}
@Provides
@Singleton
internal fun providesAuthenticator(networkHelper: NetworkHelper): Authenticator {
return object : Authenticator {
@Throws(IOException::class)
override fun authenticate(route: Route, response: Response): Request? {
if (responseCount(response) >= 3) {
Timber.e("Too many retries")
return null
}
Timber.d("Fetching new token")
val newAccessToken = networkHelper.authenticateApp()
if (newAccessToken.length < 3) {
Timber.e("New token $newAccessToken was too short")
return null
}
return response.request().newBuilder()
.addHeader("Authorization", "bearer " + newAccessToken)
.build()
}
internal fun responseCount(response: Response): Int {
var result = 1
while (response == response.priorResponse()) {
result++
}
return result
}
}
}
@Provides
@Singleton
internal fun providesRedditService(
gsonConverterFactory: GsonConverterFactory,
okHttpClient: OkHttpClient,
rxJava2CallAdapterFactory: RxJava2CallAdapterFactory,
authenticator: Authenticator,
@Named("rawJson") rawJsonInterceptor: Interceptor,
@Named("tokenInterceptor") tokenInterceptor: Interceptor
)
: RedditService.Reddit {
val retrofit = Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(gsonConverterFactory)
.addCallAdapterFactory(rxJava2CallAdapterFactory)
.client(
okHttpClient
.newBuilder()
.addInterceptor(rawJsonInterceptor)
.addNetworkInterceptor(tokenInterceptor)
.authenticator(authenticator)
.build()
)
.build()
return retrofit.create(RedditService.Reddit::class.java)
}
}
|
mit
|
5eea6c1a40663ac308ad73b8b7c59ff9
| 30.860294 | 85 | 0.57766 | 5.598191 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/stubs/AbstractStubBuilderTest.kt
|
1
|
1981
|
// 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.stubs
import com.intellij.psi.impl.DebugUtil
import com.intellij.psi.stubs.StubElement
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.name.SpecialNames
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.stubs.elements.KtFileStubBuilder
import org.jetbrains.kotlin.psi.stubs.impl.STUB_TO_STRING_PREFIX
import org.jetbrains.kotlin.idea.test.KotlinTestUtils
import java.io.File
abstract class AbstractStubBuilderTest : KotlinLightCodeInsightFixtureTestCase() {
protected fun doTest(unused: String) {
val file = myFixture.configureByFile(fileName()) as KtFile
val ktStubBuilder = KtFileStubBuilder()
val lighterTree = ktStubBuilder.buildStubTree(file)
val stubTree = serializeStubToString(lighterTree)
val testFile = testDataFile()
val expectedFile = File(testFile.parent, testFile.nameWithoutExtension + ".expected")
KotlinTestUtils.assertEqualsToFile(expectedFile, stubTree)
}
companion object {
fun serializeStubToString(stubElement: StubElement<*>): String {
val treeStr = DebugUtil.stubTreeToString(stubElement).replace(SpecialNames.SAFE_IDENTIFIER_FOR_NO_NAME.asString(), "<no name>")
// Nodes are stored in form "NodeType:Node" and have too many repeating information for Kotlin stubs
// Remove all repeating information (See KotlinStubBaseImpl.toString())
return treeStr.lines().joinToString(separator = "\n") {
if (it.contains(STUB_TO_STRING_PREFIX)) {
it.takeWhile(Char::isWhitespace) + it.substringAfter("KotlinStub$")
} else {
it
}
}.replace(", [", "[")
}
}
}
|
apache-2.0
|
0d49ffdace55ca86a161406dfdc1ed9b
| 45.069767 | 158 | 0.706714 | 4.683215 | false | true | false | false |
jwren/intellij-community
|
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/decompiler/navigation/NavigationWithMultipleLibrariesTest.kt
|
1
|
7136
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.decompiler.navigation
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.StdModuleTypes
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.impl.libraries.ProjectLibraryTable
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import com.intellij.testFramework.JavaModuleTestCase
import org.jetbrains.kotlin.idea.artifacts.KotlinArtifacts
import org.jetbrains.kotlin.idea.caches.project.LibraryInfo
import org.jetbrains.kotlin.idea.caches.project.LibrarySourceInfo
import org.jetbrains.kotlin.idea.caches.project.getNullableModuleInfo
import org.jetbrains.kotlin.idea.decompiler.navigation.NavigationChecker.Companion.checkAnnotatedCode
import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR
import org.jetbrains.kotlin.idea.util.projectStructure.getModuleDir
import org.jetbrains.kotlin.idea.test.KotlinCompilerStandalone
import org.jetbrains.kotlin.test.util.addDependency
import org.jetbrains.kotlin.test.util.jarRoot
import org.jetbrains.kotlin.test.util.projectLibrary
import org.junit.Assert
import org.junit.internal.runners.JUnit38ClassRunner
import org.junit.runner.RunWith
import java.io.File
@RunWith(JUnit38ClassRunner::class)
class NavigationWithMultipleCustomLibrariesTest : AbstractNavigationToSourceOrDecompiledTest() {
override fun getTestDataDirectory() = IDEA_TEST_DATA_DIR.resolve("decompiler/navigationMultipleLibs")
fun testNavigationToDecompiled() {
doTest(false, "expected.decompiled")
}
fun testNavigationToLibrarySources() {
doTest(true, "expected.sources")
}
override fun createProjectLib(libraryName: String, withSources: Boolean): Library {
val sources = listOf(File(getTestDataDirectory(), "libSrc"))
val libraryJar = KotlinCompilerStandalone(sources, jarWithSources = true).compile()
val jarRoot = libraryJar.jarRoot
return projectLibrary(libraryName, jarRoot, jarRoot.findChild("src").takeIf { withSources })
}
}
class NavigationWithMultipleRuntimesTest : AbstractNavigationToSourceOrDecompiledTest() {
override fun getTestDataDirectory(): File = IDEA_TEST_DATA_DIR.resolve("decompiler/navigationMultipleRuntimes")
fun testNavigationToDecompiled() {
doTest(false, "expected.decompiled")
}
fun testNavigationToLibrarySources() {
doTest(true, "expected.sources")
}
override fun createProjectLib(libraryName: String, withSources: Boolean): Library {
val libraryJar = KotlinArtifacts.instance.kotlinStdlib.copyTo(File(createTempDirectory(), "$libraryName.jar"))
val jarUrl = libraryJar.jarRoot
return runWriteAction {
val library = ProjectLibraryTable.getInstance(project).createLibrary(libraryName)
val modifiableModel = library.modifiableModel
modifiableModel.addRoot(jarUrl, OrderRootType.CLASSES)
if (withSources) {
val sourcesJar =
KotlinArtifacts.instance.kotlinStdlibSources.copyTo(File(createTempDirectory(), "$libraryName-sources.jar"))
modifiableModel.addRoot(sourcesJar.jarRoot, OrderRootType.SOURCES)
}
modifiableModel.commit()
library
}
}
}
abstract class AbstractNavigationToSourceOrDecompiledTest : AbstractNavigationWithMultipleLibrariesTest() {
fun doTest(withSources: Boolean, expectedFileName: String) {
val srcPath = getTestDataDirectory().resolve("src").absolutePath
val moduleA = module("moduleA", srcPath)
val moduleB = module("moduleB", srcPath)
moduleA.addDependency(createProjectLib("libA", withSources))
moduleB.addDependency(createProjectLib("libB", withSources))
// navigation code works by providing first matching declaration from indices
// that's we need to check references in both modules to guard against possibility of code breaking
// while tests pass by chance
checkReferencesInModule(moduleA, "libA", expectedFileName)
checkReferencesInModule(moduleB, "libB", expectedFileName)
}
abstract fun createProjectLib(libraryName: String, withSources: Boolean): Library
}
class NavigationToSingleJarInMultipleLibrariesTest : AbstractNavigationWithMultipleLibrariesTest() {
override fun getTestDataDirectory() = IDEA_TEST_DATA_DIR.resolve("multiModuleReferenceResolve/sameJarInDifferentLibraries")
fun testNavigatingToLibrarySharingSameJarOnlyOneHasSourcesAttached() {
val srcPath = getTestDataDirectory().resolve("src").absolutePath
val moduleA = module("m1", srcPath)
val moduleB = module("m2", srcPath)
val moduleC = module("m3", srcPath)
val libSrc = File(getTestDataDirectory(), "libSrc")
val sharedJar = KotlinCompilerStandalone(listOf(libSrc), jarWithSources = true).compile()
val jarRoot = sharedJar.jarRoot
moduleA.addDependency(projectLibrary("libA", jarRoot))
moduleB.addDependency(projectLibrary("libB", jarRoot, jarRoot.findChild("src")))
moduleC.addDependency(projectLibrary("libC", jarRoot))
val expectedFile = File(getTestDataDirectory(), "expected.sources")
checkAnnotatedCode(findSourceFile(moduleA), expectedFile)
checkAnnotatedCode(findSourceFile(moduleB), expectedFile)
checkAnnotatedCode(findSourceFile(moduleC), expectedFile)
}
}
abstract class AbstractNavigationWithMultipleLibrariesTest : JavaModuleTestCase() {
abstract fun getTestDataDirectory(): File
protected fun module(name: String, srcPath: String) = createModuleFromTestData(srcPath, name, StdModuleTypes.JAVA, true)
protected fun checkReferencesInModule(module: Module, libraryName: String, expectedFileName: String) {
checkAnnotatedCode(findSourceFile(module), File(getTestDataDirectory(), expectedFileName)) {
checkLibraryName(it, libraryName)
}
}
}
private fun checkLibraryName(referenceTarget: PsiElement, expectedName: String) {
val navigationFile = referenceTarget.navigationElement.containingFile ?: return
val libraryName = when (val libraryInfo = navigationFile.getNullableModuleInfo()) {
is LibraryInfo -> libraryInfo.library.name
is LibrarySourceInfo -> libraryInfo.library.name
else -> error("Couldn't get library name")
}
Assert.assertEquals("Referenced code from unrelated library: ${referenceTarget.text}", expectedName, libraryName)
}
private fun findSourceFile(module: Module): PsiFile {
val ioFile = File(module.getModuleDir()).listFiles().orEmpty().first()
val vFile = LocalFileSystem.getInstance().findFileByIoFile(ioFile)!!
return PsiManager.getInstance(module.project).findFile(vFile)!!
}
|
apache-2.0
|
4fd8600c6b3933e8e324fb8d0b26dae5
| 45.947368 | 158 | 0.757427 | 4.955556 | false | true | false | false |
SimpleMobileTools/Simple-Calendar
|
app/src/main/kotlin/com/simplemobiletools/calendar/pro/dialogs/CustomPeriodPickerDialog.kt
|
1
|
2055
|
package com.simplemobiletools.calendar.pro.dialogs
import android.app.Activity
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.calendar.pro.R
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.DAY_SECONDS
import com.simplemobiletools.commons.helpers.MONTH_SECONDS
import com.simplemobiletools.commons.helpers.WEEK_SECONDS
import kotlinx.android.synthetic.main.dialog_custom_period_picker.view.*
class CustomPeriodPickerDialog(val activity: Activity, val callback: (value: Int) -> Unit) {
private var dialog: AlertDialog? = null
private var view = (activity.layoutInflater.inflate(R.layout.dialog_custom_period_picker, null) as ViewGroup)
init {
view.dialog_custom_period_value.setText("")
view.dialog_radio_view.check(R.id.dialog_radio_days)
activity.getAlertDialogBuilder()
.setPositiveButton(R.string.ok) { dialogInterface, i -> confirmReminder() }
.setNegativeButton(R.string.cancel, null)
.apply {
activity.setupDialogStuff(view, this) { alertDialog ->
dialog = alertDialog
alertDialog.showKeyboard(view.dialog_custom_period_value)
}
}
}
private fun calculatePeriod(selectedPeriodValue: Int, selectedPeriodValueType: Int) = when (selectedPeriodValueType) {
R.id.dialog_radio_days -> selectedPeriodValue * DAY_SECONDS
R.id.dialog_radio_weeks -> selectedPeriodValue * WEEK_SECONDS
else -> selectedPeriodValue * MONTH_SECONDS
}
private fun confirmReminder() {
val value = view.dialog_custom_period_value.value
val type = view.dialog_radio_view.checkedRadioButtonId
val periodValue = if (value.isEmpty()) {
"0"
} else {
value
}
val period = calculatePeriod(Integer.valueOf(periodValue), type)
callback(period)
activity.hideKeyboard()
dialog?.dismiss()
}
}
|
gpl-3.0
|
11c3bf652c26497c793c26eff3308f3c
| 39.294118 | 122 | 0.687591 | 4.457701 | false | false | false | false |
dahlstrom-g/intellij-community
|
platform/lang-impl/testSources/com/intellij/openapi/roots/ui/configuration/SdkTypeRegistrationTest.kt
|
5
|
2873
|
// 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.roots.ui.configuration
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.projectRoots.*
import com.intellij.openapi.projectRoots.impl.UnknownSdkType
import com.intellij.openapi.util.Disposer
import com.intellij.testFramework.HeavyPlatformTestCase
import org.jdom.Element
class SdkTypeRegistrationTest : HeavyPlatformTestCase() {
fun `test unregister sdk type and register again`() {
val sdkTable = ProjectJdkTable.getInstance()
runWithRegisteredType {
val sdk = sdkTable.createSdk("foo", MockSdkType.getInstance())
val modificator = sdk.sdkModificator
modificator.sdkAdditionalData = MockSdkAdditionalData("bar")
modificator.commitChanges()
runWriteAction {
sdkTable.addJdk(sdk, testRootDisposable)
}
assertEquals("foo", assertOneElement(sdkTable.getSdksOfType(MockSdkType.getInstance())).name)
}
assertOneElement(sdkTable.getSdksOfType(UnknownSdkType.getInstance("Mock")))
registerSdkType(testRootDisposable)
val reloadedSdk = assertOneElement(sdkTable.getSdksOfType(MockSdkType.getInstance()))
assertEquals("foo", reloadedSdk.name)
}
private fun runWithRegisteredType(action: () -> Unit) {
val sdkTypeDisposable = Disposer.newDisposable()
registerSdkType(sdkTypeDisposable)
try {
action()
}
finally {
Disposer.dispose(sdkTypeDisposable)
}
}
private fun registerSdkType(disposable: Disposable) {
val sdkTypeDisposable = Disposer.newDisposable()
Disposer.register(disposable, Disposable {
runWriteAction {
Disposer.dispose(sdkTypeDisposable)
}
})
SdkType.EP_NAME.getPoint().registerExtension(MockSdkType(), sdkTypeDisposable)
}
}
private class MockSdkType : SdkType("Mock") {
companion object {
@JvmStatic
fun getInstance() = findInstance(MockSdkType::class.java)
}
override fun suggestHomePath(): String? = null
override fun isValidSdkHome(path: String): Boolean = false
override fun suggestSdkName(currentSdkName: String?, sdkHome: String): String = ""
override fun createAdditionalDataConfigurable(sdkModel: SdkModel, sdkModificator: SdkModificator): AdditionalDataConfigurable? = null
override fun getPresentableName(): String = "Mock"
override fun saveAdditionalData(additionalData: SdkAdditionalData, additional: Element) {
additional.setAttribute("data", (additionalData as MockSdkAdditionalData).data)
}
override fun loadAdditionalData(additional: Element): SdkAdditionalData {
return MockSdkAdditionalData(additional.getAttributeValue("data") ?: "")
}
}
private class MockSdkAdditionalData(var data: String) : SdkAdditionalData
|
apache-2.0
|
eb57472ceb6cb4f3af33811844b058c4
| 34.925 | 135 | 0.758789 | 4.919521 | false | true | false | false |
androidx/androidx
|
health/connect/connect-client/src/main/java/androidx/health/platform/client/utils/IntentExt.kt
|
3
|
1758
|
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
package androidx.health.platform.client.utils
import android.content.Intent
import android.os.Bundle
import androidx.annotation.RestrictTo
import androidx.health.platform.client.proto.AbstractMessageLite
fun Intent.putProtoMessages(name: String, messages: Collection<AbstractMessageLite<*, *>>): Intent =
putByteArraysExtra(name = name, byteArrays = messages.map { it.toByteArray() })
fun Intent.putByteArraysExtra(name: String, byteArrays: Collection<ByteArray>): Intent =
putExtra(
name,
Bundle(byteArrays.size).apply {
byteArrays.forEachIndexed { index, bytes ->
putByteArray(index.toString(), bytes)
}
},
)
fun <T : AbstractMessageLite<*, *>> Intent.getProtoMessages(
name: String,
parser: (ByteArray) -> T,
): List<T>? =
getByteArraysExtra(name = name)?.map(parser)
fun Intent.getByteArraysExtra(name: String): List<ByteArray>? =
getBundleExtra(name)?.let { bundle ->
List(bundle.size()) { index ->
requireNotNull(bundle.getByteArray(index.toString()))
}
}
|
apache-2.0
|
ab80a9f82452c1d7be10bd77c088de11
| 34.16 | 100 | 0.704778 | 4.156028 | false | false | false | false |
smmribeiro/intellij-community
|
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/frame/XThreadsFramesView.kt
|
1
|
17576
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.xdebugger.impl.frame
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.NonProportionalOnePixelSplitter
import com.intellij.openapi.util.Disposer
import com.intellij.ui.ListSpeedSearch
import com.intellij.ui.PopupHandler
import com.intellij.ui.ScrollPaneFactory
import com.intellij.ui.SpeedSearchComparator
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.TextTransferable
import com.intellij.util.ui.UIUtil
import com.intellij.xdebugger.XDebugSession
import com.intellij.xdebugger.frame.XExecutionStack
import com.intellij.xdebugger.frame.XStackFrame
import com.intellij.xdebugger.frame.XSuspendContext
import com.intellij.xdebugger.impl.XDebugSessionImpl
import com.intellij.xdebugger.impl.actions.XDebuggerActions
import java.awt.BorderLayout
import java.awt.Component
import java.awt.Dimension
import java.awt.Rectangle
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.JComponent
import javax.swing.JList
import javax.swing.JPanel
import javax.swing.JScrollPane
class XThreadsFramesView(val project: Project) : XDebugView() {
private val myPauseDisposables = SequentialDisposables(this)
private val myThreadsList = XDebuggerThreadsList.createDefault()
private val myFramesList = XDebuggerFramesList(project)
private val mySplitter: NonProportionalOnePixelSplitter
private var myListenersEnabled = false
private var myFramesManager: FramesManager
private var myThreadsContainer: ThreadsContainer
val threads: XDebuggerThreadsList get() = myThreadsList
val frames: XDebuggerFramesList get() = myFramesList
private var myAlreadyPaused = false
private val myFramesPresentationCache = mutableMapOf<Any, String>()
private val mainPanel = JPanel(BorderLayout())
override fun getMainComponent(): JComponent {
return mainPanel
}
val defaultFocusedComponent: JComponent = myFramesList
companion object {
private const val splitterProportionKey = "XThreadsFramesViewSplitterKey"
private const val splitterProportionDefaultValue = 0.5f
private val Disposable.isAlive get() = !Disposer.isDisposed(this)
private val Disposable.isNotAlive get() = !isAlive
private fun Disposable.onTermination(disposable: Disposable) = Disposer.register(this, disposable)
private fun Disposable.onTermination(action: () -> Unit) = Disposer.register(this, Disposable { action() })
private fun Component.toScrollPane(): JScrollPane {
return ScrollPaneFactory.createScrollPane(this)
}
private fun <T> T.withSpeedSearch(
shouldMatchFromTheBeginning: Boolean = false,
shouldMatchCamelCase: Boolean = true,
converter: ((Any?) -> String?)? = null
): T where T : JList<*> {
val search = if (converter != null) ListSpeedSearch(this, converter) else ListSpeedSearch(this)
search.comparator = SpeedSearchComparator(shouldMatchFromTheBeginning, shouldMatchCamelCase)
return this
}
}
private fun XDebuggerFramesList.withSpeedSearch(
shouldMatchFromTheBeginning: Boolean = false,
shouldMatchCamelCase: Boolean = true
): XDebuggerFramesList {
val coloredStringBuilder = TextTransferable.ColoredStringBuilder()
fun getPresentation(element: Any?): String? {
element ?: return null
return myFramesPresentationCache.getOrPut(element) {
when (element) {
is XStackFrame -> {
element.customizePresentation(coloredStringBuilder)
val value = coloredStringBuilder.builder.toString()
coloredStringBuilder.builder.clear()
value
}
else -> toString()
}
}
}
return withSpeedSearch(shouldMatchFromTheBeginning, shouldMatchCamelCase, ::getPresentation)
}
fun setThreadsVisible(visible: Boolean) {
if (mySplitter.firstComponent.isVisible == visible) return
mySplitter.firstComponent.isVisible = visible
mySplitter.revalidate()
mySplitter.repaint()
}
fun isThreadsViewVisible() = mySplitter.firstComponent.isVisible
init {
val disposable = myPauseDisposables.next()
myFramesManager = FramesManager(myFramesList, disposable)
myThreadsContainer = ThreadsContainer(myThreadsList, null, disposable)
myPauseDisposables.terminateCurrent()
mySplitter = NonProportionalOnePixelSplitter(false, splitterProportionKey, splitterProportionDefaultValue, this, project).apply {
firstComponent = myThreadsList.withSpeedSearch().toScrollPane().apply {
minimumSize = Dimension(JBUI.scale(26), 0)
}
secondComponent = myFramesList.withSpeedSearch().toScrollPane()
}
mainPanel.add(mySplitter, BorderLayout.CENTER)
myThreadsList.addListSelectionListener { e ->
if (e.valueIsAdjusting || !myListenersEnabled) return@addListSelectionListener
val stack = myThreadsList.selectedValue?.stack ?: return@addListSelectionListener
val session = getSession(e) ?: return@addListSelectionListener
stack.setActive(session)
}
myThreadsList.addMouseListener(object : PopupHandler() {
override fun invokePopup(comp: Component, x: Int, y: Int) {
val actionManager = ActionManager.getInstance()
val group = actionManager.getAction(XDebuggerActions.THREADS_TREE_POPUP_GROUP) as? ActionGroup ?: return
actionManager.createActionPopupMenu(ActionPlaces.UNKNOWN, group).component.show(comp, x, y)
}
})
myThreadsList.addMouseListener(object : MouseAdapter() {
// not mousePressed here, otherwise click in unfocused frames list transfers focus to the new opened editor
override fun mouseReleased(e: MouseEvent) {
if (!myListenersEnabled) return
val i = myThreadsList.locationToIndex(e.point)
if (i == -1 || !myThreadsList.isSelectedIndex(i)) return
val session = getSession(e) ?: return
val stack = myThreadsList.selectedValue?.stack ?: return
stack.setActive(session)
}
})
myFramesList.addListSelectionListener {
if (it.valueIsAdjusting || !myListenersEnabled) return@addListSelectionListener
val session = getSession(it) ?: return@addListSelectionListener
val stack = myThreadsList.selectedValue?.stack ?: return@addListSelectionListener
val frame = myFramesList.selectedValue as? XStackFrame ?: return@addListSelectionListener
session.setCurrentStackFrame(stack, frame)
}
myFramesList.addMouseListener(object : PopupHandler() {
override fun invokePopup(comp: Component, x: Int, y: Int) {
val actionManager = ActionManager.getInstance()
val group = actionManager.getAction(XDebuggerActions.FRAMES_TREE_POPUP_GROUP) as ActionGroup
actionManager.createActionPopupMenu(ActionPlaces.UNKNOWN, group).component.show(comp, x, y)
}
})
myFramesList.addMouseListener(object : MouseAdapter() {
// not mousePressed here, otherwise click in unfocused frames list transfers focus to the new opened editor
override fun mouseReleased(e: MouseEvent) {
if (!myListenersEnabled) return
val i = myFramesList.locationToIndex(e.point)
if (i == -1 || !myFramesList.isSelectedIndex(i)) return
val session = getSession(e) ?: return
val stack = myThreadsList.selectedValue?.stack ?: return
val frame = myFramesList.selectedValue as? XStackFrame ?: return
session.setCurrentStackFrame(stack, frame)
}
})
}
fun saveUiState() {
if (mySplitter.width < mySplitter.minimumSize.width) return
mySplitter.saveProportion()
}
override fun processSessionEvent(event: SessionEvent, session: XDebugSession) {
if (event == SessionEvent.BEFORE_RESUME) {
return
}
val suspendContext = session.suspendContext
if (suspendContext == null) {
UIUtil.invokeLaterIfNeeded { myAlreadyPaused = false }
requestClear()
return
}
UIUtil.invokeLaterIfNeeded {
if (!myAlreadyPaused && (event == SessionEvent.PAUSED || event == SessionEvent.SETTINGS_CHANGED && session.isSuspended)) {
myAlreadyPaused = true
// clear immediately
cancelClear()
clear()
start(session)
return@invokeLaterIfNeeded
}
if (event == SessionEvent.FRAME_CHANGED) {
val currentExecutionStack = (session as XDebugSessionImpl).currentExecutionStack
val currentStackFrame = session.getCurrentStackFrame()
var selectedStack = threads.selectedValue?.stack
if (selectedStack != currentExecutionStack) {
val newSelectedItemIndex = threads.model.items.indexOfFirst { it.stack == currentExecutionStack }
if (newSelectedItemIndex != -1) {
threads.selectedIndex = newSelectedItemIndex;
myFramesManager.refresh();
selectedStack = threads.selectedValue?.stack;
}
}
if (selectedStack != currentExecutionStack)
return@invokeLaterIfNeeded;
val selectedFrame = frames.selectedValue
if (selectedFrame != currentStackFrame) {
frames.setSelectedValue(currentStackFrame, true);
}
}
if (event == SessionEvent.SETTINGS_CHANGED) {
myFramesManager.refresh()
}
}
}
fun start(session: XDebugSession) {
val suspendContext = session.suspendContext ?: return
val disposable = nextDisposable()
myFramesManager = FramesManager(myFramesList, disposable)
val activeStack = suspendContext.activeExecutionStack
activeStack?.setActive(session)
myThreadsContainer = ThreadsContainer(myThreadsList, activeStack, disposable)
myThreadsContainer.start(suspendContext)
}
private fun XExecutionStack.setActive(session: XDebugSession) {
myFramesManager.setActive(this)
val currentFrame = myFramesManager.tryGetCurrentFrame(this) ?: return
session.setCurrentStackFrame(this, currentFrame)
}
private fun nextDisposable(): Disposable {
val disposable = myPauseDisposables.next()
disposable.onTermination {
myListenersEnabled = false
}
myListenersEnabled = true
return disposable
}
override fun clear() {
myPauseDisposables.terminateCurrent()
myThreadsList.clear()
myFramesList.clear()
myFramesPresentationCache.clear()
}
override fun dispose() = Unit
private class FramesContainer(
private val myDisposable: Disposable,
private val myFramesList: XDebuggerFramesList,
private val myExecutionStack: XExecutionStack
) : XStackFrameContainerEx {
private var isActive = false
private var isProcessed = false
private var isStarted = false
private var mySelectedValue: Any? = null
private var myVisibleRectangle: Rectangle? = null
private val myItems = mutableListOf<Any?>()
val currentFrame: XStackFrame?
get() = myFramesList.selectedValue as? XStackFrame
fun startIfNeeded() {
UIUtil.invokeLaterIfNeeded {
if (isStarted)
return@invokeLaterIfNeeded
isStarted = true
myItems.add(null) // loading
myExecutionStack.computeStackFrames(0, this)
}
}
fun setActive(activeDisposable: Disposable) {
startIfNeeded()
isActive = true
activeDisposable.onTermination {
isActive = false
myVisibleRectangle = myFramesList.visibleRect
mySelectedValue = if (myFramesList.isSelectionEmpty) null else myFramesList.selectedValue
}
updateView()
}
private fun updateView() {
if (!isActive) return
myFramesList.model.replaceAll(myItems)
if (mySelectedValue != null) {
myFramesList.setSelectedValue(mySelectedValue, true)
}
else if (myFramesList.model.items.isNotEmpty()) {
myFramesList.selectedIndex = 0
mySelectedValue = myFramesList.selectedValue
}
val visibleRectangle = myVisibleRectangle
if (visibleRectangle != null)
myFramesList.scrollRectToVisible(visibleRectangle)
myFramesList.repaint()
}
override fun errorOccurred(errorMessage: String) {
addStackFramesInternal(mutableListOf(errorMessage), null, true)
}
override fun addStackFrames(stackFrames: MutableList<out XStackFrame>, toSelect: XStackFrame?, last: Boolean) {
addStackFramesInternal(stackFrames, toSelect, last)
}
override fun addStackFrames(stackFrames: MutableList<out XStackFrame>, last: Boolean) {
addStackFrames(stackFrames, null, last)
}
private fun addStackFramesInternal(stackFrames: MutableList<*>, toSelect: XStackFrame?, last: Boolean) {
invokeIfNeeded {
val insertIndex = myItems.size - 1
if (stackFrames.isNotEmpty()) {
myItems.addAll(insertIndex, stackFrames)
}
if (last) {
// remove loading
myItems.removeAt(myItems.size - 1)
isProcessed = true
}
if (toSelect != null && myItems.contains(toSelect)) {
mySelectedValue = toSelect
}
updateView()
}
}
private fun invokeIfNeeded(action: () -> Unit) {
UIUtil.invokeLaterIfNeeded {
if (isProcessed || myDisposable.isNotAlive)
return@invokeLaterIfNeeded
action()
}
}
}
private class FramesManager(private val myFramesList: XDebuggerFramesList, private val disposable: Disposable) {
private val myMap = mutableMapOf<StackInfo, FramesContainer>()
private val myActiveStackDisposables = SequentialDisposables(disposable)
private var myActiveStack: XExecutionStack? = null
private fun XExecutionStack.getContainer(): FramesContainer {
return myMap.getOrPut(StackInfo.from(this)) {
FramesContainer(disposable, myFramesList, this)
}
}
fun setActive(stack: XExecutionStack) {
val disposable = myActiveStackDisposables.next()
myActiveStack = stack
stack.getContainer().setActive(disposable)
}
fun tryGetCurrentFrame(stack: XExecutionStack): XStackFrame? {
return stack.getContainer().currentFrame
}
fun refresh() {
myMap.clear()
setActive(myActiveStack ?: return)
}
}
private class ThreadsContainer(
private val myThreadsList: XDebuggerThreadsList,
private val myActiveStack: XExecutionStack?,
private val myDisposable: Disposable
) : XSuspendContext.XExecutionStackContainer {
private var isProcessed = false
private var isStarted = false
companion object {
private val loading = listOf(StackInfo.loading)
}
fun start(suspendContext: XSuspendContext) {
UIUtil.invokeLaterIfNeeded {
if (isStarted) return@invokeLaterIfNeeded
if (myActiveStack != null) {
myThreadsList.model.replaceAll(listOf(StackInfo.from(myActiveStack), StackInfo.loading))
} else {
myThreadsList.model.replaceAll(loading)
}
myThreadsList.selectedIndex = 0
suspendContext.computeExecutionStacks(this)
isStarted = true
}
}
override fun errorOccurred(errorMessage: String) {
invokeIfNeeded {
val model = myThreadsList.model
// remove loading
model.remove(model.size - 1)
model.add(listOf(StackInfo.error(errorMessage)))
isProcessed = true
}
}
override fun addExecutionStack(executionStacks: MutableList<out XExecutionStack>, last: Boolean) {
invokeIfNeeded {
val model = myThreadsList.model
val insertIndex = model.size - 1
val threads = getThreadsList(executionStacks)
if (threads.any()) {
model.addAll(insertIndex, threads)
}
if (last) {
// remove loading
model.remove(model.size - 1)
isProcessed = true
}
myThreadsList.repaint()
}
}
fun addExecutionStack(executionStack: XExecutionStack, last: Boolean) {
addExecutionStack(mutableListOf(executionStack), last)
}
private fun getThreadsList(executionStacks: MutableList<out XExecutionStack>): List<StackInfo> {
var sequence = executionStacks.asSequence()
if (myActiveStack != null) {
sequence = sequence.filter { it != myActiveStack }
}
return sequence.map { StackInfo.from(it) }.toList()
}
private fun invokeIfNeeded(action: () -> Unit) {
UIUtil.invokeLaterIfNeeded {
if (isProcessed || myDisposable.isNotAlive) {
return@invokeLaterIfNeeded
}
action()
}
}
}
private class SequentialDisposables(parent: Disposable? = null) : Disposable {
private var myCurrentDisposable: Disposable? = null
init {
parent?.onTermination(this)
}
fun next(): Disposable {
val newDisposable = Disposer.newDisposable()
Disposer.register(this, newDisposable)
myCurrentDisposable?.disposeIfNeeded()
myCurrentDisposable = newDisposable
return newDisposable
}
fun terminateCurrent() {
myCurrentDisposable?.disposeIfNeeded()
myCurrentDisposable = null
}
private fun Disposable.disposeIfNeeded() {
if (this.isAlive)
Disposer.dispose(this)
}
override fun dispose() = terminateCurrent()
}
}
|
apache-2.0
|
54b7dcab404836f63288cfb5e2182ed1
| 31.791045 | 140 | 0.705508 | 4.979037 | false | false | false | false |
smmribeiro/intellij-community
|
platform/configuration-store-impl/src/FileBasedStorage.kt
|
1
|
13993
|
// 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.configurationStore
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.notification.Notifications
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PathMacroSubstitutor
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.components.StateStorageOperation
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.fileEditor.impl.LoadTextUtil
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.SafeStAXStreamBuilder
import com.intellij.openapi.util.createXmlStreamReader
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.ArrayUtil
import com.intellij.util.LineSeparator
import com.intellij.util.io.readCharSequence
import com.intellij.util.io.systemIndependentPath
import org.jdom.Element
import org.jdom.JDOMException
import org.jetbrains.annotations.NonNls
import java.io.IOException
import java.nio.ByteBuffer
import java.nio.file.Files
import java.nio.file.NoSuchFileException
import java.nio.file.Path
import java.nio.file.attribute.BasicFileAttributes
import javax.xml.stream.XMLStreamException
open class FileBasedStorage(file: Path,
fileSpec: String,
rootElementName: String?,
pathMacroManager: PathMacroSubstitutor? = null,
roamingType: RoamingType? = null,
provider: StreamProvider? = null) :
XmlElementStorage(fileSpec, rootElementName, pathMacroManager, roamingType, provider) {
@Volatile
private var cachedVirtualFile: VirtualFile? = null
private var lineSeparator: LineSeparator? = null
private var blockSaving: BlockSaving? = null
@Volatile
var file = file
private set
protected open val configuration: FileBasedStorageConfiguration
get() = defaultFileBasedStorageConfiguration
init {
val app = ApplicationManager.getApplication()
if (app != null && app.isUnitTestMode && file.toString().startsWith('$')) {
throw AssertionError("It seems like some macros were not expanded for path: $file")
}
}
protected open val isUseXmlProlog = false
final override val isUseVfsForWrite: Boolean
get() = configuration.isUseVfsForWrite
private val isUseUnixLineSeparator: Boolean
// only ApplicationStore doesn't use xml prolog
get() = !isUseXmlProlog
// we never set io file to null
fun setFile(virtualFile: VirtualFile?, ioFileIfChanged: Path?) {
cachedVirtualFile = virtualFile
if (ioFileIfChanged != null) {
file = ioFileIfChanged
}
}
override fun createSaveSession(states: StateMap) = FileSaveSession(states, this)
protected open class FileSaveSession(storageData: StateMap, storage: FileBasedStorage) :
XmlElementStorage.XmlElementStorageSaveSession<FileBasedStorage>(storageData, storage) {
final override fun isSaveAllowed(): Boolean {
if (!super.isSaveAllowed()) {
return false
}
if (storage.blockSaving != null) {
LOG.warn("Save blocked for $storage")
return false
}
return true
}
override fun saveLocally(dataWriter: DataWriter?) {
var lineSeparator = storage.lineSeparator
if (lineSeparator == null) {
lineSeparator = if (storage.isUseUnixLineSeparator) LineSeparator.LF else LineSeparator.getSystemLineSeparator()
storage.lineSeparator = lineSeparator
}
val isUseVfs = storage.configuration.isUseVfsForWrite
val virtualFile = if (isUseVfs) storage.getVirtualFile(StateStorageOperation.WRITE) else null
when {
dataWriter == null -> {
if (isUseVfs && virtualFile == null) {
LOG.warn("Cannot find virtual file $virtualFile")
}
deleteFile(storage.file, this, virtualFile)
storage.cachedVirtualFile = null
}
isUseVfs -> {
storage.cachedVirtualFile = writeFile(storage.file, this, virtualFile, dataWriter, lineSeparator, storage.isUseXmlProlog)
}
else -> {
val file = storage.file
LOG.debug { "Save $file" }
try {
dataWriter.writeTo(file, this, lineSeparator.separatorString)
}
catch (e: ReadOnlyModificationException) {
throw e
}
catch (e: Throwable) {
throw RuntimeException("Cannot write $file", e)
}
}
}
}
}
fun getVirtualFile(reasonOperation: StateStorageOperation): VirtualFile? {
var result = cachedVirtualFile
if (result == null) {
result = configuration.resolveVirtualFile(file.systemIndependentPath, reasonOperation)
cachedVirtualFile = result
}
return result
}
private inline fun <T> runAndHandleExceptions(task: () -> T): T? {
try {
return task()
}
catch (e: JDOMException) {
processReadException(e)
}
catch (e: XMLStreamException) {
processReadException(e)
}
catch (e: IOException) {
processReadException(e)
}
return null
}
fun preloadStorageData(isEmpty: Boolean) {
if (isEmpty) {
storageDataRef.set(StateMap.EMPTY)
}
else {
getStorageData()
}
}
override fun loadLocalData(): Element? {
blockSaving = null
return runAndHandleExceptions {
if (configuration.isUseVfsForRead) {
loadUsingVfs()
}
else {
loadLocalDataUsingIo()
}
}
}
private fun loadLocalDataUsingIo(): Element? {
val attributes: BasicFileAttributes?
try {
attributes = Files.readAttributes(file, BasicFileAttributes::class.java)
}
catch (e: NoSuchFileException) {
LOG.debug { "Document was not loaded for $fileSpec, doesn't exist" }
return null
}
if (!attributes.isRegularFile) {
LOG.debug { "Document was not loaded for $fileSpec, not a file" }
return null
}
else if (attributes.size() == 0L) {
processReadException(null)
return null
}
if (isUseUnixLineSeparator) {
// do not load the whole data into memory if no need to detect line separator
lineSeparator = LineSeparator.LF
val xmlStreamReader = createXmlStreamReader(Files.newInputStream(file))
try {
return SafeStAXStreamBuilder.build(xmlStreamReader, true, false, SafeStAXStreamBuilder.FACTORY)
}
finally {
xmlStreamReader.close()
}
}
else {
val data = CharsetToolkit.inputStreamSkippingBOM(Files.newInputStream(file)).reader().readCharSequence(attributes.size().toInt())
lineSeparator = detectLineSeparators(data, if (isUseXmlProlog) null else LineSeparator.LF)
return JDOMUtil.load(data)
}
}
private fun loadUsingVfs(): Element? {
val virtualFile = getVirtualFile(StateStorageOperation.READ)
if (virtualFile == null || !virtualFile.exists()) {
// only on first load
handleVirtualFileNotFound()
return null
}
val byteArray = virtualFile.contentsToByteArray()
if (byteArray.isEmpty()) {
processReadException(null)
return null
}
val charBuffer = Charsets.UTF_8.decode(ByteBuffer.wrap(byteArray))
lineSeparator = detectLineSeparators(charBuffer, if (isUseXmlProlog) null else LineSeparator.LF)
return JDOMUtil.load(charBuffer)
}
protected open fun handleVirtualFileNotFound() {
}
private fun processReadException(e: Exception?) {
val contentTruncated = e == null
if (!contentTruncated &&
(fileSpec == PROJECT_FILE || fileSpec.startsWith(PROJECT_CONFIG_DIR) ||
fileSpec == StoragePathMacros.MODULE_FILE || fileSpec == StoragePathMacros.WORKSPACE_FILE)) {
blockSaving = BlockSaving(reason = e?.toString() ?: "empty file")
}
else {
blockSaving = null
}
if (e != null) {
LOG.warn("Cannot read ${toString()}", e)
}
val app = ApplicationManager.getApplication()
if (!app.isUnitTestMode && !app.isHeadlessEnvironment) {
val reason = if (contentTruncated) ConfigurationStoreBundle.message("notification.load.settings.error.reason.truncated") else e!!.message
val action = if (blockSaving == null)
ConfigurationStoreBundle.message("notification.load.settings.action.content.will.be.recreated")
else ConfigurationStoreBundle.message("notification.load.settings.action.please.correct.file.content")
Notification(Notifications.SYSTEM_MESSAGES_GROUP_ID,
ConfigurationStoreBundle.message("notification.load.settings.title"),
"${ConfigurationStoreBundle.message("notification.load.settings.content", file)}: $reason\n$action",
NotificationType.WARNING)
.notify(null)
}
}
override fun toString() = "FileBasedStorage(file=$file, fileSpec=$fileSpec, isBlockSavingTheContent=$blockSaving)"
}
internal fun writeFile(cachedFile: Path?,
requestor: StorageManagerFileWriteRequestor,
virtualFile: VirtualFile?,
dataWriter: DataWriter,
lineSeparator: LineSeparator,
prependXmlProlog: Boolean): VirtualFile {
val file = if (cachedFile != null && (virtualFile == null || !virtualFile.isValid)) {
getOrCreateVirtualFile(cachedFile, requestor)
}
else {
virtualFile!!
}
if ((LOG.isDebugEnabled || ApplicationManager.getApplication().isUnitTestMode) && !FileUtilRt.isTooLarge(file.length)) {
val content = dataWriter.toBufferExposingByteArray(lineSeparator)
if (isEqualContent(file, lineSeparator, content, prependXmlProlog)) {
val contentString = content.toByteArray().toString(Charsets.UTF_8)
val message = "Content equals, but it must be handled not on this level: file ${file.name}, content:\n$contentString"
if (ApplicationManager.getApplication().isUnitTestMode) {
LOG.debug(message)
}
else {
LOG.warn(message)
}
}
else if (DEBUG_LOG != null && ApplicationManager.getApplication().isUnitTestMode) {
DEBUG_LOG = "${file.path}:\n$content\nOld Content:\n${LoadTextUtil.loadText(file)}"
}
}
doWrite(requestor, file, dataWriter, lineSeparator, prependXmlProlog)
return file
}
internal val XML_PROLOG = """<?xml version="1.0" encoding="UTF-8"?>""".toByteArray()
private fun isEqualContent(result: VirtualFile,
lineSeparator: LineSeparator,
content: BufferExposingByteArrayOutputStream,
prependXmlProlog: Boolean): Boolean {
val headerLength = if (!prependXmlProlog) 0 else XML_PROLOG.size + lineSeparator.separatorBytes.size
if (result.length.toInt() != (headerLength + content.size())) {
return false
}
val oldContent = result.contentsToByteArray()
if (prependXmlProlog && (!ArrayUtil.startsWith(oldContent, XML_PROLOG) ||
!ArrayUtil.startsWith(oldContent, XML_PROLOG.size, lineSeparator.separatorBytes))) {
return false
}
return (headerLength until oldContent.size).all { oldContent[it] == content.internalBuffer[it - headerLength] }
}
private fun doWrite(requestor: StorageManagerFileWriteRequestor, file: VirtualFile, dataWriterOrByteArray: Any, lineSeparator: LineSeparator, prependXmlProlog: Boolean) {
LOG.debug { "Save ${file.presentableUrl}" }
if (!file.isWritable) {
// may be element is not long-lived, so, we must write it to byte array
val byteArray = when (dataWriterOrByteArray) {
is DataWriter -> dataWriterOrByteArray.toBufferExposingByteArray(lineSeparator)
else -> dataWriterOrByteArray as BufferExposingByteArrayOutputStream
}
throw ReadOnlyModificationException(file, object : SaveSession {
override fun save() {
doWrite(requestor, file, byteArray, lineSeparator, prependXmlProlog)
}
})
}
runAsWriteActionIfNeeded {
file.getOutputStream(requestor).use { output ->
if (prependXmlProlog) {
output.write(XML_PROLOG)
output.write(lineSeparator.separatorBytes)
}
if (dataWriterOrByteArray is DataWriter) {
dataWriterOrByteArray.write(output, lineSeparator.separatorString)
}
else {
(dataWriterOrByteArray as BufferExposingByteArrayOutputStream).writeTo(output)
}
}
}
}
internal fun detectLineSeparators(chars: CharSequence, defaultSeparator: LineSeparator? = null): LineSeparator {
for (c in chars) {
if (c == '\r') {
return LineSeparator.CRLF
}
else if (c == '\n') {
// if we are here, there was no \r before
return LineSeparator.LF
}
}
return defaultSeparator ?: LineSeparator.getSystemLineSeparator()
}
private fun deleteFile(file: Path, requestor: StorageManagerFileWriteRequestor, virtualFile: VirtualFile?) {
if (virtualFile == null) {
try {
Files.delete(file)
}
catch (ignored: NoSuchFileException) {
}
}
else if (virtualFile.exists()) {
if (virtualFile.isWritable) {
virtualFile.delete(requestor)
}
else {
throw ReadOnlyModificationException(virtualFile, object : SaveSession {
override fun save() {
// caller must wraps into undo transparent and write action
virtualFile.delete(requestor)
}
})
}
}
}
internal class ReadOnlyModificationException(val file: VirtualFile, val session: SaveSession?) : RuntimeException("File is read-only: $file")
private data class BlockSaving(@NonNls val reason: String)
|
apache-2.0
|
6af9ee1c443659f20efe79fc0e78598b
| 34.160804 | 170 | 0.687987 | 4.956784 | false | false | false | false |
webianks/BlueChat
|
app/src/main/java/com/webianks/bluechat/Constants.kt
|
1
|
564
|
package com.webianks.bluechat
/**
* Created by ramankit on 20/7/17.
*/
class Constants{
companion object {
// Message types sent from the BluetoothChatService Handler
val MESSAGE_STATE_CHANGE = 1
val MESSAGE_READ = 2
val MESSAGE_WRITE = 3
val MESSAGE_DEVICE_NAME = 4
val MESSAGE_TOAST = 5
var MESSAGE_TYPE_SENT = 0
var MESSAGE_TYPE_RECEIVED = 1
// Key names received from the BluetoothChatService Handler
val DEVICE_NAME = "device_name"
val TOAST = "toast"
}
}
|
mit
|
01d24ba0deb53d8addf0912cd514106c
| 21.6 | 67 | 0.615248 | 4.147059 | false | false | false | false |
leesocrates/remind
|
app/src/main/java/com/lee/socrates/remind/fragment/LoginFragment.kt
|
1
|
2398
|
package com.lee.socrates.remind.fragment
import android.app.Activity
import android.app.ProgressDialog
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.lee.library.util.Constant
import com.lee.socrates.remind.R
import com.lee.socrates.remind.entity.User
import com.lee.socrates.remind.util.*
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_login.*
import java.util.HashMap
/**
* Created by socrates on 2016/4/4.
*/
@Route(path = "/remain/fragment/login")
class LoginFragment : AppBaseFragment() {
override fun getLayoutId(): Int {
return R.layout.fragment_login
}
override fun initView() {
btnLogin.setOnClickListener {
if (!inputEmail.text.toString().validateUserName(context)) {
return@setOnClickListener
}
if (!inputPassword.text.toString().validatePassword(context)) {
return@setOnClickListener
}
login()
}
linkSignUp.setOnClickListener {
ARouter.getInstance().navigation(activity, "register", "", 0, Constant.materialActivityContainer)
}
}
fun login() {
val progressDialog = ProgressDialog(activity,
R.style.AppTheme_Dark_Dialog)
progressDialog.isIndeterminate = true
progressDialog.setMessage("Login...")
progressDialog.show()
val hashMap = HashMap<String, Any?>()
val userName = inputEmail.text.toString()
hashMap.put("userName", userName)
hashMap.put("password", inputPassword.text.toString())
retrofitService.login(hashMap)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
progressDialog.dismiss()
context.showToast(it.message)
if (it.isSuccess){
val user: User = User()
user.userAccount = userName
UserInfoManager.addUser(user)
activity.setResult(Activity.RESULT_OK)
activity.finish()
}
}, { progressDialog.dismiss() })
}
}
|
gpl-3.0
|
570c2d9811e2ed6563fa5e8decfa213c
| 34.791045 | 109 | 0.61176 | 4.924025 | false | false | false | false |
JakeWharton/dex-method-list
|
diffuse/src/main/kotlin/com/jakewharton/diffuse/TypeDescriptor.kt
|
1
|
1147
|
package com.jakewharton.diffuse
inline class TypeDescriptor(val value: String) : Comparable<TypeDescriptor> {
override fun compareTo(other: TypeDescriptor): Int {
return sourceName.compareTo(other.sourceName)
}
val sourceName get() = value.toHumanName()
val simpleName get() = sourceName.substringAfterLast('.')
val arrayArity get() = value.indexOfFirst { it != '[' }
val componentDescriptor get() = TypeDescriptor(value.substring(arrayArity))
fun asArray(arity: Int = 1) = TypeDescriptor("[".repeat(arity) + value)
override fun toString() = sourceName
companion object {
private fun String.toHumanName(): String {
if (startsWith("[")) {
return substring(1).toHumanName() + "[]"
}
if (startsWith("L")) {
return substring(1, length - 1).replace('/', '.')
}
return when (this) {
"B" -> "byte"
"C" -> "char"
"D" -> "double"
"F" -> "float"
"I" -> "int"
"J" -> "long"
"S" -> "short"
"V" -> "void"
"Z" -> "boolean"
else -> throw IllegalArgumentException("Unknown type $this")
}
}
}
}
|
apache-2.0
|
e7d6fe487b4587c621219955c7062b30
| 28.410256 | 77 | 0.582389 | 4.01049 | false | false | false | false |
sandy-8925/Checklist
|
app/src/main/java/org/sanpra/checklist/activity/ChecklistItemRecyclerAdapter.kt
|
1
|
4276
|
/*
* Copyright (C) 2011-2018 Sandeep Raghuraman ([email protected])
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sanpra.checklist.activity
import android.annotation.SuppressLint
import android.text.Spannable
import android.text.SpannableString
import android.text.style.StrikethroughSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.UiThread
import androidx.core.text.toSpannable
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import org.apache.commons.lang3.StringUtils
import org.sanpra.checklist.R
import org.sanpra.checklist.databinding.ItemRowBinding
import org.sanpra.checklist.dbhelper.ChecklistItem
internal class ChecklistItemRecyclerAdapter @UiThread
constructor() : ListAdapter<ChecklistItem, ChecklistItemViewHolder>(ChecklistDiffCallback()) {
internal var itemClickListener: View.OnClickListener? = null
internal var itemLongClickListener: View.OnLongClickListener? = null
init {
setHasStableIds(true)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChecklistItemViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = ItemRowBinding.inflate(inflater, parent, false)
return ChecklistItemViewHolder(binding)
}
private val strikethroughSpan = StrikethroughSpan()
override fun onBindViewHolder(holder: ChecklistItemViewHolder, position: Int) {
val item = getItem(position)
holder.binding.item = item
if(item.isChecked)
holder.binding.itemtext.text = SpannableString(item.description).apply {
setSpan(strikethroughSpan, 0, length, Spannable.SPAN_INCLUSIVE_INCLUSIVE)
}
else holder.binding.itemtext.text.toSpannable().removeSpan(strikethroughSpan)
holder.itemView.apply {
setTag(VIEWHOLDER_TAG, getItemId(position))
setOnClickListener(itemClickListener)
setOnLongClickListener(itemLongClickListener)
}
}
override fun getItemId(position: Int) = getItem(position).id
internal abstract class ItemClickListener : View.OnClickListener {
override fun onClick(v: View) {
val itemId = v.getTag(VIEWHOLDER_TAG) as Long
onClick(v, itemId)
}
internal abstract fun onClick(view: View, itemId: Long)
}
internal abstract class ItemLongClickListener : View.OnLongClickListener {
internal abstract fun onLongClick(view: View, itemId: Long)
override fun onLongClick(v: View): Boolean {
val itemId = v.getTag(VIEWHOLDER_TAG) as Long
onLongClick(v, itemId)
return true
}
}
companion object {
private const val VIEWHOLDER_TAG = R.id.CursorItemId
}
}
/**
* Used to hold a reference to the TextView containing the text in a row
*/
internal class ChecklistItemViewHolder(val binding: ItemRowBinding) : RecyclerView.ViewHolder(binding.root)
private class ChecklistDiffCallback : DiffUtil.ItemCallback<ChecklistItem>() {
@SuppressLint("DiffUtilEquals")
override fun areContentsTheSame(oldItem: ChecklistItem, newItem: ChecklistItem): Boolean {
if(oldItem == newItem) return true
return oldItem.isChecked == newItem.isChecked && StringUtils.equals(oldItem.description, newItem.description)
}
override fun areItemsTheSame(oldItem: ChecklistItem, newItem: ChecklistItem): Boolean {
if(oldItem == newItem) return true
return oldItem.id == newItem.id
}
}
|
gpl-3.0
|
7040c145034ddb4cd8f1f2d6a90d4f83
| 37.531532 | 117 | 0.732928 | 4.870159 | false | false | false | false |
timakden/advent-of-code
|
src/main/kotlin/ru/timakden/aoc/year2015/day07/Puzzle.kt
|
1
|
2794
|
package ru.timakden.aoc.year2015.day07
import ru.timakden.aoc.util.isLetter
import ru.timakden.aoc.util.isNumber
import ru.timakden.aoc.util.measure
import kotlin.time.ExperimentalTime
@ExperimentalTime
fun main() {
measure {
println("a = ${solve(input, listOf("a"))["a"]}")
}
}
fun solve(input: List<String>, wiresToReturn: List<String>): Map<String, UShort> {
val map = mutableMapOf<String, UShort>()
while (map.size != input.size) {
input.forEach {
val expressions = it.split("\\s->\\s".toRegex())
val leftPart = expressions[0].split("\\s(?!or|and|lshift|rshift)".toRegex())
when (leftPart.size) {
1 -> {
// example: 44430 -> b
if (leftPart[0].isNumber()) {
map[expressions[1]] = leftPart[0].toUShort()
} else if (leftPart[0].isLetter()) {
map[leftPart[0]]?.let { value -> map[expressions[1]] = value }
}
}
2 -> {
// example: NOT di -> dj
if (leftPart[1].isNumber()) {
map[expressions[1]] = leftPart[1].toUShort().inv()
} else if (leftPart[1].isLetter()) {
map[leftPart[1]]?.let { value -> map[expressions[1]] = value.inv() }
}
}
3 -> {
// example: dd OR do -> dp
var val1: UShort? = null
var val2: UShort? = null
if (leftPart[0].isNumber()) {
val1 = leftPart[0].toUShort()
} else if (leftPart[0].isLetter()) {
val1 = map[leftPart[0]]
}
if (leftPart[2].isNumber()) {
val2 = leftPart[2].toUShort()
} else if (leftPart[2].isLetter()) {
val2 = map[leftPart[2]]
}
if (val1 != null && val2 != null) {
when (leftPart[1]) {
"AND" -> map[expressions[1]] = val1 and val2
"OR" -> map[expressions[1]] = val1 or val2
"LSHIFT" -> map[expressions[1]] = val1 shl val2
"RSHIFT" -> map[expressions[1]] = val1 shr val2
}
}
}
}
}
}
return map.filter { it.key in wiresToReturn }
}
private infix fun UShort.shl(shift: UShort): UShort = (this.toInt() shl shift.toInt()).toUShort()
private infix fun UShort.shr(shift: UShort): UShort = (this.toInt() shr shift.toInt()).toUShort()
|
apache-2.0
|
b3c4490f15f5e8bcc7b6a47a6dc8e6b1
| 36.756757 | 97 | 0.442019 | 4.305085 | false | false | false | false |
spinnaker/kork
|
kork-plugins/src/test/kotlin/com/netflix/spinnaker/kork/version/ServiceVersionTest.kt
|
3
|
2180
|
/*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.kork.version
import dev.minutest.junit.JUnit5Minutests
import dev.minutest.rootContext
import io.mockk.every
import io.mockk.mockk
import org.springframework.context.ApplicationContext
import strikt.api.expectThat
import strikt.assertions.isEqualTo
class ServiceVersionTest : JUnit5Minutests {
fun tests() = rootContext {
derivedContext<KnownVersionFixture>("Known version test") {
fixture {
KnownVersionFixture()
}
test("should resolve to known version") {
expectThat(subject.resolve()).isEqualTo("1.0.0")
}
}
derivedContext<UnKnownVersionFixture>("Unknown version test") {
fixture {
UnKnownVersionFixture()
}
test("should resolve to unknown version") {
expectThat(subject.resolve()).isEqualTo(ServiceVersion.UNKNOWN_VERSION)
}
}
}
private inner class KnownVersionFixture {
val applicationContext: ApplicationContext = mockk(relaxed = true)
val resolver: VersionResolver = mockk(relaxed = true)
val subject = ServiceVersion(applicationContext, listOf(resolver))
init {
every { applicationContext.applicationName } returns "test"
every { resolver.resolve("test") } returns "1.0.0"
}
}
private inner class UnKnownVersionFixture {
val applicationContext: ApplicationContext = mockk(relaxed = true)
val resolver: VersionResolver = mockk(relaxed = true)
val subject = ServiceVersion(applicationContext, listOf(resolver))
init {
every { resolver.resolve("test") } returns null
}
}
}
|
apache-2.0
|
37fe368dddbd60b10e586efa02b99345
| 29.704225 | 79 | 0.716514 | 4.467213 | false | true | false | false |
BlueBoxWare/LibGDXPlugin
|
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/inspections/kotlin/KotlinMissingFlushInspection.kt
|
1
|
3745
|
/*
* Copyright 2016 Blue Box Ware
*
* 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.gmail.blueboxware.libgdxplugin.inspections.kotlin
import com.gmail.blueboxware.libgdxplugin.message
import com.gmail.blueboxware.libgdxplugin.utils.findClass
import com.gmail.blueboxware.libgdxplugin.utils.resolveCallToStrings
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import com.intellij.psi.search.searches.ClassInheritorsSearch
import org.jetbrains.kotlin.idea.base.utils.fqname.getKotlinFqName
import org.jetbrains.kotlin.psi.*
class KotlinMissingFlushInspection : LibGDXKotlinBaseInspection() {
override fun getStaticDescription() = message("missing.flush.html.description")
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : KtVisitorVoid() {
override fun visitBlockExpression(expression: KtBlockExpression) {
super.visitBlockExpression(expression)
if (
expression.parent !is KtNamedFunction
&& expression.parent !is KtClassInitializer
&& expression.parent !is KtFunctionLiteral
) return
val methodChecker = MissingFlushInspectionMethodChecker(getPreferenceSubClasses(holder.project))
expression.accept(methodChecker)
methodChecker.lastPreferenceChange?.let { lastPreferenceChange ->
if (holder.results.none { it.psiElement == lastPreferenceChange }) {
holder.registerProblem(lastPreferenceChange, message("missing.flush.problem.descriptor"))
}
}
}
}
companion object {
private var preferencesSubClasses: Collection<PsiClass>? = null
private fun getPreferenceSubClasses(project: Project): Collection<PsiClass> {
if (preferencesSubClasses == null) {
val preferenceClass = project.findClass("com.badlogic.gdx.Preferences")
@Suppress("LiftReturnOrAssignment")
if (preferenceClass != null) {
val cs = ClassInheritorsSearch.search(preferenceClass).findAll().toMutableSet()
cs.add(preferenceClass)
preferencesSubClasses = cs
} else {
preferencesSubClasses = listOf()
}
}
return preferencesSubClasses ?: listOf()
}
}
}
private class MissingFlushInspectionMethodChecker(
val preferencesSubClasses: Collection<PsiClass>
) : KtTreeVisitorVoid() {
var lastPreferenceChange: KtElement? = null
override fun visitQualifiedExpression(expression: KtQualifiedExpression) {
val (className, methodName) = expression.resolveCallToStrings() ?: return
for (subClass in preferencesSubClasses) {
if (subClass.getKotlinFqName()?.asString() == className) {
if (methodName.startsWith("put") || methodName == "remove") {
lastPreferenceChange = expression
} else if (methodName == "flush") {
lastPreferenceChange = null
}
}
}
}
}
|
apache-2.0
|
1863cb5ed7c1f9642d73d49b96666f84
| 35.009615 | 109 | 0.670761 | 5.223152 | false | false | false | false |
osfans/trime
|
app/src/main/java/com/osfans/trime/data/db/clipboard/ClipboardHelper.kt
|
1
|
4921
|
package com.osfans.trime.data.db.clipboard
import android.content.ClipboardManager
import android.content.Context
import androidx.room.Room
import com.osfans.trime.data.AppPrefs
import com.osfans.trime.data.db.Database
import com.osfans.trime.data.db.DatabaseBean
import com.osfans.trime.data.db.DatabaseDao
import com.osfans.trime.util.StringUtils.mismatch
import com.osfans.trime.util.StringUtils.replace
import com.osfans.trime.util.WeakHashSet
import com.osfans.trime.util.clipboardManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import timber.log.Timber
object ClipboardHelper :
ClipboardManager.OnPrimaryClipChangedListener,
CoroutineScope by CoroutineScope(SupervisorJob() + Dispatchers.Default) {
private lateinit var clbDb: Database
private lateinit var clbDao: DatabaseDao
fun interface OnClipboardUpdateListener {
fun onUpdate(text: String)
}
private val mutex = Mutex()
var itemCount: Int = 0
private set
private suspend fun updateItemCount() {
itemCount = clbDao.itemCount()
}
private val onUpdateListeners = WeakHashSet<OnClipboardUpdateListener>()
fun addOnUpdateListener(listener: OnClipboardUpdateListener) {
onUpdateListeners.add(listener)
}
fun removeOnUpdateListener(listener: OnClipboardUpdateListener) {
onUpdateListeners.remove(listener)
}
private val limit get() = AppPrefs.defaultInstance().other.clipboardLimit.toInt()
private val compare get() = AppPrefs.defaultInstance().other.clipboardCompareRules
private val output get() = AppPrefs.defaultInstance().other.clipboardOutputRules
var lastBean: DatabaseBean? = null
fun init(context: Context) {
clipboardManager.addPrimaryClipChangedListener(this)
clbDb = Room
.databaseBuilder(context, Database::class.java, "clipboard.db")
.addMigrations(Database.MIGRATION_3_4)
.build()
clbDao = clbDb.databaseDao()
launch { updateItemCount() }
}
suspend fun get(id: Int) = clbDao.get(id)
suspend fun getAll() = clbDao.getAll()
suspend fun pin(id: Int) = clbDao.updatePinned(id, true)
suspend fun unpin(id: Int) = clbDao.updatePinned(id, false)
suspend fun delete(id: Int) {
clbDao.delete(id)
updateItemCount()
}
suspend fun deleteAll(skipUnpinned: Boolean = true) {
if (skipUnpinned) {
clbDao.deleteAllUnpinned()
} else {
clbDao.deleteAll()
}
}
/**
* 此方法设置监听剪贴板变化,如有新的剪贴内容,就启动选定的剪贴板管理器
*
* - [compare] 比较规则。每次通知剪贴板管理器,都会保存 ClipBoardCompare 处理过的 string。
* 如果两次处理过的内容不变,则不通知。
*
* - [output] 输出规则。如果剪贴板内容与规则匹配,则不通知剪贴板管理器。
*/
override fun onPrimaryClipChanged() {
if (!(limit != 0 && this::clbDao.isInitialized)) {
return
}
clipboardManager
.primaryClip
?.let { DatabaseBean.fromClipData(it) }
?.takeIf {
it.text!!.isNotBlank() &&
it.text.mismatch(output.toTypedArray())
}
?.let { b ->
if (b.text!!.replace(compare.toTypedArray()).isEmpty()) return
Timber.d("Accept clipboard $b")
launch {
mutex.withLock {
val all = clbDao.getAll()
var pinned = false
all.find { b.text == it.text }?.let {
clbDao.delete(it.id)
pinned = it.pinned
}
val rowId = clbDao.insert(b.copy(pinned = pinned))
removeOutdated()
updateItemCount()
clbDao.get(rowId)?.let { newBean ->
lastBean = newBean
onUpdateListeners.forEach { listener ->
listener.onUpdate(newBean.text ?: "")
}
}
}
}
}
}
private suspend fun removeOutdated() {
val all = clbDao.getAll()
if (all.size > limit) {
val outdated = all
.map {
if (it.pinned) it.copy(id = Int.MAX_VALUE)
else it
}
.sortedBy { it.id }
.subList(0, all.size - limit)
clbDao.delete(outdated)
}
}
}
|
gpl-3.0
|
8f9ba5ace35abc462af7f4440c8e1f08
| 32.161972 | 86 | 0.589722 | 4.396825 | false | false | false | false |
google/private-compute-libraries
|
javatests/com/google/android/libraries/pcc/chronicle/samples/util/ChronicleHelperTest.kt
|
1
|
8535
|
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.libraries.pcc.chronicle.samples.util
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.android.libraries.pcc.chronicle.api.Connection
import com.google.android.libraries.pcc.chronicle.api.ConnectionRequest
import com.google.android.libraries.pcc.chronicle.api.DataType
import com.google.android.libraries.pcc.chronicle.api.DataTypeDescriptor
import com.google.android.libraries.pcc.chronicle.api.ManagedDataType
import com.google.android.libraries.pcc.chronicle.api.ManagementStrategy
import com.google.android.libraries.pcc.chronicle.api.ProcessorNode
import com.google.android.libraries.pcc.chronicle.api.StorageMedia
import com.google.android.libraries.pcc.chronicle.api.flags.Flags
import com.google.android.libraries.pcc.chronicle.api.policy.Policy
import com.google.android.libraries.pcc.chronicle.api.remote.ICancellationSignal
import com.google.android.libraries.pcc.chronicle.api.remote.IRemote
import com.google.android.libraries.pcc.chronicle.api.remote.IResponseCallback
import com.google.android.libraries.pcc.chronicle.api.remote.RemoteError
import com.google.android.libraries.pcc.chronicle.api.remote.RemoteRequest
import com.google.android.libraries.pcc.chronicle.api.remote.RemoteRequestMetadata
import com.google.android.libraries.pcc.chronicle.api.remote.RemoteResponse
import com.google.android.libraries.pcc.chronicle.api.remote.StoreRequest
import com.google.android.libraries.pcc.chronicle.api.remote.serialization.ProtoSerializer
import com.google.android.libraries.pcc.chronicle.api.remote.serialization.Serializer
import com.google.android.libraries.pcc.chronicle.api.remote.server.RemoteStoreServer
import com.google.android.libraries.pcc.chronicle.api.storage.WrappedEntity
import com.google.android.libraries.pcc.chronicle.samples.datahub.peopleproto.PERSON_GENERATED_DTD
import com.google.android.libraries.pcc.chronicle.samples.datahub.peopleproto.PeopleReader
import com.google.android.libraries.pcc.chronicle.samples.datahub.peopleproto.PeopleWriter
import com.google.android.libraries.pcc.chronicle.samples.datahub.peopleproto.Person
import com.google.android.libraries.pcc.chronicle.samples.policy.peopleproto.PEOPLE_PROTO_POLICY
import com.google.protobuf.Empty
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.spy
import com.nhaarman.mockitokotlin2.verify
import java.time.Duration
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.test.assertFails
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.suspendCancellableCoroutine
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class ChronicleHelperTest {
private val reader = PeopleReaderImpl()
private val writer = PeopleWriterImpl()
private val readerSpy = spy(reader)
private val writerSpy = spy(writer)
private val peopleServer = spy(PeopleServer())
private val connectionProviders = setOf(peopleServer)
private val servers = setOf(peopleServer)
private val policies = setOf(PEOPLE_PROTO_POLICY)
private val helper = ChronicleHelper(policies, connectionProviders, servers)
@Test
fun getChronicle_returnsWorkingChronicle(): Unit = runBlocking {
val chronicle = helper.chronicle
val processorNode =
object : ProcessorNode {
override val requiredConnectionTypes = setOf(PeopleReader::class.java)
}
val connection =
chronicle.getConnectionOrThrow(
ConnectionRequest(PeopleReader::class.java, processorNode, PEOPLE_PROTO_POLICY)
)
connection.fetchAll()
verify(readerSpy).fetchAll()
}
@Test
fun setFlags_updatesFlagsInChronicle(): Unit = runBlocking {
val chronicle = helper.chronicle
val processorNode =
object : ProcessorNode {
override val requiredConnectionTypes = setOf(PeopleReader::class.java)
}
helper.setFlags(Flags(failNewConnections = true))
assertFails {
chronicle.getConnectionOrThrow(
ConnectionRequest(PeopleReader::class.java, processorNode, PEOPLE_PROTO_POLICY)
)
}
}
@Test
fun createRemoteConnectionBinder_createsWorkingRemoteRouter() {
// Arrange:
// Have a ChronicleHelper create a remote connection binder, and prepare a "count" remote
// request for the Person data type.
val helper =
ChronicleHelper(
policies = setOf(PEOPLE_PROTO_POLICY),
connectionProviders = emptySet(),
remoteServers = setOf(peopleServer)
)
val binder: IRemote =
helper.createRemoteConnectionBinder(
ApplicationProvider.getApplicationContext(),
CoroutineScope(SupervisorJob())
)
val request =
RemoteRequest(
RemoteRequestMetadata.newBuilder()
.setStore(
StoreRequest.newBuilder()
.setCount(Empty.getDefaultInstance())
.setDataTypeName(PERSON_GENERATED_DTD.name)
.build()
)
.setUsageType(PEOPLE_PROTO_POLICY.name)
.build()
)
runBlocking {
// Act:
// Call binder.serve, and suspend the coroutine until the callback's onComplete is triggered.
suspendCancellableCoroutine { cont ->
val callback =
object : IResponseCallback.Stub() {
override fun onData(data: RemoteResponse?) = Unit
override fun provideCancellationSignal(signal: ICancellationSignal?) = Unit
override fun onError(error: RemoteError?) {
cont.resumeWithException(error!!)
}
override fun onComplete() {
cont.resume(Unit)
}
}
binder.serve(request, callback)
}
// Assert:
// Assert that the IBinder returned from the helper actually called-through to the
// peopleServer's `count` method in response to the request we sent it.
verify(peopleServer).count(any())
}
}
open inner class PeopleServer : RemoteStoreServer<Person> {
override val dataType: DataType =
ManagedDataType(
PERSON_GENERATED_DTD,
ManagementStrategy.Stored(false, StorageMedia.MEMORY, Duration.ofHours(5)),
setOf(
PeopleReader::class.java,
PeopleWriter::class.java,
)
)
override val dataTypeDescriptor: DataTypeDescriptor = dataType.descriptor
override val serializer: Serializer<Person> =
ProtoSerializer.createFrom(Person.getDefaultInstance())
override fun getConnection(connectionRequest: ConnectionRequest<out Connection>): Connection {
return when (connectionRequest.connectionType) {
PeopleReader::class.java -> readerSpy
PeopleWriter::class.java -> writerSpy
else -> throw IllegalArgumentException()
}
}
override suspend fun count(policy: Policy?): Int = 42
override fun fetchById(policy: Policy?, ids: List<String>): Flow<List<WrappedEntity<Person>>> =
emptyFlow()
override fun fetchAll(policy: Policy?): Flow<List<WrappedEntity<Person>>> = emptyFlow()
override suspend fun create(policy: Policy?, wrappedEntities: List<WrappedEntity<Person>>) =
Unit
override suspend fun update(policy: Policy?, wrappedEntities: List<WrappedEntity<Person>>) =
Unit
override suspend fun deleteAll(policy: Policy?) = Unit
override suspend fun deleteById(policy: Policy?, ids: List<String>) = Unit
}
open class PeopleReaderImpl : PeopleReader {
override suspend fun fetchAll(): List<Person> = emptyList()
}
open class PeopleWriterImpl : PeopleWriter {
override suspend fun putPerson(person: Person) = Unit
override suspend fun deletePerson(name: String) = Unit
override suspend fun deleteAll() = Unit
}
}
|
apache-2.0
|
0a71d5ce2c87c22466efc5bc88eb1b40
| 39.450237 | 99 | 0.745636 | 4.53748 | false | false | false | false |
elect86/modern-jogl-examples
|
src/main/kotlin/glNext/tut11/phongLighting.kt
|
2
|
11639
|
package glNext.tut11
import com.jogamp.newt.event.KeyEvent
import com.jogamp.newt.event.MouseEvent
import com.jogamp.opengl.GL2ES3.*
import com.jogamp.opengl.GL3
import glNext.*
import glm.f
import glm.vec._3.Vec3
import glm.vec._4.Vec4
import glm.quat.Quat
import glm.mat.Mat4
import main.framework.Framework
import main.framework.Semantic
import main.framework.component.Mesh
import uno.buffer.intBufferBig
import uno.glm.MatrixStack
import uno.mousePole.*
import uno.time.Timer
import glm.glm
import uno.buffer.destroy
import uno.glsl.programOf
/**
* Created by GBarbieri on 24.03.2017.
*/
fun main(args: Array<String>) {
PhongLighting_Next().setup("Tutorial 11 - Fragment Attenuation")
}
class PhongLighting_Next : Framework() {
lateinit var whiteNoPhong: ProgramData
lateinit var colorNoPhong: ProgramData
lateinit var whitePhong: ProgramData
lateinit var colorPhong: ProgramData
lateinit var whitePhongOnly: ProgramData
lateinit var colorPhongOnly: ProgramData
lateinit var unlit: UnlitProgData
val initialViewData = ViewData(
Vec3(0.0f, 0.5f, 0.0f),
Quat(0.92387953f, 0.3826834f, 0.0f, 0.0f),
5.0f,
0.0f)
val viewScale = ViewScale(
3.0f, 20.0f,
1.5f, 0.5f,
0.0f, 0.0f, //No camera movement.
90.0f / 250.0f)
val initialObjectData = ObjectData(
Vec3(0.0f, 0.5f, 0.0f),
Quat(1.0f, 0.0f, 0.0f, 0.0f))
val viewPole = ViewPole(initialViewData, viewScale, MouseEvent.BUTTON1)
val objectPole = ObjectPole(initialObjectData, 90.0f / 250.0f, MouseEvent.BUTTON3, viewPole)
lateinit var cylinder: Mesh
lateinit var plane: Mesh
lateinit var cube: Mesh
var lightModel = LightingModel.DiffuseAndSpecular
var drawColoredCyl = false
var drawLightSource = false
var scaleCyl = false
var drawDark = false
var lightHeight = 1.5f
var lightRadius = 1.0f
val lightAttenuation = 1.2f
var shininessFactor = 4.0f
val darkColor = Vec4(0.2f, 0.2f, 0.2f, 1.0f)
val lightColor = Vec4(1.0f)
val lightTimer = Timer(Timer.Type.Loop, 5.0f)
val projectionUniformBuffer = intBufferBig(1)
override fun init(gl: GL3) = with(gl) {
initializePrograms(gl)
cylinder = Mesh(gl, javaClass, "tut11/UnitCylinder.xml")
plane = Mesh(gl, javaClass, "tut11/LargePlane.xml")
cube = Mesh(gl, javaClass, "tut11/UnitCube.xml")
cullFace {
enable()
cullFace = back
frontFace = cw
}
depth {
test = true
mask = true
func = lEqual
range = 0.0 .. 1.0
clamp = true
}
initUniformBuffer(projectionUniformBuffer) {
data(Mat4.SIZE, GL_DYNAMIC_DRAW)
//Bind the static buffers.
range(Semantic.Uniform.PROJECTION, 0, Mat4.SIZE)
}
}
fun initializePrograms(gl: GL3) {
whiteNoPhong = ProgramData(gl, "pn.vert", "no-phong.frag")
colorNoPhong = ProgramData(gl, "pcn.vert", "no-phong.frag")
whitePhong = ProgramData(gl, "pn.vert", "phong-lighting.frag")
colorPhong = ProgramData(gl, "pcn.vert", "phong-lighting.frag")
whitePhongOnly = ProgramData(gl, "pn.vert", "phong-only.frag")
colorPhongOnly = ProgramData(gl, "pcn.vert", "phong-only.frag")
unlit = UnlitProgData(gl, "pos-transform.vert", "uniform-color.frag")
}
override fun display(gl: GL3) = with(gl) {
lightTimer.update()
clear {
color(0)
depth()
}
val modelMatrix = MatrixStack()
modelMatrix.setMatrix(viewPole.calcMatrix())
val worldLightPos = calcLightPosition()
val lightPosCameraSpace = modelMatrix.top() * worldLightPos
val (whiteProg, colorProg) = when (lightModel) {
LightingModel.PureDiffuse -> Pair(whiteNoPhong, colorNoPhong)
LightingModel.DiffuseAndSpecular -> Pair(whitePhong, colorPhong)
LightingModel.SpecularOnly -> Pair(whitePhongOnly, colorPhongOnly)
}
usingProgram(whiteProg.theProgram) {
glUniform4f(whiteProg.lightIntensityUnif, 0.8f, 0.8f, 0.8f, 1.0f)
glUniform4f(whiteProg.ambientIntensityUnif, 0.2f, 0.2f, 0.2f, 1.0f)
glUniform3f(whiteProg.cameraSpaceLightPosUnif, lightPosCameraSpace)
glUniform1f(whiteProg.lightAttenuationUnif, lightAttenuation)
glUniform1f(whiteProg.shininessFactorUnif, shininessFactor)
glUniform4f(whiteProg.baseDiffuseColorUnif, if (drawDark) darkColor else lightColor)
name = colorProg.theProgram
glUniform4f(colorProg.lightIntensityUnif, 0.8f, 0.8f, 0.8f, 1.0f)
glUniform4f(colorProg.ambientIntensityUnif, 0.2f, 0.2f, 0.2f, 1.0f)
glUniform3f(colorProg.cameraSpaceLightPosUnif, lightPosCameraSpace)
glUniform1f(colorProg.lightAttenuationUnif, lightAttenuation)
glUniform1f(colorProg.shininessFactorUnif, shininessFactor)
}
modelMatrix run {
//Render the ground plane.
run {
val normMatrix = top().toMat3()
normMatrix.inverse_().transpose_()
usingProgram(whiteProg.theProgram) {
whiteProg.modelToCameraMatrixUnif.mat4 = top()
glUniformMatrix3f(whiteProg.normalModelToCameraMatrixUnif, normMatrix)
plane.render(gl)
}
}
//Render the Cylinder
run {
applyMatrix(objectPole.calcMatrix())
if (scaleCyl)
scale(1.0f, 1.0f, 0.2f)
val normMatrix = top().toMat3()
normMatrix.inverse_().transpose_()
val prog = if (drawColoredCyl) colorProg else whiteProg
usingProgram(prog.theProgram) {
prog.modelToCameraMatrixUnif.mat4 = top()
glUniformMatrix3f(prog.normalModelToCameraMatrixUnif, normMatrix)
cylinder.render(gl, if (drawColoredCyl) "lit-color" else "lit")
}
}
//Render the light
if (drawLightSource)
run {
translate(worldLightPos)
scale(0.1f)
usingProgram(unlit.theProgram) {
unlit.modelToCameraMatrixUnif.mat4 = top()
glUniform4f(unlit.objectColorUnif, 0.8078f, 0.8706f, 0.9922f, 1.0f)
cube.render(gl, "flat")
}
}
}
}
fun calcLightPosition(): Vec4 {
val currentTimeThroughLoop = lightTimer.getAlpha()
val ret = Vec4(0.0f, lightHeight, 0.0f, 1.0f)
ret.x = glm.cos(currentTimeThroughLoop * (glm.PIf * 2.0f)) * lightRadius
ret.z = glm.sin(currentTimeThroughLoop * (glm.PIf * 2.0f)) * lightRadius
return ret
}
override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) {
val zNear = 1.0f
val zFar = 1_000f
val perspMatrix = MatrixStack()
val proj = perspMatrix.perspective(45.0f, w.f / h, zNear, zFar).top()
withUniformBuffer(projectionUniformBuffer) { subData(proj) }
glViewport(w, h)
}
override fun mousePressed(e: MouseEvent) {
viewPole.mousePressed(e)
objectPole.mousePressed(e)
}
override fun mouseDragged(e: MouseEvent) {
viewPole.mouseDragged(e)
objectPole.mouseDragged(e)
}
override fun mouseReleased(e: MouseEvent) {
viewPole.mouseReleased(e)
objectPole.mouseReleased(e)
}
override fun mouseWheelMoved(e: MouseEvent) {
viewPole.mouseWheel(e)
}
override fun keyPressed(e: KeyEvent) {
var changedShininess = false
when (e.keyCode) {
KeyEvent.VK_ESCAPE -> quit()
KeyEvent.VK_SPACE -> drawColoredCyl = !drawColoredCyl
KeyEvent.VK_I -> lightHeight += if (e.isShiftDown) 0.05f else 0.2f
KeyEvent.VK_K -> lightHeight -= if (e.isShiftDown) 0.05f else 0.2f
KeyEvent.VK_L -> lightRadius += if (e.isShiftDown) 0.05f else 0.2f
KeyEvent.VK_J -> lightRadius -= if (e.isShiftDown) 0.05f else 0.2f
KeyEvent.VK_O -> {
shininessFactor += if (e.isShiftDown) 0.1f else 0.5f
changedShininess = true
}
KeyEvent.VK_U -> {
shininessFactor -= if (e.isShiftDown) 0.1f else 0.5f
changedShininess = true
}
KeyEvent.VK_Y -> drawLightSource = !drawLightSource
KeyEvent.VK_T -> scaleCyl = !scaleCyl
KeyEvent.VK_B -> lightTimer.togglePause()
KeyEvent.VK_G -> drawDark = !drawDark
KeyEvent.VK_H -> {
lightModel += if (e.isShiftDown) -1 else +1
println(lightModel)
}
}
if (lightRadius < 0.2f)
lightRadius = 0.2f
if (shininessFactor < 0.0f)
shininessFactor = 0.0001f
if (changedShininess)
println("Shiny: $shininessFactor")
}
override fun end(gl: GL3) = with(gl) {
glDeletePrograms(whiteNoPhong.theProgram, colorNoPhong.theProgram, whitePhong.theProgram, colorPhong.theProgram,
whitePhongOnly.theProgram, colorPhongOnly.theProgram, unlit.theProgram)
glDeleteBuffer(projectionUniformBuffer)
cylinder.dispose(gl)
plane.dispose(gl)
cube.dispose(gl)
projectionUniformBuffer.destroy()
}
enum class LightingModel {
PureDiffuse,
DiffuseAndSpecular,
SpecularOnly;
operator fun plus(i: Int) = values()[(this.ordinal + i + values().size) % values().size]
}
inner class ProgramData(gl: GL3, vertex: String, fragment: String) {
val theProgram = programOf(gl, javaClass, "tut11", vertex, fragment)
val modelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "modelToCameraMatrix")
val lightIntensityUnif = gl.glGetUniformLocation(theProgram, "lightIntensity")
val ambientIntensityUnif = gl.glGetUniformLocation(theProgram, "ambientIntensity")
val normalModelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "normalModelToCameraMatrix")
val cameraSpaceLightPosUnif = gl.glGetUniformLocation(theProgram, "cameraSpaceLightPos")
val lightAttenuationUnif = gl.glGetUniformLocation(theProgram, "lightAttenuation")
val shininessFactorUnif = gl.glGetUniformLocation(theProgram, "shininessFactor")
val baseDiffuseColorUnif = gl.glGetUniformLocation(theProgram, "baseDiffuseColor")
init {
gl.glUniformBlockBinding(
theProgram,
gl.glGetUniformBlockIndex(theProgram, "Projection"),
Semantic.Uniform.PROJECTION)
}
}
inner class UnlitProgData(gl: GL3, vertex: String, fragment: String) {
val theProgram = programOf(gl, javaClass, "tut11", vertex, fragment)
val objectColorUnif = gl.glGetUniformLocation(theProgram, "objectColor")
val modelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "modelToCameraMatrix")
init {
gl.glUniformBlockBinding(
theProgram,
gl.glGetUniformBlockIndex(theProgram, "Projection"),
Semantic.Uniform.PROJECTION)
}
}
}
|
mit
|
f5051b93602e65530ce380e8cbccc26e
| 30.630435 | 120 | 0.611908 | 4.078136 | false | false | false | false |
nickthecoder/tickle
|
tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/util/Polar2d.kt
|
1
|
1537
|
/*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle.util
data class Polar2d(val angle: Angle = Angle(), var magnitude: Double = 0.0) {
constructor(polar: Polar2d) : this(Angle.radians(polar.angle.radians), polar.magnitude)
fun vector() = angle.vector().mul(magnitude)
override fun toString() = "${angle.degrees}:${magnitude}"
fun lerp(other: Polar2d, t: Double): Polar2d {
return lerp(other, t, this)
}
fun lerp(other: Polar2d, t: Double, dest: Polar2d): Polar2d {
dest.angle.radians = angle.radians * (1 - t) + other.angle.radians * t
dest.magnitude = magnitude * (1 - t) + other.magnitude * t
return dest
}
companion object {
fun fromString(string: String): Polar2d {
val split = string.split(":")
return Polar2d(Angle.degrees(split[0].toDouble()), split[1].toDouble())
}
}
}
|
gpl-3.0
|
f90ba801ccea51a88915fcf2c8157a50
| 31.702128 | 91 | 0.689655 | 3.795062 | false | false | false | false |
ethauvin/kobalt
|
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/maven/aether/ConsoleTransferListener.kt
|
2
|
4462
|
package com.beust.kobalt.maven.aether
import com.beust.kobalt.misc.KobaltLogger
import com.beust.kobalt.misc.kobaltLog
import org.eclipse.aether.transfer.AbstractTransferListener
import org.eclipse.aether.transfer.MetadataNotFoundException
import org.eclipse.aether.transfer.TransferEvent
import org.eclipse.aether.transfer.TransferResource
import java.io.PrintStream
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.util.*
import java.util.concurrent.ConcurrentHashMap
class ConsoleTransferListener @JvmOverloads constructor(out: PrintStream? = null) : AbstractTransferListener() {
private val out: PrintStream
private val downloads = ConcurrentHashMap<TransferResource, Long>()
private var lastLength: Int = 0
init {
this.out = out ?: System.out
}
override fun transferInitiated(event: TransferEvent?) {
val message = if (event!!.requestType == TransferEvent.RequestType.PUT) "Uploading" else "Downloading"
kobaltLog(2, message + ": " + event.resource.repositoryUrl + event.resource.resourceName)
}
val PROPERTY_NO_ANIMATIONS = "com.beust.kobalt.noAnimations"
override fun transferProgressed(event: TransferEvent?) {
// Not on a terminal: don't display the progress
if (System.console() == null || System.getProperty(PROPERTY_NO_ANIMATIONS) != null) return
val resource = event!!.resource
downloads.put(resource, java.lang.Long.valueOf(event.transferredBytes))
val buffer = StringBuilder(64)
for (entry in downloads.entries) {
val total = entry.key.contentLength
val complete = entry.value
buffer.append(getStatus(complete, total)).append(" ")
}
val pad = lastLength - buffer.length
lastLength = buffer.length
pad(buffer, pad)
buffer.append('\r')
out.print(buffer)
}
private fun getStatus(complete: Long, total: Long): String {
if (total >= 1024) {
return toKB(complete).toString() + "/" + toKB(total) + " KB "
} else if (total >= 0) {
return complete.toString() + "/" + total + " B "
} else if (complete >= 1024) {
return toKB(complete).toString() + " KB "
} else {
return complete.toString() + " B "
}
}
private fun pad(buffer: StringBuilder, spaces: Int) {
var spaces = spaces
val block = " "
while (spaces > 0) {
val n = Math.min(spaces, block.length)
buffer.append(block, 0, n)
spaces -= n
}
}
override fun transferSucceeded(event: TransferEvent) {
transferCompleted(event)
val resource = event.resource
val contentLength = event.transferredBytes
if (contentLength >= 0) {
val type = if (event.requestType == TransferEvent.RequestType.PUT) "Uploaded" else "Downloaded"
val len = if (contentLength >= 1024) toKB(contentLength).toString() + " KB"
else contentLength.toString() + " B"
var throughput = ""
val duration = System.currentTimeMillis() - resource.transferStartTime
if (duration > 0) {
val bytes = contentLength - resource.resumeOffset
val format = DecimalFormat("0.0", DecimalFormatSymbols(Locale.ENGLISH))
val kbPerSec = bytes / 1024.0 / (duration / 1000.0)
throughput = " at " + format.format(kbPerSec) + " KB/sec"
}
kobaltLog(2, type + ": " + resource.repositoryUrl + resource.resourceName + " (" + len
+ throughput + ")")
}
}
override fun transferFailed(event: TransferEvent) {
transferCompleted(event)
if (event.exception !is MetadataNotFoundException) {
if (KobaltLogger.LOG_LEVEL > 2) {
Exceptions.printStackTrace(event.exception)
}
}
}
private fun transferCompleted(event: TransferEvent) {
downloads.remove(event.resource)
val buffer = StringBuilder(64)
pad(buffer, lastLength)
buffer.append('\r')
out.print(buffer)
}
override fun transferCorrupted(event: TransferEvent?) {
Exceptions.printStackTrace(event!!.exception)
}
fun toKB(bytes: Long): Long {
return (bytes + 1023) / 1024
}
}
|
apache-2.0
|
e13021957e92579b3cfb82b9f07e5be0
| 32.548872 | 112 | 0.616988 | 4.57641 | false | false | false | false |
coil-kt/coil
|
coil-base/src/androidTest/java/coil/fetch/ResourceUriFetcherTest.kt
|
1
|
4459
|
package coil.fetch
import android.content.ContentResolver.SCHEME_ANDROID_RESOURCE
import android.content.Context
import android.graphics.drawable.BitmapDrawable
import android.os.Build.VERSION.SDK_INT
import androidx.core.graphics.drawable.toBitmap
import androidx.core.net.toUri
import androidx.test.core.app.ApplicationProvider
import coil.ImageLoader
import coil.base.test.R
import coil.map.ResourceIntMapper
import coil.map.ResourceUriMapper
import coil.request.Options
import coil.size.Size
import coil.util.ViewTestActivity
import coil.util.assertIsSimilarTo
import coil.util.assumeTrue
import coil.util.getDrawableCompat
import coil.util.launchActivity
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
@OptIn(ExperimentalCoroutinesApi::class)
class ResourceUriFetcherTest {
private lateinit var context: Context
private lateinit var fetcherFactory: ResourceUriFetcher.Factory
@Before
fun before() {
context = ApplicationProvider.getApplicationContext()
fetcherFactory = ResourceUriFetcher.Factory()
}
@Test
fun rasterDrawable() = runTest {
val uri = "$SCHEME_ANDROID_RESOURCE://${context.packageName}/${R.drawable.normal}".toUri()
val options = Options(context, size = Size(100, 100))
val result = fetcherFactory.create(uri, options, ImageLoader(context))?.fetch()
assertTrue(result is SourceResult)
assertEquals("image/jpeg", result.mimeType)
assertFalse(result.source.source().exhausted())
}
@Test
fun vectorDrawable() = runTest {
val uri = "$SCHEME_ANDROID_RESOURCE://${context.packageName}/${R.drawable.ic_android}".toUri()
val options = Options(context, size = Size(100, 100))
val result = fetcherFactory.create(uri, options, ImageLoader(context))?.fetch()
assertTrue(result is DrawableResult)
assertTrue(result.drawable is BitmapDrawable)
assertTrue(result.isSampled)
}
@Test
fun externalPackageRasterDrawable() = runTest {
// https://android.googlesource.com/platform/packages/apps/Settings/+/master/res/drawable-xhdpi
val resource = if (SDK_INT >= 23) "msg_bubble_incoming" else "ic_power_system"
val rawUri = "$SCHEME_ANDROID_RESOURCE://com.android.settings/drawable/$resource".toUri()
val options = Options(context, size = Size(100, 100))
val uri = assertNotNull(ResourceUriMapper().map(rawUri, options))
val result = fetcherFactory.create(uri, options, ImageLoader(context))?.fetch()
assertTrue(result is SourceResult)
assertEquals("image/png", result.mimeType)
assertFalse(result.source.source().exhausted())
}
@Test
fun externalPackageVectorDrawable() = runTest {
// com.android.settings/drawable/ic_cancel was added in API 23.
assumeTrue(SDK_INT >= 23)
// https://android.googlesource.com/platform/packages/apps/Settings/+/master/res/drawable/ic_cancel.xml
val rawUri = "$SCHEME_ANDROID_RESOURCE://com.android.settings/drawable/ic_cancel".toUri()
val options = Options(context, size = Size(100, 100))
val uri = assertNotNull(ResourceUriMapper().map(rawUri, options))
val result = fetcherFactory.create(uri, options, ImageLoader(context))?.fetch()
assertTrue(result is DrawableResult)
assertTrue(result.drawable is BitmapDrawable)
assertTrue(result.isSampled)
}
/** Regression test: https://github.com/coil-kt/coil/issues/469 */
@Test
fun colorAttributeIsApplied() = launchActivity { activity: ViewTestActivity ->
// Intentionally use the application context.
val imageLoader = ImageLoader(context.applicationContext)
val options = Options(context = activity, size = Size.ORIGINAL)
val result = runBlocking {
val uri = assertNotNull(ResourceIntMapper().map(R.drawable.ic_tinted_vector, options))
fetcherFactory.create(uri, options, imageLoader)?.fetch()
}
val expected = activity.getDrawableCompat(R.drawable.ic_tinted_vector).toBitmap()
val actual = (result as DrawableResult).drawable.toBitmap()
actual.assertIsSimilarTo(expected)
}
}
|
apache-2.0
|
78877f3e0c90855b72a7ce23954762f1
| 39.908257 | 111 | 0.721462 | 4.485915 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.