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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Senspark/ee-x | src/android/facebook_ads/src/main/java/com/ee/internal/FacebookRewardedAd.kt | 1 | 5281 | package com.ee.internal
import android.app.Activity
import androidx.annotation.AnyThread
import androidx.annotation.UiThread
import com.ee.IFullScreenAd
import com.ee.ILogger
import com.ee.IMessageBridge
import com.ee.Thread
import com.ee.Utils
import com.facebook.ads.Ad
import com.facebook.ads.AdError
import com.facebook.ads.RewardedVideoAd
import com.facebook.ads.RewardedVideoAdListener
import kotlinx.serialization.Serializable
import java.util.concurrent.atomic.AtomicBoolean
/**
* Created by Zinge on 10/11/17.
*/
internal class FacebookRewardedAd(
private val _bridge: IMessageBridge,
private val _logger: ILogger,
private var _activity: Activity?,
private val _adId: String)
: IFullScreenAd, RewardedVideoAdListener {
@Serializable
@Suppress("unused")
private class ErrorResponse(
val code: Int,
val message: String
)
companion object {
private val kTag = FacebookRewardedAd::class.java.name
}
private val _messageHelper = MessageHelper("FacebookRewardedAd", _adId)
private val _helper = FullScreenAdHelper(_bridge, this, _messageHelper)
private val _isLoaded = AtomicBoolean(false)
private var _displaying = false
private var _rewarded = false
private var _ad: RewardedVideoAd? = null
init {
_logger.info("$kTag: constructor: adId = $_adId")
registerHandlers()
}
override fun onCreate(activity: Activity) {
_activity = activity
}
override fun onResume() {
}
override fun onPause() {
}
override fun onDestroy() {
_activity = null
}
override fun destroy() {
_logger.info("$kTag: ${this::destroy.name}: adId = $_adId")
deregisterHandlers()
destroyInternalAd()
}
@AnyThread
private fun registerHandlers() {
_helper.registerHandlers()
}
@AnyThread
private fun deregisterHandlers() {
_helper.deregisterHandlers()
}
@UiThread
private fun createInternalAd(): RewardedVideoAd {
_ad?.let {
return@createInternalAd it
}
val ad = RewardedVideoAd(_activity, _adId)
_ad = ad
return ad
}
@AnyThread
private fun destroyInternalAd() {
Thread.runOnMainThread {
val ad = _ad ?: return@runOnMainThread
ad.destroy()
_ad = null
}
}
override val isLoaded: Boolean
@AnyThread get() = _isLoaded.get()
@AnyThread
override fun load() {
Thread.runOnMainThread {
_logger.debug("$kTag: ${this::load.name}: id = $_adId")
val ad = createInternalAd()
ad.loadAd(ad.buildLoadAdConfig()
.withFailOnCacheFailureEnabled(true)
.withAdListener(this)
.build())
}
}
@AnyThread
override fun show() {
Thread.runOnMainThread {
_logger.debug("$kTag: ${this::show.name}: id = $_adId")
val ad = createInternalAd()
_displaying = true
_rewarded = false
val result = ad.show(ad.buildShowAdConfig().build())
if (result) {
// OK.
_isLoaded.set(false)
} else {
destroyInternalAd()
_bridge.callCpp(_messageHelper.onFailedToShow, ErrorResponse(-1, "Failed to show ad").serialize())
}
}
}
override fun onError(ad: Ad, error: AdError) {
Thread.runOnMainThread {
_logger.debug("$kTag: ${this::onError.name}: id = $_adId message = ${error.errorMessage}")
destroyInternalAd()
if (_displaying) {
_displaying = false
_isLoaded.set(false)
_bridge.callCpp(_messageHelper.onFailedToShow, ErrorResponse(error.errorCode, error.errorMessage).serialize())
} else {
_bridge.callCpp(_messageHelper.onFailedToLoad, ErrorResponse(error.errorCode, error.errorMessage).serialize())
}
}
}
override fun onAdLoaded(ad: Ad) {
Thread.runOnMainThread {
_logger.debug("$kTag: ${this::onAdLoaded.name}: id = $_adId")
_isLoaded.set(true)
_bridge.callCpp(_messageHelper.onLoaded)
}
}
override fun onLoggingImpression(ad: Ad) {
Thread.runOnMainThread {
_logger.debug("$kTag: ${this::onLoggingImpression.name}: id = $_adId")
}
}
override fun onAdClicked(ad: Ad) {
Thread.runOnMainThread {
_logger.debug("$kTag: ${this::onAdClicked.name}: id = $_adId")
_bridge.callCpp(_messageHelper.onClicked)
}
}
override fun onRewardedVideoCompleted() {
Thread.runOnMainThread {
_logger.debug("$kTag: ${this::onRewardedVideoCompleted.name}: id = $_adId")
_rewarded = true
}
}
override fun onRewardedVideoClosed() {
Thread.runOnMainThread {
_logger.debug("$kTag: ${this::onRewardedVideoClosed.name}: id = $_adId")
_displaying = false
_isLoaded.set(false)
destroyInternalAd()
_bridge.callCpp(_messageHelper.onClosed, Utils.toString(_rewarded))
}
}
} | mit | 35744c68d50bbe850baabac0755d8c1b | 27.863388 | 126 | 0.595721 | 4.505973 | false | false | false | false |
jk1/youtrack-idea-plugin | src/test/kotlin/com/github/jk1/ytplugin/SetupConnectionTrait.kt | 1 | 1581 | package com.github.jk1.ytplugin
import com.github.jk1.ytplugin.tasks.YouTrackServer
import com.intellij.openapi.project.Project
import com.intellij.tasks.TaskManager
import com.intellij.tasks.impl.TaskManagerImpl
import com.intellij.tasks.youtrack.YouTrackRepository
import com.intellij.tasks.youtrack.YouTrackRepositoryType
interface SetupConnectionTrait: IdeaProjectTrait, YouTrackConnectionTrait {
val project: Project
fun getTaskManagerComponent() = TaskManager.getManager(project)!! as TaskManagerImpl
fun createYouTrackRepository(url: String, token: String, shareUrl: Boolean = false,
useProxy: Boolean = false, useHTTP: Boolean = false, loginAnon: Boolean = false): YouTrackServer {
val repository = YouTrackRepository(YouTrackRepositoryType())
repository.url = url
repository.username = username
repository.password = token
repository.defaultSearch = ""
repository.isShared = shareUrl
repository.isUseProxy = useProxy
repository.isUseHttpAuthentication = useHTTP
repository.isLoginAnonymously = loginAnon
getTaskManagerComponent().setRepositories(listOf(repository))
//todo: mock YouTrack server here to break dependency from task-core
return YouTrackServer(repository, project)
}
fun cleanUpTaskManager(){
val taskManager = getTaskManagerComponent()
readAction {
taskManager.localTasks.forEach { taskManager.removeTask(it) }
}
taskManager.setRepositories(listOf())
}
} | apache-2.0 | 7548702512c7c18a0170307b325356be | 38.55 | 131 | 0.727388 | 5.083601 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/inventory/items/ItemsFragment.kt | 2 | 3484 | package com.habitrpg.android.habitica.ui.fragments.inventory.items
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.databinding.FragmentViewpagerBinding
import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment
class ItemsFragment : BaseMainFragment<FragmentViewpagerBinding>() {
override var binding: FragmentViewpagerBinding? = null
override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentViewpagerBinding {
return FragmentViewpagerBinding.inflate(inflater, container, false)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
this.usesTabLayout = true
this.hidesToolbar = true
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding?.viewPager?.currentItem = 0
setViewPagerAdapter()
arguments?.let {
val args = ItemsFragmentArgs.fromBundle(it)
binding?.viewPager?.currentItem = when (args.itemType) {
"hatchingPotions" -> 1
"food" -> 2
"quests" -> 3
"special" -> 4
else -> 0
}
}
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
private fun setViewPagerAdapter() {
val fragmentManager = childFragmentManager
binding?.viewPager?.adapter = object : FragmentStateAdapter(fragmentManager, lifecycle) {
override fun createFragment(position: Int): androidx.fragment.app.Fragment {
val fragment = ItemRecyclerFragment()
fragment.itemType = when (position) {
0 -> "eggs"
1 -> "hatchingPotions"
2 -> "food"
3 -> "quests"
4 -> "special"
else -> ""
}
fragment.itemTypeText =
if (position == 4 && isAdded) getString(R.string.special_items)
else getPageTitle(position)
return fragment
}
override fun getItemCount(): Int {
return 5
}
}
tabLayout?.let {
binding?.viewPager?.let { it1 ->
TabLayoutMediator(it, it1) { tab, position ->
tab.text = getPageTitle(position)
}.attach()
}
}
tabLayout?.tabMode = TabLayout.MODE_SCROLLABLE
}
private fun getPageTitle(position: Int): String {
return when (position) {
0 -> activity?.getString(R.string.eggs)
1 -> activity?.getString(R.string.hatching_potions)
2 -> activity?.getString(R.string.food)
3 -> activity?.getString(R.string.quests)
4 -> activity?.getString(R.string.special)
else -> ""
} ?: ""
}
}
| gpl-3.0 | e56c0651a3fecba2495d8a4a9521f624 | 33.156863 | 107 | 0.603617 | 5.231231 | false | false | false | false |
yzbzz/beautifullife | app/src/main/java/com/ddu/ui/fragment/study/ui/BezierViewFragment.kt | 2 | 4656 | package com.ddu.ui.fragment.study.ui
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.graphics.PointF
import android.util.Log
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.FrameLayout
import com.ddu.R
import com.ddu.icore.bezier.QuadraticPointFTypeEvaluator
import com.ddu.icore.ui.fragment.DefaultFragment
import com.ddu.icore.ui.widget.MoveButton
import com.iannotation.IElement
import kotlinx.android.synthetic.main.study_bezier.*
/**
* Created by yzbzz on 2018/6/8.
*/
@IElement("customer")
class BezierViewFragment : DefaultFragment() {
override fun getLayoutId(): Int {
return R.layout.study_bezier
}
override fun initView() {
btn_shake.setOnClickListener {
startBezier()
}
}
private fun startBezier() {
val displayMetrics = resources.displayMetrics
val width = displayMetrics.widthPixels
val height = displayMetrics.heightPixels
val mAnimCoinWidth = btn_start.width
val mAnimCoinHeight = btn_start.height
val start = IntArray(2)
btn_start.getLocationInWindow(start)
start[0] = btn_start.x.toInt()
start[1] = btn_start.y.toInt()
val control = IntArray(2)
btn_control.getLocationInWindow(control)
control[0] = btn_control.x.toInt() + btn_control.width / 2
control[1] = btn_control.y.toInt() + btn_control.height / 2
val end = IntArray(2)
btn_end.getLocationInWindow(end)
end[0] = btn_end.x.toInt()
end[1] = btn_end.y.toInt()
val button = MoveButton(mContext)
val layoutParams = FrameLayout.LayoutParams(btn_start.width, btn_start.height)
button.layoutParams = layoutParams
button.x = start[0].toFloat()
button.y = start[1].toFloat()
// button.x = width / 2f - mAnimCoinWidth / 2f
// button.y = height / 2f - mAnimCoinHeight / 2f
rl_root.addView(button)
val startP = PointF()
val endP = PointF()
val controlP = PointF()
startP.x = start[0].toFloat()
startP.y = start[1].toFloat()
endP.x = end[0].toFloat()
endP.y = end[1].toFloat()
controlP.x = control[0].toFloat()
controlP.y = control[1].toFloat()
// startP.x = btn_start.x
// startP.y = btn_start.y
// startP.x = width / 2f - mAnimCoinWidth / 2f
// startP.y = height / 2f - mAnimCoinHeight / 2f
// endP.x = btn_end.x
// endP.y = btn_end.y
// endP.x = end[0] + width / 2f - mAnimCoinWidth / 2f
// endP.y = end[1] + height / 2f - mAnimCoinHeight / 2f
//
// controlP.x = (end[0] - mAnimCoinWidth).toFloat()
// controlP.y = (startP.y - endP.y) / 2
Log.v("lhz", "startP: $startP")
Log.v("lhz", "startP: $controlP")
Log.v("lhz", "startP: $endP")
val objectAnimator =
ObjectAnimator.ofObject(button, "mPointF", QuadraticPointFTypeEvaluator(controlP), startP, endP)
// objectAnimator.addListener(object : Animator.AnimatorListener {
// override fun onAnimationRepeat(animation: Animator?) {
// }
//
// override fun onAnimationEnd(animation: Animator?) {
// rl_root.removeView(button)
// }
//
// override fun onAnimationCancel(animation: Animator?) {
// }
//
// override fun onAnimationStart(animation: Animator?) {
// }
//
// })
// objectAnimator.start()
// val valueAnimator = ValueAnimator.ofObject(PointFTypeEvaluator(controlP), startP, endP)
// valueAnimator.addUpdateListener {
// val point = it.animatedValue as PointF
// button.x = point.x
// button.y = point.y
// }
val objectAnimator2 = ObjectAnimator.ofFloat(button, "scaleX", 1f, 0f)
val objectAnimator3 = ObjectAnimator.ofFloat(button, "scaleY", 1f, 0f)
val animatorSet = AnimatorSet()
animatorSet.playTogether(objectAnimator, objectAnimator2, objectAnimator3)
animatorSet.interpolator = AccelerateDecelerateInterpolator()
animatorSet.duration = 700
animatorSet.startDelay = (100 * 1).toLong()
animatorSet.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
super.onAnimationEnd(animation)
rl_root.removeView(button)
}
})
animatorSet.start()
}
}
| apache-2.0 | 398b22f7dbd0490d7ddaa41d688dcc55 | 31.559441 | 108 | 0.622637 | 3.959184 | false | false | false | false |
androidx/androidx | room/room-compiler/src/test/test-data/kotlinCodeGen/pojoRowAdapter_customTypeConverter.kt | 3 | 2973 | import android.database.Cursor
import androidx.room.EntityInsertionAdapter
import androidx.room.RoomDatabase
import androidx.room.RoomSQLiteQuery
import androidx.room.RoomSQLiteQuery.Companion.acquire
import androidx.room.util.getColumnIndexOrThrow
import androidx.room.util.query
import androidx.sqlite.db.SupportSQLiteStatement
import java.lang.Class
import javax.`annotation`.processing.Generated
import kotlin.Int
import kotlin.String
import kotlin.Suppress
import kotlin.Unit
import kotlin.collections.List
import kotlin.jvm.JvmStatic
@Generated(value = ["androidx.room.RoomProcessor"])
@Suppress(names = ["UNCHECKED_CAST", "DEPRECATION"])
public class MyDao_Impl(
__db: RoomDatabase,
) : MyDao {
private val __db: RoomDatabase
private val __insertionAdapterOfMyEntity: EntityInsertionAdapter<MyEntity>
private val __fooConverter: FooConverter = FooConverter()
init {
this.__db = __db
this.__insertionAdapterOfMyEntity = object : EntityInsertionAdapter<MyEntity>(__db) {
public override fun createQuery(): String =
"INSERT OR ABORT INTO `MyEntity` (`pk`,`foo`) VALUES (?,?)"
public override fun bind(statement: SupportSQLiteStatement, entity: MyEntity): Unit {
statement.bindLong(1, entity.pk.toLong())
val _tmp: String = __fooConverter.toString(entity.foo)
statement.bindString(2, _tmp)
}
}
}
public override fun addEntity(item: MyEntity): Unit {
__db.assertNotSuspendingTransaction()
__db.beginTransaction()
try {
__insertionAdapterOfMyEntity.insert(item)
__db.setTransactionSuccessful()
} finally {
__db.endTransaction()
}
}
public override fun getEntity(): MyEntity {
val _sql: String = "SELECT * FROM MyEntity"
val _statement: RoomSQLiteQuery = acquire(_sql, 0)
__db.assertNotSuspendingTransaction()
val _cursor: Cursor = query(__db, _statement, false, null)
try {
val _cursorIndexOfPk: Int = getColumnIndexOrThrow(_cursor, "pk")
val _cursorIndexOfFoo: Int = getColumnIndexOrThrow(_cursor, "foo")
val _result: MyEntity
if (_cursor.moveToFirst()) {
val _tmpPk: Int
_tmpPk = _cursor.getInt(_cursorIndexOfPk)
val _tmpFoo: Foo
val _tmp: String
_tmp = _cursor.getString(_cursorIndexOfFoo)
_tmpFoo = __fooConverter.fromString(_tmp)
_result = MyEntity(_tmpPk,_tmpFoo)
} else {
error("Cursor was empty, but expected a single item.")
}
return _result
} finally {
_cursor.close()
_statement.release()
}
}
public companion object {
@JvmStatic
public fun getRequiredConverters(): List<Class<*>> = emptyList()
}
} | apache-2.0 | 484e52557bffeb88cf8c40ee8200cf5f | 34.404762 | 97 | 0.625631 | 4.734076 | false | false | false | false |
MoonlightOwl/Yui | src/main/kotlin/totoro/yui/actions/LuckyAction.kt | 1 | 797 | package totoro.yui.actions
import totoro.yui.client.Command
import totoro.yui.client.IRCClient
import totoro.yui.util.Dict
import totoro.yui.util.F
class LuckyAction : SensitivityAction("islucky", "lucky") {
override fun handle(client: IRCClient, command: Command): Boolean {
val value = command.args.firstOrNull()
val text = value?.let { lucky(it) } ?: F.Gray + "gimme something to estimate" + F.Reset
client.send(command.chan, text)
return true
}
private fun sum(value: String) = value.fold(0) { acc, ch -> acc + ch.toInt() }
private fun lucky(value: String): String {
val half = value.length / 2
val success = sum(value.dropLast(half)) == sum(value.drop(half))
return if (success) Dict.Yeah() else Dict.Nope()
}
}
| mit | 7db8a482151def989a8efa3805f61e54 | 33.652174 | 95 | 0.65872 | 3.558036 | false | false | false | false |
androidx/androidx | core/core-ktx/src/main/java/androidx/core/util/Range.kt | 3 | 2208 | /*
* 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.
*/
@file:SuppressLint("ClassVerificationFailure") // Entire file is RequiresApi(21)
@file:Suppress("NOTHING_TO_INLINE") // Aliases to public API.
package androidx.core.util
import android.annotation.SuppressLint
import android.util.Range
import androidx.annotation.RequiresApi
/**
* Creates a range from this [Comparable] value to [that].
*
* @throws IllegalArgumentException if this value is comparatively smaller than [that].
*/
@RequiresApi(21)
public inline infix fun <T : Comparable<T>> T.rangeTo(that: T): Range<T> = Range(this, that)
/** Return the smallest range that includes this and [value]. */
@RequiresApi(21)
public inline operator fun <T : Comparable<T>> Range<T>.plus(value: T): Range<T> = extend(value)
/** Return the smallest range that includes this and [other]. */
@RequiresApi(21)
public inline operator fun <T : Comparable<T>> Range<T>.plus(other: Range<T>): Range<T> =
extend(other)
/**
* Return the intersection of this range and [other].
*
* @throws IllegalArgumentException if this is disjoint from [other].
*/
@RequiresApi(21)
public inline infix fun <T : Comparable<T>> Range<T>.and(other: Range<T>): Range<T> =
intersect(other)
/** Returns this [Range] as a [ClosedRange]. */
@RequiresApi(21)
public fun <T : Comparable<T>> Range<T>.toClosedRange(): ClosedRange<T> = object : ClosedRange<T> {
override val endInclusive get() = upper
override val start get() = lower
}
/** Returns this [ClosedRange] as a [Range]. */
@RequiresApi(21)
public fun <T : Comparable<T>> ClosedRange<T>.toRange(): Range<T> = Range(start, endInclusive)
| apache-2.0 | cd71746527e1ebf07a4ed7a5144e7017 | 35.196721 | 99 | 0.720109 | 3.767918 | false | false | false | false |
androidx/androidx | compose/runtime/runtime/src/commonMain/kotlin/androidx/compose/runtime/Composer.kt | 3 | 170500 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:OptIn(
InternalComposeApi::class,
)
package androidx.compose.runtime
import androidx.compose.runtime.Composer.Companion.equals
import androidx.compose.runtime.collection.IdentityArrayMap
import androidx.compose.runtime.collection.IdentityArraySet
import androidx.compose.runtime.external.kotlinx.collections.immutable.PersistentMap
import androidx.compose.runtime.external.kotlinx.collections.immutable.persistentHashMapOf
import androidx.compose.runtime.snapshots.currentSnapshot
import androidx.compose.runtime.snapshots.fastForEach
import androidx.compose.runtime.snapshots.fastForEachIndexed
import androidx.compose.runtime.snapshots.fastMap
import androidx.compose.runtime.snapshots.fastToSet
import androidx.compose.runtime.tooling.CompositionData
import androidx.compose.runtime.tooling.LocalInspectionTables
import kotlin.coroutines.CoroutineContext
internal typealias Change = (
applier: Applier<*>,
slots: SlotWriter,
rememberManager: RememberManager
) -> Unit
private class GroupInfo(
/**
* The current location of the slot relative to the start location of the pending slot changes
*/
var slotIndex: Int,
/**
* The current location of the first node relative the start location of the pending node
* changes
*/
var nodeIndex: Int,
/**
* The current number of nodes the group contains after changes have been applied
*/
var nodeCount: Int
)
/**
* An interface used during [ControlledComposition.applyChanges] and [Composition.dispose] to
* track when [RememberObserver] instances and leave the composition an also allows recording
* [SideEffect] calls.
*/
internal interface RememberManager {
/**
* The [RememberObserver] is being remembered by a slot in the slot table.
*/
fun remembering(instance: RememberObserver)
/**
* The [RememberObserver] is being forgotten by a slot in the slot table.
*/
fun forgetting(instance: RememberObserver)
/**
* The [effect] should be called when changes are being applied but after the remember/forget
* notifications are sent.
*/
fun sideEffect(effect: () -> Unit)
}
/**
* Pending starts when the key is different than expected indicating that the structure of the tree
* changed. It is used to determine how to update the nodes and the slot table when changes to the
* structure of the tree is detected.
*/
private class Pending(
val keyInfos: MutableList<KeyInfo>,
val startIndex: Int
) {
var groupIndex: Int = 0
init {
require(startIndex >= 0) { "Invalid start index" }
}
private val usedKeys = mutableListOf<KeyInfo>()
private val groupInfos = run {
var runningNodeIndex = 0
val result = hashMapOf<Int, GroupInfo>()
for (index in 0 until keyInfos.size) {
val keyInfo = keyInfos[index]
@OptIn(InternalComposeApi::class)
result[keyInfo.location] = GroupInfo(index, runningNodeIndex, keyInfo.nodes)
@OptIn(InternalComposeApi::class)
runningNodeIndex += keyInfo.nodes
}
result
}
/**
* A multi-map of keys from the previous composition. The keys can be retrieved in the order
* they were generated by the previous composition.
*/
val keyMap by lazy {
multiMap<Any, KeyInfo>().also {
for (index in 0 until keyInfos.size) {
val keyInfo = keyInfos[index]
@Suppress("ReplacePutWithAssignment")
it.put(keyInfo.joinedKey, keyInfo)
}
}
}
/**
* Get the next key information for the given key.
*/
fun getNext(key: Int, dataKey: Any?): KeyInfo? {
val joinedKey: Any = if (dataKey != null) JoinedKey(key, dataKey) else key
return keyMap.pop(joinedKey)
}
/**
* Record that this key info was generated.
*/
fun recordUsed(keyInfo: KeyInfo) = usedKeys.add(keyInfo)
val used: List<KeyInfo> get() = usedKeys
// TODO(chuckj): This is a correct but expensive implementation (worst cases of O(N^2)). Rework
// to O(N)
fun registerMoveSlot(from: Int, to: Int) {
if (from > to) {
groupInfos.values.forEach { group ->
val position = group.slotIndex
if (position == from) group.slotIndex = to
else if (position in to until from) group.slotIndex = position + 1
}
} else if (to > from) {
groupInfos.values.forEach { group ->
val position = group.slotIndex
if (position == from) group.slotIndex = to
else if (position in (from + 1) until to) group.slotIndex = position - 1
}
}
}
fun registerMoveNode(from: Int, to: Int, count: Int) {
if (from > to) {
groupInfos.values.forEach { group ->
val position = group.nodeIndex
if (position in from until from + count) group.nodeIndex = to + (position - from)
else if (position in to until from) group.nodeIndex = position + count
}
} else if (to > from) {
groupInfos.values.forEach { group ->
val position = group.nodeIndex
if (position in from until from + count) group.nodeIndex = to + (position - from)
else if (position in (from + 1) until to) group.nodeIndex = position - count
}
}
}
@OptIn(InternalComposeApi::class)
fun registerInsert(keyInfo: KeyInfo, insertIndex: Int) {
groupInfos[keyInfo.location] = GroupInfo(-1, insertIndex, 0)
}
fun updateNodeCount(group: Int, newCount: Int): Boolean {
val groupInfo = groupInfos[group]
if (groupInfo != null) {
val index = groupInfo.nodeIndex
val difference = newCount - groupInfo.nodeCount
groupInfo.nodeCount = newCount
if (difference != 0) {
groupInfos.values.forEach { childGroupInfo ->
if (childGroupInfo.nodeIndex >= index && childGroupInfo != groupInfo) {
val newIndex = childGroupInfo.nodeIndex + difference
if (newIndex >= 0)
childGroupInfo.nodeIndex = newIndex
}
}
}
return true
}
return false
}
@OptIn(InternalComposeApi::class)
fun slotPositionOf(keyInfo: KeyInfo) = groupInfos[keyInfo.location]?.slotIndex ?: -1
@OptIn(InternalComposeApi::class)
fun nodePositionOf(keyInfo: KeyInfo) = groupInfos[keyInfo.location]?.nodeIndex ?: -1
@OptIn(InternalComposeApi::class)
fun updatedNodeCountOf(keyInfo: KeyInfo) =
groupInfos[keyInfo.location]?.nodeCount ?: keyInfo.nodes
}
private class Invalidation(
/**
* The recompose scope being invalidate
*/
val scope: RecomposeScopeImpl,
/**
* The index of the group in the slot table being invalidated.
*/
val location: Int,
/**
* The instances invalidating the scope. If this is `null` or empty then the scope is
* unconditionally invalid. If it contains instances it is only invalid if at least on of the
* instances is changed. This is used to track `DerivedState<*>` changes and only treat the
* scope as invalid if the instance has changed.
*/
var instances: IdentityArraySet<Any>?
) {
fun isInvalid(): Boolean = scope.isInvalidFor(instances)
}
/**
* Internal compose compiler plugin API that is used to update the function the composer will
* call to recompose a recomposition scope. This should not be used or called directly.
*/
@ComposeCompilerApi
interface ScopeUpdateScope {
/**
* Called by generated code to update the recomposition scope with the function to call
* recompose the scope. This is called by code generated by the compose compiler plugin and
* should not be called directly.
*/
fun updateScope(block: (Composer, Int) -> Unit)
}
internal enum class InvalidationResult {
/**
* The invalidation was ignored because the associated recompose scope is no longer part of the
* composition or has yet to be entered in the composition. This could occur for invalidations
* called on scopes that are no longer part of composition or if the scope was invalidated
* before [ControlledComposition.applyChanges] was called that will enter the scope into the
* composition.
*/
IGNORED,
/**
* The composition is not currently composing and the invalidation was recorded for a future
* composition. A recomposition requested to be scheduled.
*/
SCHEDULED,
/**
* The composition that owns the recompose scope is actively composing but the scope has
* already been composed or is in the process of composing. The invalidation is treated as
* SCHEDULED above.
*/
DEFERRED,
/**
* The composition that owns the recompose scope is actively composing and the invalidated
* scope has not been composed yet but will be recomposed before the composition completes. A
* new recomposition was not scheduled for this invalidation.
*/
IMMINENT
}
/**
* An instance to hold a value provided by [CompositionLocalProvider] and is created by the
* [ProvidableCompositionLocal.provides] infixed operator. If [canOverride] is `false`, the
* provided value will not overwrite a potentially already existing value in the scope.
*/
class ProvidedValue<T> internal constructor(
val compositionLocal: CompositionLocal<T>,
val value: T,
val canOverride: Boolean
)
/**
* A [CompositionLocal] map is is an immutable map that maps [CompositionLocal] keys to a provider
* of their current value. It is used to represent the combined scope of all provided
* [CompositionLocal]s.
*/
internal typealias CompositionLocalMap = PersistentMap<CompositionLocal<Any?>, State<Any?>>
internal inline fun CompositionLocalMap.mutate(
mutator: (MutableMap<CompositionLocal<Any?>, State<Any?>>) -> Unit
): CompositionLocalMap = builder().apply(mutator).build()
@Suppress("UNCHECKED_CAST")
internal fun <T> CompositionLocalMap.contains(key: CompositionLocal<T>) =
this.containsKey(key as CompositionLocal<Any?>)
@Suppress("UNCHECKED_CAST")
internal fun <T> CompositionLocalMap.getValueOf(key: CompositionLocal<T>) =
this[key as CompositionLocal<Any?>]?.value as T
@Composable
private fun compositionLocalMapOf(
values: Array<out ProvidedValue<*>>,
parentScope: CompositionLocalMap
): CompositionLocalMap {
val result: CompositionLocalMap = persistentHashMapOf()
return result.mutate {
for (provided in values) {
if (provided.canOverride || !parentScope.contains(provided.compositionLocal)) {
@Suppress("UNCHECKED_CAST")
it[provided.compositionLocal as CompositionLocal<Any?>] =
provided.compositionLocal.provided(provided.value)
}
}
}
}
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* An instance used to track the identity of the movable content. Using a holder object allows
* creating unique movable content instances from the same instance of a lambda. This avoids
* using the identity of a lambda instance as it can be merged into a singleton or merged by later
* rewritings and using its identity might lead to unpredictable results that might change from the
* debug and release builds.
*/
@InternalComposeApi
class MovableContent<P>(val content: @Composable (parameter: P) -> Unit)
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* A reference to the movable content state prior to changes being applied.
*/
@InternalComposeApi
class MovableContentStateReference internal constructor(
internal val content: MovableContent<Any?>,
internal val parameter: Any?,
internal val composition: ControlledComposition,
internal val slotTable: SlotTable,
internal val anchor: Anchor,
internal val invalidations: List<Pair<RecomposeScopeImpl, IdentityArraySet<Any>?>>,
internal val locals: CompositionLocalMap
)
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* A reference to the state of a [MovableContent] after changes have being applied. This is the
* state that was removed from the `from` composition during [ControlledComposition.applyChanges]
* and before it is inserted during [ControlledComposition.insertMovableContent].
*/
@InternalComposeApi
class MovableContentState internal constructor(
internal val slotTable: SlotTable
)
/**
* Composer is the interface that is targeted by the Compose Kotlin compiler plugin and used by
* code generation helpers. It is highly recommended that direct calls these be avoided as the
* runtime assumes that the calls are generated by the compiler and contain only a minimum amount
* of state validation.
*/
sealed interface Composer {
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Changes calculated and recorded during composition and are sent to [applier] which makes
* the physical changes to the node tree implied by a composition.
*
* Composition has two discrete phases, 1) calculate and record changes and 2) making the
* changes via the [applier]. While a [Composable] functions is executing, none of the
* [applier] methods are called. The recorded changes are sent to the [applier] all at once
* after all [Composable] functions have completed.
*/
@ComposeCompilerApi
val applier: Applier<*>
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Reflects that a new part of the composition is being created, that is, the composition
* will insert new nodes into the resulting tree.
*/
@ComposeCompilerApi
val inserting: Boolean
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Reflects whether the [Composable] function can skip. Even if a [Composable] function is
* called with the same parameters it might still need to run because, for example, a new
* value was provided for a [CompositionLocal] created by [staticCompositionLocalOf].
*/
@ComposeCompilerApi
val skipping: Boolean
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Reflects whether the default parameter block of a [Composable] function is valid. This is
* `false` if a [State] object read in the [startDefaults] group was modified since the last
* time the [Composable] function was run.
*/
@ComposeCompilerApi
val defaultsInvalid: Boolean
/**
* A Compose internal property. DO NOT call directly. Use [currentRecomposeScope] instead.
*
* The invalidation current invalidation scope. An new invalidation scope is created whenever
* [startRestartGroup] is called. when this scope's [RecomposeScope.invalidate] is called
* then lambda supplied to [endRestartGroup]'s [ScopeUpdateScope] will be scheduled to be
* run.
*/
@InternalComposeApi
val recomposeScope: RecomposeScope?
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Return an object that can be used to uniquely identity of the current recomposition scope.
* This identity will be the same even if the recompose scope instance changes.
*
* This is used internally by tooling track composable function invocations.
*/
@ComposeCompilerApi
val recomposeScopeIdentity: Any?
/**
* A Compose internal property. DO NOT call directly. Use [currentCompositeKeyHash] instead.
*
* This a hash value used to coordinate map externally stored state to the composition. For
* example, this is used by saved instance state to preserve state across activity lifetime
* boundaries.
*
* This value is not likely to be unique but is not guaranteed unique. There are known cases,
* such as for loops without a [key], where the runtime does not have enough information to
* make the compound key hash unique.
*/
@InternalComposeApi
val compoundKeyHash: Int
// Groups
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Start a replacable group. A replacable group is a group that cannot be moved during
* execution and can only either inserted, removed, or replaced. For example, the group
* created by most control flow constructs such as an `if` statement are replacable groups.
*
* @param key A compiler generated key based on the source location of the call.
*/
@ComposeCompilerApi
fun startReplaceableGroup(key: Int)
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Called at the end of a replacable group.
*
* @see startRestartGroup
*/
@ComposeCompilerApi
fun endReplaceableGroup()
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Start a movable group. A movable group is one that can be moved based on the value of
* [dataKey] which is typically supplied by the [key][androidx.compose.runtime.key] pseudo
* compiler function.
*
* A movable group implements the semantics of [key][androidx.compose.runtime.key] which allows
* the state and nodes generated by a loop to move with the composition implied by the key
* passed to [key][androidx.compose.runtime.key].
* @param key A compiler generated key based on the source location of the call.
*/
@ComposeCompilerApi
fun startMovableGroup(key: Int, dataKey: Any?)
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Called at the end of a movable group.
*
* @see startMovableGroup
*/
@ComposeCompilerApi
fun endMovableGroup()
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Called to start the group that calculates the default parameters of a [Composable] function.
*
* This method is called near the beginning of a [Composable] function with default
* parameters and surrounds the remembered values or [Composable] calls necessary to produce
* the default parameters. For example, for `model: Model = remember { DefaultModel() }` the
* call to [remember] is called inside a [startDefaults] group.
*/
@ComposeCompilerApi
fun startDefaults()
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Called at the end of defaults group.
*
* @see startDefaults
*/
@ComposeCompilerApi
fun endDefaults()
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Called to record a group for a [Composable] function and starts a group that can be
* recomposed on demand based on the lambda passed to
* [updateScope][ScopeUpdateScope.updateScope] when [endRestartGroup] is called
*
* @param key A compiler generated key based on the source location of the call.
* @return the instance of the composer to use for the rest of the function.
*/
@ComposeCompilerApi
fun startRestartGroup(key: Int): Composer
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Called to end a restart group.
*/
@ComposeCompilerApi
fun endRestartGroup(): ScopeUpdateScope?
/**
* A Compose internal API. DO NOT call directly.
*
* Request movable content be inserted at the current location. This will schedule with the
* root composition parent a call to [insertMovableContent] with the correct
* [MovableContentState] if one was released in another part of composition.
*/
@InternalComposeApi
fun insertMovableContent(value: MovableContent<*>, parameter: Any?)
/**
* A Compose internal API. DO NOT call directly.
*
* Perform a late composition that adds to the current late apply that will insert the given
* references to [MovableContent] into the composition. If a [MovableContent] is paired
* then this is a request to move a released [MovableContent] from a different location or
* from a different composition. If it is not paired (i.e. the `second`
* [MovableContentStateReference] is `null`) then new state for the [MovableContent] is
* inserted into the composition.
*/
@InternalComposeApi
fun insertMovableContentReferences(
references: List<Pair<MovableContentStateReference, MovableContentStateReference?>>
)
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Record the source information string for a group. This must be immediately called after the
* start of a group.
*
* @param sourceInformation An string value to that provides the compose tools enough
* information to calculate the source location of calls to composable functions.
*/
fun sourceInformation(sourceInformation: String)
/**
* A compose compiler plugin API. DO NOT call directly.
*
* Record a source information marker. This marker can be used in place of a group that would
* have contained the information but was elided as the compiler plugin determined the group
* was not necessary such as when a function is marked with [ReadOnlyComposable].
*
* @param key A compiler generated key based on the source location of the call.
* @param sourceInformation An string value to that provides the compose tools enough
* information to calculate the source location of calls to composable functions.
*
*/
fun sourceInformationMarkerStart(key: Int, sourceInformation: String)
/**
* A compose compiler plugin API. DO NOT call directly.
*
* Record the end of the marked source information range.
*/
fun sourceInformationMarkerEnd()
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Skips the composer to the end of the current group. This generated by the compiler to when
* the body of a [Composable] function can be skipped typically because the parameters to the
* function are equal to the values passed to it in the previous composition.
*/
@ComposeCompilerApi
fun skipToGroupEnd()
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Deactivates the content to the end of the group by treating content as if it was deleted and
* replaces all slot table entries for calls to [cache] to be [Empty]. This must be called as
* the first call for a group.
*/
@ComposeCompilerApi
fun deactivateToEndGroup(changed: Boolean)
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Skips the current group. This called by the compiler to indicate that the current group
* can be skipped, for example, this is generated to skip the [startDefaults] group the
* default group is was not invalidated.
*/
@ComposeCompilerApi
fun skipCurrentGroup()
// Nodes
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Start a group that tracks a the code that will create or update a node that is generated
* as part of the tree implied by the composition.
*/
@ComposeCompilerApi
fun startNode()
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Start a group that tracks a the code that will create or update a node that is generated
* as part of the tree implied by the composition. A reusable node can be reused in a
* reusable group even if the group key is changed.
*/
@ComposeCompilerApi
fun startReusableNode()
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Report the [factory] that will be used to create the node that will be generated into the
* tree implied by the composition. This will only be called if [inserting] is is `true`.
*
* @param factory a factory function that will generate a node that will eventually be
* supplied to [applier] though [Applier.insertBottomUp] and [Applier.insertTopDown].
*/
@ComposeCompilerApi
fun <T> createNode(factory: () -> T)
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Report that the node is still being used. This will be called in the same location as the
* corresponding [createNode] when [inserting] is `false`.
*/
@ComposeCompilerApi
fun useNode()
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Called at the end of a node group.
*/
@ComposeCompilerApi
fun endNode()
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Start a reuse group. Unlike a movable group, in a reuse group if the [dataKey] changes
* the composition shifts into a reusing state cause the composer to act like it is
* inserting (e.g. [cache] acts as if all values are invalid, [changed] always returns
* true, etc.) even though it is recomposing until it encounters a reusable node. If the
* node is reusable it temporarily shifts into recomposition for the node and then shifts
* back to reusing for the children. If a non-reusable node is generated the composer
* shifts to inserting for the node and all of its children.
*
* @param key An compiler generated key based on the source location of the call.
* @param dataKey A key provided by the [ReusableContent] composable function that is used to
* determine if the composition shifts into a reusing state for this group.
*/
@ComposeCompilerApi
fun startReusableGroup(key: Int, dataKey: Any?)
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Called at the end of a reusable group.
*/
@ComposeCompilerApi
fun endReusableGroup()
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Temporarily disable reusing if it is enabled.
*/
@ComposeCompilerApi
fun disableReusing()
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Reenable reusing if it was previously enabled before the last call to [disableReusing].
*/
@ComposeCompilerApi
fun enableReusing()
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Return a marker for the current group that can be used in a call to [endToMarker].
*/
@ComposeCompilerApi
val currentMarker: Int
/**
* Compose compiler plugin API. DO NOT call directly.
*
* Ends all the groups up to but not including the group that is the parent group when
* [currentMarker] was called to produce [marker]. All groups ended must have been started with
* either [startReplaceableGroup] or [startMovableGroup]. Ending other groups can cause the
* state of the composer to become inconsistent.
*/
@ComposeCompilerApi
fun endToMarker(marker: Int)
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Schedule [block] to called with [value]. This is intended to update the node generated by
* [createNode] to changes discovered by composition.
*
* @param value the new value to be set into some property of the node.
* @param block the block that sets the some property of the node to [value].
*/
@ComposeCompilerApi
fun <V, T> apply(value: V, block: T.(V) -> Unit)
// State
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Produce an object that will compare equal an iff [left] and [right] compare equal to
* some [left] and [right] of a previous call to [joinKey]. This is used by [key] to handle
* multiple parameters. Since the previous composition stored [left] and [right] in a "join
* key" object this call is used to return the previous value without an allocation instead
* of blindly creating a new value that will be immediately discarded.
*
* @param left the first part of a a joined key.
* @param right the second part of a joined key.
* @return an object that will compare equal to a value previously returned by [joinKey] iff
* [left] and [right] compare equal to the [left] and [right] passed to the previous call.
*/
@ComposeCompilerApi
fun joinKey(left: Any?, right: Any?): Any
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Remember a value into the composition state. This is a primitive method used to implement
* [remember].
*
* @return [Composer.Empty] when [inserting] is `true` or the value passed to
* [updateRememberedValue]
* from the previous composition.
*
* @see cache
*/
@ComposeCompilerApi
fun rememberedValue(): Any?
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Update the remembered value correspond to the previous call to [rememberedValue]. The
* [value] will be returned by [rememberedValue] for the next composition.
*/
@ComposeCompilerApi
fun updateRememberedValue(value: Any?)
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Check [value] is different than the value used in the previous composition. This is used,
* for example, to check parameter values to determine if they have changed.
*
* @param value the value to check
* @return `true` if the value if [equals] of the previous value returns `false` when passed
* [value].
*/
@ComposeCompilerApi
fun changed(value: Any?): Boolean
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Check [value] is different than the value used in the previous composition. This is used,
* for example, to check parameter values to determine if they have changed.
*
* This overload is provided to avoid boxing [value] to compare with a potentially boxed
* version of [value] in the composition state.
*
* @param value the value to check
* @return `true` if the value if [equals] of the previous value returns `false` when passed
* [value].
*/
@ComposeCompilerApi
fun changed(value: Boolean): Boolean = changed(value)
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Check [value] is different than the value used in the previous composition. This is used,
* for example, to check parameter values to determine if they have changed.
*
* This overload is provided to avoid boxing [value] to compare with a potentially boxed
* version of [value] in the composition state.
*
* @param value the value to check
* @return `true` if the value if [equals] of the previous value returns `false` when passed
* [value].
*/
@ComposeCompilerApi
fun changed(value: Char): Boolean = changed(value)
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Check [value] is different than the value used in the previous composition. This is used,
* for example, to check parameter values to determine if they have changed.
*
* This overload is provided to avoid boxing [value] to compare with a potentially boxed
* version of [value] in the composition state.
*
* @param value the value to check
* @return `true` if the value if [equals] of the previous value returns `false` when passed
* [value].
*/
@ComposeCompilerApi
fun changed(value: Byte): Boolean = changed(value)
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Check [value] is different than the value used in the previous composition. This is used,
* for example, to check parameter values to determine if they have changed.
*
* This overload is provided to avoid boxing [value] to compare with a potentially boxed
* version of [value] in the composition state.
*
* @param value the value to check
* @return `true` if the value if [equals] of the previous value returns `false` when passed
* [value].
*/
@ComposeCompilerApi
fun changed(value: Short): Boolean = changed(value)
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Check [value] is different than the value used in the previous composition. This is used,
* for example, to check parameter values to determine if they have changed.
*
* This overload is provided to avoid boxing [value] to compare with a potentially boxed
* version of [value] in the composition state.
*
* @param value the value to check
* @return `true` if the value if [equals] of the previous value returns `false` when passed
* [value].
*/
@ComposeCompilerApi
fun changed(value: Int): Boolean = changed(value)
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Check [value] is different than the value used in the previous composition. This is used,
* for example, to check parameter values to determine if they have changed.
*
* This overload is provided to avoid boxing [value] to compare with a potentially boxed
* version of [value] in the composition state.
*
* @param value the value to check
* @return `true` if the value if [equals] of the previous value returns `false` when passed
* [value].
*/
@ComposeCompilerApi
fun changed(value: Float): Boolean = changed(value)
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Check [value] is different than the value used in the previous composition. This is used,
* for example, to check parameter values to determine if they have changed.
*
* This overload is provided to avoid boxing [value] to compare with a potentially boxed
* version of [value] in the composition state.
*
* @param value the value to check
* @return `true` if the value if [equals] of the previous value returns `false` when passed
* [value].
*/
@ComposeCompilerApi
fun changed(value: Long): Boolean = changed(value)
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Check [value] is different than the value used in the previous composition. This is used,
* for example, to check parameter values to determine if they have changed.
*
* This overload is provided to avoid boxing [value] to compare with a potentially boxed
* version of [value] in the composition state.
*
* @param value the value to check
* @return `true` if the value if [equals] of the previous value returns `false` when passed
* [value].
*/
@ComposeCompilerApi
fun changed(value: Double): Boolean = changed(value)
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Check [value] is different than the value used in the previous composition using `===`
* instead of `==` equality. This is used, for example, to check parameter values to determine
* if they have changed for values that use value equality but, for correct behavior, the
* composer needs reference equality.
*
* @param value the value to check
* @return `true` if the value is === equal to the previous value and returns `false` when
* [value] is different.
*/
@ComposeCompilerApi
fun changedInstance(value: Any?): Boolean = changed(value)
// Scopes
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Mark [scope] as used. [endReplaceableGroup] will return `null` unless [recordUsed] is
* called on the corresponding [scope]. This is called implicitly when [State] objects are
* read during composition is called when [currentRecomposeScope] is called in the
* [Composable] function.
*/
@InternalComposeApi
fun recordUsed(scope: RecomposeScope)
// Internal API
/**
* A Compose internal function. DO NOT call directly.
*
* Record a function to call when changes to the corresponding tree are applied to the
* [applier]. This is used to implement [SideEffect].
*
* @param effect a lambda to invoke after the changes calculated up to this point have been
* applied.
*/
@InternalComposeApi
fun recordSideEffect(effect: () -> Unit)
/**
* A Compose internal function. DO NOT call directly.
*
* Return the [CompositionLocal] value associated with [key]. This is the primitive function
* used to implement [CompositionLocal.current].
*
* @param key the [CompositionLocal] value to be retrieved.
*/
@InternalComposeApi
fun <T> consume(key: CompositionLocal<T>): T
/**
* A Compose internal function. DO NOT call directly.
*
* Provide the given values for the associated [CompositionLocal] keys. This is the primitive
* function used to implement [CompositionLocalProvider].
*
* @param values an array of value to provider key pairs.
*/
@InternalComposeApi
fun startProviders(values: Array<out ProvidedValue<*>>)
/**
* A Compose internal function. DO NOT call directly.
*
* End the provider group.
*
* @see startProviders
*/
@InternalComposeApi
fun endProviders()
/**
* A tooling API function. DO NOT call directly.
*
* The data stored for the composition. This is used by Compose tools, such as the preview and
* the inspector, to display or interpret the result of composition.
*/
val compositionData: CompositionData
/**
* A tooling API function. DO NOT call directly.
*
* Called by the inspector to inform the composer that it should collect additional
* information about call parameters. By default, only collect parameter information for
* scopes that are [recordUsed] has been called on. If [collectParameterInformation] is called
* it will attempt to collect all calls even if the runtime doesn't need them.
*
* WARNING: calling this will result in a significant number of additional allocations that are
* typically avoided.
*/
fun collectParameterInformation()
/**
* A Compose internal function. DO NOT call directly.
*
* Build a composition context that can be used to created a subcomposition. A composition
* reference is used to communicate information from this composition to the subcompositions
* such as the all the [CompositionLocal]s provided at the point the reference is created.
*/
@InternalComposeApi
fun buildContext(): CompositionContext
/**
* A Compose internal function. DO NOT call directly.
*
* The coroutine context for the composition. This is used, for example, to implement
* [LaunchedEffect]. This context is managed by the [Recomposer].
*/
@InternalComposeApi
val applyCoroutineContext: CoroutineContext
@TestOnly
get
/**
* The composition that is used to control this composer.
*/
val composition: ControlledComposition
@TestOnly get
fun disableSourceInformation()
companion object {
/**
* A special value used to represent no value was stored (e.g. an empty slot). This is
* returned, for example by [Composer.rememberedValue] while it is [Composer.inserting]
* is `true`.
*/
val Empty = object {
override fun toString() = "Empty"
}
/**
* Internal API for specifying a tracer used for instrumenting frequent
* operations, e.g. recompositions.
*/
@InternalComposeTracingApi
fun setTracer(tracer: CompositionTracer) {
compositionTracer = tracer
}
}
}
/**
* A Compose compiler plugin API. DO NOT call directly.
*
* Cache, that is remember, a value in the composition data of a composition. This is used to
* implement [remember] and used by the compiler plugin to generate more efficient calls to
* [remember] when it determines these optimizations are safe.
*/
@ComposeCompilerApi
inline fun <T> Composer.cache(invalid: Boolean, block: @DisallowComposableCalls () -> T): T {
@Suppress("UNCHECKED_CAST")
return rememberedValue().let {
if (invalid || it === Composer.Empty) {
val value = block()
updateRememberedValue(value)
value
} else it
} as T
}
/**
* A Compose internal function. DO NOT call directly.
*
* Records source information that can be used for tooling to determine the source location of
* the corresponding composable function. By default, this function is declared as having no
* side-effects. It is safe for code shrinking tools (such as R8 or ProGuard) to remove it.
*/
@ComposeCompilerApi
fun sourceInformation(composer: Composer, sourceInformation: String) {
composer.sourceInformation(sourceInformation)
}
/**
* A Compose internal function. DO NOT call directly.
*
* Records the start of a source information marker that can be used for tooling to determine the
* source location of the corresponding composable function that otherwise don't require tracking
* information such as [ReadOnlyComposable] functions. By default, this function is declared as
* having no side-effects. It is safe for code shrinking tools (such as R8 or ProGuard) to remove
* it.
*
* Important that both [sourceInformationMarkerStart] and [sourceInformationMarkerEnd] are removed
* together or both kept. Removing only one will cause incorrect runtime behavior.
*/
@ComposeCompilerApi
fun sourceInformationMarkerStart(composer: Composer, key: Int, sourceInformation: String) {
composer.sourceInformationMarkerStart(key, sourceInformation)
}
/**
* Internal tracing API.
*
* Should be called without thread synchronization with occasional information loss.
*/
@InternalComposeTracingApi
interface CompositionTracer {
fun traceEventStart(key: Int, dirty1: Int, dirty2: Int, info: String): Unit
fun traceEventEnd(): Unit
fun isTraceInProgress(): Boolean
}
@OptIn(InternalComposeTracingApi::class)
private var compositionTracer: CompositionTracer? = null
/**
* Internal tracing API.
*
* Should be called without thread synchronization with occasional information loss.
*/
@OptIn(InternalComposeTracingApi::class)
@ComposeCompilerApi
fun isTraceInProgress(): Boolean = compositionTracer.let { it != null && it.isTraceInProgress() }
@OptIn(InternalComposeTracingApi::class)
@ComposeCompilerApi
@Deprecated(
message = "Use the overload with \$dirty metadata instead",
ReplaceWith("traceEventStart(key, dirty1, dirty2, info)"),
DeprecationLevel.HIDDEN
)
fun traceEventStart(key: Int, info: String): Unit = traceEventStart(key, -1, -1, info)
/**
* Internal tracing API.
*
* Should be called without thread synchronization with occasional information loss.
*
* @param dirty1 $dirty metadata: forced-recomposition and function parameters 1..10 if present
* @param dirty2 $dirty2 metadata: forced-recomposition and function parameters 11..20 if present
*/
@OptIn(InternalComposeTracingApi::class)
@ComposeCompilerApi
fun traceEventStart(key: Int, dirty1: Int, dirty2: Int, info: String) {
compositionTracer?.traceEventStart(key, dirty1, dirty2, info)
}
/**
* Internal tracing API.
*
* Should be called without thread synchronization with occasional information loss.
*/
@OptIn(InternalComposeTracingApi::class)
@ComposeCompilerApi
fun traceEventEnd() {
compositionTracer?.traceEventEnd()
}
/**
* A Compose internal function. DO NOT call directly.
*
* Records the end of a source information marker that can be used for tooling to determine the
* source location of the corresponding composable function that otherwise don't require tracking
* information such as [ReadOnlyComposable] functions. By default, this function is declared as
* having no side-effects. It is safe for code shrinking tools (such as R8 or ProGuard) to remove
* it.
*
* Important that both [sourceInformationMarkerStart] and [sourceInformationMarkerEnd] are removed
* together or both kept. Removing only one will cause incorrect runtime behavior.
*/
@ComposeCompilerApi
fun sourceInformationMarkerEnd(composer: Composer) {
composer.sourceInformationMarkerEnd()
}
/**
* Implementation of a composer for a mutable tree.
*/
internal class ComposerImpl(
/**
* An adapter that applies changes to the tree using the Applier abstraction.
*/
override val applier: Applier<*>,
/**
* Parent of this composition; a [Recomposer] for root-level compositions.
*/
private val parentContext: CompositionContext,
/**
* The slot table to use to store composition data
*/
private val slotTable: SlotTable,
private val abandonSet: MutableSet<RememberObserver>,
private var changes: MutableList<Change>,
private var lateChanges: MutableList<Change>,
/**
* The composition that owns this composer
*/
override val composition: ControlledComposition
) : Composer {
private val pendingStack = Stack<Pending?>()
private var pending: Pending? = null
private var nodeIndex: Int = 0
private var nodeIndexStack = IntStack()
private var groupNodeCount: Int = 0
private var groupNodeCountStack = IntStack()
private var nodeCountOverrides: IntArray? = null
private var nodeCountVirtualOverrides: HashMap<Int, Int>? = null
private var forceRecomposeScopes = false
private var forciblyRecompose = false
private var nodeExpected = false
private val invalidations: MutableList<Invalidation> = mutableListOf()
private val entersStack = IntStack()
private var parentProvider: CompositionLocalMap = persistentHashMapOf()
private val providerUpdates = HashMap<Int, CompositionLocalMap>()
private var providersInvalid = false
private val providersInvalidStack = IntStack()
private var reusing = false
private var reusingGroup = -1
private var childrenComposing: Int = 0
private var snapshot = currentSnapshot()
private var compositionToken: Int = 0
private var sourceInformationEnabled = true
private val invalidateStack = Stack<RecomposeScopeImpl>()
internal var isComposing = false
private set
internal var isDisposed = false
private set
internal val areChildrenComposing get() = childrenComposing > 0
internal val hasPendingChanges: Boolean get() = changes.isNotEmpty()
private var reader: SlotReader = slotTable.openReader().also { it.close() }
internal var insertTable = SlotTable()
private var writer: SlotWriter = insertTable.openWriter().also { it.close() }
private var writerHasAProvider = false
private var providerCache: CompositionLocalMap? = null
internal var deferredChanges: MutableList<Change>? = null
private var insertAnchor: Anchor = insertTable.read { it.anchor(0) }
private val insertFixups = mutableListOf<Change>()
override val applyCoroutineContext: CoroutineContext
@TestOnly get() = parentContext.effectCoroutineContext
/**
* Inserts a "Replaceable Group" starting marker in the slot table at the current execution
* position. A Replaceable Group is a group which cannot be moved between its siblings, but
* can be removed or inserted. These groups are inserted by the compiler around branches of
* conditional logic in Composable functions such as if expressions, when expressions, early
* returns, and null-coalescing operators.
*
* A call to [startReplaceableGroup] must be matched with a corresponding call to
* [endReplaceableGroup].
*
* Warning: This is expected to be executed by the compiler only and should not be called
* directly from source code. Call this API at your own risk.
*
* @param key The source-location-based key for the group. Expected to be unique among its
* siblings.
*
* @see [endReplaceableGroup]
* @see [startMovableGroup]
* @see [startRestartGroup]
*/
@ComposeCompilerApi
override fun startReplaceableGroup(key: Int) = start(key, null, false, null)
/**
* Indicates the end of a "Replaceable Group" at the current execution position. A
* Replaceable Group is a group which cannot be moved between its siblings, but
* can be removed or inserted. These groups are inserted by the compiler around branches of
* conditional logic in Composable functions such as if expressions, when expressions, early
* returns, and null-coalescing operators.
*
* Warning: This is expected to be executed by the compiler only and should not be called
* directly from source code. Call this API at your own risk.
*
* @see [startReplaceableGroup]
*/
@ComposeCompilerApi
override fun endReplaceableGroup() = endGroup()
/**
*
* Warning: This is expected to be executed by the compiler only and should not be called
* directly from source code. Call this API at your own risk.
*
*/
@ComposeCompilerApi
@Suppress("unused")
override fun startDefaults() = start(defaultsKey, null, false, null)
/**
*
* Warning: This is expected to be executed by the compiler only and should not be called
* directly from source code. Call this API at your own risk.
*
* @see [startReplaceableGroup]
*/
@ComposeCompilerApi
@Suppress("unused")
override fun endDefaults() {
endGroup()
val scope = currentRecomposeScope
if (scope != null && scope.used) {
scope.defaultsInScope = true
}
}
@ComposeCompilerApi
@Suppress("unused")
override val defaultsInvalid: Boolean
get() {
return providersInvalid || currentRecomposeScope?.defaultsInvalid == true
}
/**
* Inserts a "Movable Group" starting marker in the slot table at the current execution
* position. A Movable Group is a group which can be moved or reordered between its siblings
* and retain slot table state, in addition to being removed or inserted. Movable Groups
* are more expensive than other groups because when they are encountered with a mismatched
* key in the slot table, they must be held on to temporarily until the entire parent group
* finishes execution in case it moved to a later position in the group. Movable groups are
* only inserted by the compiler as a result of calls to [key].
*
* A call to [startMovableGroup] must be matched with a corresponding call to [endMovableGroup].
*
* Warning: This is expected to be executed by the compiler only and should not be called
* directly from source code. Call this API at your own risk.
*
* @param key The source-location-based key for the group. Expected to be unique among its
* siblings.
*
* @param dataKey Additional identifying information to compound with [key]. If there are
* multiple values, this is expected to be compounded together with [joinKey]. Whatever value
* is passed in here is expected to have a meaningful [equals] and [hashCode] implementation.
*
* @see [endMovableGroup]
* @see [key]
* @see [joinKey]
* @see [startReplaceableGroup]
* @see [startRestartGroup]
*/
@ComposeCompilerApi
override fun startMovableGroup(key: Int, dataKey: Any?) = start(key, dataKey, false, null)
/**
* Indicates the end of a "Movable Group" at the current execution position. A Movable Group is
* a group which can be moved or reordered between its siblings and retain slot table state,
* in addition to being removed or inserted. These groups are only valid when they are
* inserted as direct children of Container Groups. Movable Groups are more expensive than
* other groups because when they are encountered with a mismatched key in the slot table,
* they must be held on to temporarily until the entire parent group finishes execution in
* case it moved to a later position in the group. Movable groups are only inserted by the
* compiler as a result of calls to [key].
*
* Warning: This is expected to be executed by the compiler only and should not be called
* directly from source code. Call this API at your own risk.
*
* @see [startMovableGroup]
*/
@ComposeCompilerApi
override fun endMovableGroup() = endGroup()
/**
* Start the composition. This should be called, and only be called, as the first group in
* the composition.
*/
@OptIn(InternalComposeApi::class)
private fun startRoot() {
reader = slotTable.openReader()
startGroup(rootKey)
// parent reference management
parentContext.startComposing()
parentProvider = parentContext.getCompositionLocalScope()
providersInvalidStack.push(providersInvalid.asInt())
providersInvalid = changed(parentProvider)
providerCache = null
if (!forceRecomposeScopes) {
forceRecomposeScopes = parentContext.collectingParameterInformation
}
resolveCompositionLocal(LocalInspectionTables, parentProvider)?.let {
it.add(slotTable)
parentContext.recordInspectionTable(it)
}
startGroup(parentContext.compoundHashKey)
}
/**
* End the composition. This should be called, and only be called, to end the first group in
* the composition.
*/
@OptIn(InternalComposeApi::class)
private fun endRoot() {
endGroup()
parentContext.doneComposing()
endGroup()
recordEndRoot()
finalizeCompose()
reader.close()
forciblyRecompose = false
}
/**
* Discard a pending composition because an error was encountered during composition
*/
@OptIn(InternalComposeApi::class)
private fun abortRoot() {
cleanUpCompose()
pendingStack.clear()
nodeIndexStack.clear()
groupNodeCountStack.clear()
entersStack.clear()
providersInvalidStack.clear()
providerUpdates.clear()
if (!reader.closed) {
reader.close()
}
if (!writer.closed) {
writer.close()
}
createFreshInsertTable()
compoundKeyHash = 0
childrenComposing = 0
nodeExpected = false
inserting = false
reusing = false
isComposing = false
forciblyRecompose = false
}
internal fun changesApplied() {
providerUpdates.clear()
}
/**
* True if the composition is currently scheduling nodes to be inserted into the tree. During
* first composition this is always true. During recomposition this is true when new nodes
* are being scheduled to be added to the tree.
*/
@ComposeCompilerApi
override var inserting: Boolean = false
private set
/**
* True if the composition should be checking if the composable functions can be skipped.
*/
@ComposeCompilerApi
override val skipping: Boolean
get() {
return !inserting && !reusing &&
!providersInvalid &&
currentRecomposeScope?.requiresRecompose == false &&
!forciblyRecompose
}
/**
* Returns the hash of the compound key calculated as a combination of the keys of all the
* currently started groups via [startGroup].
*/
@InternalComposeApi
override var compoundKeyHash: Int = 0
private set
/**
* Start collecting parameter information. This enables the tools API to always be able to
* determine the parameter values of composable calls.
*/
override fun collectParameterInformation() {
forceRecomposeScopes = true
}
@OptIn(InternalComposeApi::class)
internal fun dispose() {
trace("Compose:Composer.dispose") {
parentContext.unregisterComposer(this)
invalidateStack.clear()
invalidations.clear()
changes.clear()
providerUpdates.clear()
applier.clear()
isDisposed = true
}
}
internal fun forceRecomposeScopes(): Boolean {
return if (!forceRecomposeScopes) {
forceRecomposeScopes = true
forciblyRecompose = true
true
} else {
false
}
}
/**
* Start a group with the given key. During recomposition if the currently expected group does
* not match the given key a group the groups emitted in the same parent group are inspected
* to determine if one of them has this key and that group the first such group is moved
* (along with any nodes emitted by the group) to the current position and composition
* continues. If no group with this key is found, then the composition shifts into insert
* mode and new nodes are added at the current position.
*
* @param key The key for the group
*/
private fun startGroup(key: Int) = start(key, null, false, null)
private fun startGroup(key: Int, dataKey: Any?) = start(key, dataKey, false, null)
/**
* End the current group.
*/
private fun endGroup() = end(isNode = false)
@OptIn(InternalComposeApi::class)
private fun skipGroup() {
groupNodeCount += reader.skipGroup()
}
/**
* Start emitting a node. It is required that [createNode] is called after [startNode].
* Similar to [startGroup], if, during recomposition, the current node does not have the
* provided key a node with that key is scanned for and moved into the current position if
* found, if no such node is found the composition switches into insert mode and a the node
* is scheduled to be inserted at the current location.
*/
override fun startNode() {
val key = if (inserting) nodeKey
else if (reusing)
if (reader.groupKey == nodeKey) nodeKeyReplace else nodeKey
else if (reader.groupKey == nodeKeyReplace) nodeKeyReplace
else nodeKey
start(key, null, true, null)
nodeExpected = true
}
override fun startReusableNode() {
start(nodeKey, null, true, null)
nodeExpected = true
}
/**
* Schedule a node to be created and inserted at the current location. This is only valid to
* call when the composer is inserting.
*/
@Suppress("UNUSED")
override fun <T> createNode(factory: () -> T) {
validateNodeExpected()
runtimeCheck(inserting) { "createNode() can only be called when inserting" }
val insertIndex = nodeIndexStack.peek()
val groupAnchor = writer.anchor(writer.parent)
groupNodeCount++
recordFixup { applier, slots, _ ->
@Suppress("UNCHECKED_CAST")
val node = factory()
slots.updateNode(groupAnchor, node)
@Suppress("UNCHECKED_CAST") val nodeApplier = applier as Applier<T>
nodeApplier.insertTopDown(insertIndex, node)
applier.down(node)
}
recordInsertUpFixup { applier, slots, _ ->
@Suppress("UNCHECKED_CAST")
val nodeToInsert = slots.node(groupAnchor)
applier.up()
@Suppress("UNCHECKED_CAST") val nodeApplier = applier as Applier<Any?>
nodeApplier.insertBottomUp(insertIndex, nodeToInsert)
}
}
/**
* Mark the node that was created by [createNode] as used by composition.
*/
@OptIn(InternalComposeApi::class)
override fun useNode() {
validateNodeExpected()
runtimeCheck(!inserting) { "useNode() called while inserting" }
recordDown(reader.node)
}
/**
* Called to end the node group.
*/
override fun endNode() = end(isNode = true)
override fun startReusableGroup(key: Int, dataKey: Any?) {
if (reader.groupKey == key && reader.groupAux != dataKey && reusingGroup < 0) {
// Starting to reuse nodes
reusingGroup = reader.currentGroup
reusing = true
}
start(key, null, false, dataKey)
}
override fun endReusableGroup() {
if (reusing && reader.parent == reusingGroup) {
reusingGroup = -1
reusing = false
}
end(isNode = false)
}
override fun disableReusing() {
reusing = false
}
override fun enableReusing() {
reusing = reusingGroup >= 0
}
override val currentMarker: Int
get() = if (inserting) -writer.parent else reader.parent
override fun endToMarker(marker: Int) {
if (marker < 0) {
val writerLocation = -marker
while (writer.parent > writerLocation) end(false)
} else {
while (reader.parent > marker) end(false)
}
}
/**
* Schedule a change to be applied to a node's property. This change will be applied to the
* node that is the current node in the tree which was either created by [createNode].
*/
override fun <V, T> apply(value: V, block: T.(V) -> Unit) {
val operation: Change = { applier, _, _ ->
@Suppress("UNCHECKED_CAST")
(applier.current as T).block(value)
}
if (inserting) recordFixup(operation)
else recordApplierOperation(operation)
}
/**
* Create a composed key that can be used in calls to [startGroup] or [startNode]. This will
* use the key stored at the current location in the slot table to avoid allocating a new key.
*/
@ComposeCompilerApi
@OptIn(InternalComposeApi::class)
override fun joinKey(left: Any?, right: Any?): Any =
getKey(reader.groupObjectKey, left, right) ?: JoinedKey(left, right)
/**
* Return the next value in the slot table and advance the current location.
*/
@PublishedApi
@OptIn(InternalComposeApi::class)
internal fun nextSlot(): Any? = if (inserting) {
validateNodeNotExpected()
Composer.Empty
} else reader.next().let { if (reusing) Composer.Empty else it }
/**
* Determine if the current slot table value is equal to the given value, if true, the value
* is scheduled to be skipped during [ControlledComposition.applyChanges] and [changes] return
* false; otherwise [ControlledComposition.applyChanges] will update the slot table to [value].
* In either case the composer's slot table is advanced.
*
* @param value the value to be compared.
*/
@ComposeCompilerApi
override fun changed(value: Any?): Boolean {
return if (nextSlot() != value) {
updateValue(value)
true
} else {
false
}
}
@ComposeCompilerApi
override fun changedInstance(value: Any?): Boolean {
return if (nextSlot() !== value) {
updateValue(value)
true
} else {
false
}
}
@ComposeCompilerApi
override fun changed(value: Char): Boolean {
val next = nextSlot()
if (next is Char) {
val nextPrimitive: Char = next
if (value == nextPrimitive) return false
}
updateValue(value)
return true
}
@ComposeCompilerApi
override fun changed(value: Byte): Boolean {
val next = nextSlot()
if (next is Byte) {
val nextPrimitive: Byte = next
if (value == nextPrimitive) return false
}
updateValue(value)
return true
}
@ComposeCompilerApi
override fun changed(value: Short): Boolean {
val next = nextSlot()
if (next is Short) {
val nextPrimitive: Short = next
if (value == nextPrimitive) return false
}
updateValue(value)
return true
}
@ComposeCompilerApi
override fun changed(value: Boolean): Boolean {
val next = nextSlot()
if (next is Boolean) {
val nextPrimitive: Boolean = next
if (value == nextPrimitive) return false
}
updateValue(value)
return true
}
@ComposeCompilerApi
override fun changed(value: Float): Boolean {
val next = nextSlot()
if (next is Float) {
val nextPrimitive: Float = next
if (value == nextPrimitive) return false
}
updateValue(value)
return true
}
@ComposeCompilerApi
override fun changed(value: Long): Boolean {
val next = nextSlot()
if (next is Long) {
val nextPrimitive: Long = next
if (value == nextPrimitive) return false
}
updateValue(value)
return true
}
@ComposeCompilerApi
override fun changed(value: Double): Boolean {
val next = nextSlot()
if (next is Double) {
val nextPrimitive: Double = next
if (value == nextPrimitive) return false
}
updateValue(value)
return true
}
@ComposeCompilerApi
override fun changed(value: Int): Boolean {
val next = nextSlot()
if (next is Int) {
val nextPrimitive: Int = next
if (value == nextPrimitive) return false
}
updateValue(value)
return true
}
/**
* Cache a value in the composition. During initial composition [block] is called to produce the
* value that is then stored in the slot table. During recomposition, if [invalid] is false
* the value is obtained from the slot table and [block] is not invoked. If [invalid] is
* false a new value is produced by calling [block] and the slot table is updated to contain
* the new value.
*/
@ComposeCompilerApi
inline fun <T> cache(invalid: Boolean, block: () -> T): T {
var result = nextSlot()
if (result === Composer.Empty || invalid) {
val value = block()
updateValue(value)
result = value
}
@Suppress("UNCHECKED_CAST")
return result as T
}
/**
* Schedule the current value in the slot table to be updated to [value].
*
* @param value the value to schedule to be written to the slot table.
*/
@PublishedApi
@OptIn(InternalComposeApi::class)
internal fun updateValue(value: Any?) {
if (inserting) {
writer.update(value)
if (value is RememberObserver) {
record { _, _, rememberManager -> rememberManager.remembering(value) }
abandonSet.add(value)
}
} else {
val groupSlotIndex = reader.groupSlotIndex - 1
if (value is RememberObserver) {
abandonSet.add(value)
}
recordSlotTableOperation(forParent = true) { _, slots, rememberManager ->
if (value is RememberObserver) {
rememberManager.remembering(value)
}
when (val previous = slots.set(groupSlotIndex, value)) {
is RememberObserver ->
rememberManager.forgetting(previous)
is RecomposeScopeImpl -> {
val composition = previous.composition
if (composition != null) {
previous.release()
composition.pendingInvalidScopes = true
}
}
}
}
}
}
/**
* Schedule the current value in the slot table to be updated to [value].
*
* @param value the value to schedule to be written to the slot table.
*/
@PublishedApi
@OptIn(InternalComposeApi::class)
internal fun updateCachedValue(value: Any?) {
updateValue(value)
}
override val compositionData: CompositionData get() = slotTable
/**
* Schedule a side effect to run when we apply composition changes.
*/
override fun recordSideEffect(effect: () -> Unit) {
record { _, _, rememberManager -> rememberManager.sideEffect(effect) }
}
/**
* Return the current [CompositionLocal] scope which was provided by a parent group.
*/
private fun currentCompositionLocalScope(group: Int? = null): CompositionLocalMap {
if (group == null)
providerCache?.let { return it }
if (inserting && writerHasAProvider) {
var current = writer.parent
while (current > 0) {
if (writer.groupKey(current) == compositionLocalMapKey &&
writer.groupObjectKey(current) == compositionLocalMap
) {
@Suppress("UNCHECKED_CAST")
val providers = writer.groupAux(current) as CompositionLocalMap
providerCache = providers
return providers
}
current = writer.parent(current)
}
}
if (reader.size > 0) {
var current = group ?: reader.parent
while (current > 0) {
if (reader.groupKey(current) == compositionLocalMapKey &&
reader.groupObjectKey(current) == compositionLocalMap
) {
@Suppress("UNCHECKED_CAST")
val providers = providerUpdates[current]
?: reader.groupAux(current) as CompositionLocalMap
providerCache = providers
return providers
}
current = reader.parent(current)
}
}
providerCache = parentProvider
return parentProvider
}
/**
* Update (or create) the slots to record the providers. The providers maps are first the
* scope followed by the map used to augment the parent scope. Both are needed to detect
* inserts, updates and deletes to the providers.
*/
private fun updateProviderMapGroup(
parentScope: CompositionLocalMap,
currentProviders: CompositionLocalMap
): CompositionLocalMap {
val providerScope = parentScope.mutate { it.putAll(currentProviders) }
startGroup(providerMapsKey, providerMaps)
changed(providerScope)
changed(currentProviders)
endGroup()
return providerScope
}
@InternalComposeApi
override fun startProviders(values: Array<out ProvidedValue<*>>) {
val parentScope = currentCompositionLocalScope()
startGroup(providerKey, provider)
// The group is needed here because compositionLocalMapOf() might change the number or
// kind of slots consumed depending on the content of values to remember, for example, the
// value holders used last time.
startGroup(providerValuesKey, providerValues)
val currentProviders = invokeComposableForResult(this) {
compositionLocalMapOf(values, parentScope)
}
endGroup()
val providers: CompositionLocalMap
val invalid: Boolean
if (inserting) {
providers = updateProviderMapGroup(parentScope, currentProviders)
invalid = false
writerHasAProvider = true
} else {
@Suppress("UNCHECKED_CAST")
val oldScope = reader.groupGet(0) as CompositionLocalMap
@Suppress("UNCHECKED_CAST")
val oldValues = reader.groupGet(1) as CompositionLocalMap
// skipping is true iff parentScope has not changed.
if (!skipping || oldValues != currentProviders) {
providers = updateProviderMapGroup(parentScope, currentProviders)
// Compare against the old scope as currentProviders might have modified the scope
// back to the previous value. This could happen, for example, if currentProviders
// and parentScope have a key in common and the oldScope had the same value as
// currentProviders for that key. If the scope has not changed, because these
// providers obscure a change in the parent as described above, re-enable skipping
// for the child region.
invalid = providers != oldScope
} else {
// Nothing has changed
skipGroup()
providers = oldScope
invalid = false
}
}
if (invalid && !inserting) {
providerUpdates[reader.currentGroup] = providers
}
providersInvalidStack.push(providersInvalid.asInt())
providersInvalid = invalid
providerCache = providers
start(compositionLocalMapKey, compositionLocalMap, false, providers)
}
@InternalComposeApi
override fun endProviders() {
endGroup()
endGroup()
providersInvalid = providersInvalidStack.pop().asBool()
providerCache = null
}
@InternalComposeApi
override fun <T> consume(key: CompositionLocal<T>): T =
resolveCompositionLocal(key, currentCompositionLocalScope())
/**
* Create or use a memoized [CompositionContext] instance at this position in the slot table.
*/
override fun buildContext(): CompositionContext {
startGroup(referenceKey, reference)
if (inserting)
writer.markGroup()
var holder = nextSlot() as? CompositionContextHolder
if (holder == null) {
holder = CompositionContextHolder(
CompositionContextImpl(
compoundKeyHash,
forceRecomposeScopes
)
)
updateValue(holder)
}
holder.ref.updateCompositionLocalScope(currentCompositionLocalScope())
endGroup()
return holder.ref
}
private fun <T> resolveCompositionLocal(
key: CompositionLocal<T>,
scope: CompositionLocalMap
): T = if (scope.contains(key)) {
scope.getValueOf(key)
} else {
key.defaultValueHolder.value
}
/**
* The number of changes that have been scheduled to be applied during
* [ControlledComposition.applyChanges].
*
* Slot table movement (skipping groups and nodes) will be coalesced so this number is
* possibly less than the total changes detected.
*/
internal val changeCount get() = changes.size
internal val currentRecomposeScope: RecomposeScopeImpl?
get() = invalidateStack.let {
if (childrenComposing == 0 && it.isNotEmpty()) it.peek() else null
}
private fun ensureWriter() {
if (writer.closed) {
writer = insertTable.openWriter()
// Append to the end of the table
writer.skipToGroupEnd()
writerHasAProvider = false
providerCache = null
}
}
private fun createFreshInsertTable() {
runtimeCheck(writer.closed)
insertTable = SlotTable()
writer = insertTable.openWriter().also { it.close() }
}
/**
* Start the reader group updating the data of the group if necessary
*/
private fun startReaderGroup(isNode: Boolean, data: Any?) {
if (isNode) {
reader.startNode()
} else {
if (data != null && reader.groupAux !== data) {
recordSlotTableOperation { _, slots, _ ->
slots.updateAux(data)
}
}
reader.startGroup()
}
}
private fun start(key: Int, objectKey: Any?, isNode: Boolean, data: Any?) {
validateNodeNotExpected()
updateCompoundKeyWhenWeEnterGroup(key, objectKey, data)
// Check for the insert fast path. If we are already inserting (creating nodes) then
// there is no need to track insert, deletes and moves with a pending changes object.
if (inserting) {
reader.beginEmpty()
val startIndex = writer.currentGroup
when {
isNode -> writer.startNode(Composer.Empty)
data != null -> writer.startData(key, objectKey ?: Composer.Empty, data)
else -> writer.startGroup(key, objectKey ?: Composer.Empty)
}
pending?.let { pending ->
val insertKeyInfo = KeyInfo(
key = key,
objectKey = -1,
location = insertedGroupVirtualIndex(startIndex),
nodes = -1,
index = 0
)
pending.registerInsert(insertKeyInfo, nodeIndex - pending.startIndex)
pending.recordUsed(insertKeyInfo)
}
enterGroup(isNode, null)
return
}
if (pending == null) {
val slotKey = reader.groupKey
if (slotKey == key && objectKey == reader.groupObjectKey) {
// The group is the same as what was generated last time.
startReaderGroup(isNode, data)
} else {
pending = Pending(
reader.extractKeys(),
nodeIndex
)
}
}
val pending = pending
var newPending: Pending? = null
if (pending != null) {
// Check to see if the key was generated last time from the keys collected above.
val keyInfo = pending.getNext(key, objectKey)
if (keyInfo != null) {
// This group was generated last time, use it.
pending.recordUsed(keyInfo)
// Move the slot table to the location where the information about this group is
// stored. The slot information will move once the changes are applied so moving the
// current of the slot table is sufficient.
val location = keyInfo.location
// Determine what index this group is in. This is used for inserting nodes into the
// group.
nodeIndex = pending.nodePositionOf(keyInfo) + pending.startIndex
// Determine how to move the slot group to the correct position.
val relativePosition = pending.slotPositionOf(keyInfo)
val currentRelativePosition = relativePosition - pending.groupIndex
pending.registerMoveSlot(relativePosition, pending.groupIndex)
recordReaderMoving(location)
reader.reposition(location)
if (currentRelativePosition > 0) {
// The slot group must be moved, record the move to be performed during apply.
recordSlotEditingOperation { _, slots, _ ->
slots.moveGroup(currentRelativePosition)
}
}
startReaderGroup(isNode, data)
} else {
// The group is new, go into insert mode. All child groups will written to the
// insertTable until the group is complete which will schedule the groups to be
// inserted into in the table.
reader.beginEmpty()
inserting = true
providerCache = null
ensureWriter()
writer.beginInsert()
val startIndex = writer.currentGroup
when {
isNode -> writer.startNode(Composer.Empty)
data != null -> writer.startData(key, objectKey ?: Composer.Empty, data)
else -> writer.startGroup(key, objectKey ?: Composer.Empty)
}
insertAnchor = writer.anchor(startIndex)
val insertKeyInfo = KeyInfo(
key = key,
objectKey = -1,
location = insertedGroupVirtualIndex(startIndex),
nodes = -1,
index = 0
)
pending.registerInsert(insertKeyInfo, nodeIndex - pending.startIndex)
pending.recordUsed(insertKeyInfo)
newPending = Pending(
mutableListOf(),
if (isNode) 0 else nodeIndex
)
}
}
enterGroup(isNode, newPending)
}
private fun enterGroup(isNode: Boolean, newPending: Pending?) {
// When entering a group all the information about the parent should be saved, to be
// restored when end() is called, and all the tracking counters set to initial state for the
// group.
pendingStack.push(pending)
this.pending = newPending
this.nodeIndexStack.push(nodeIndex)
if (isNode) nodeIndex = 0
this.groupNodeCountStack.push(groupNodeCount)
groupNodeCount = 0
}
private fun exitGroup(expectedNodeCount: Int, inserting: Boolean) {
// Restore the parent's state updating them if they have changed based on changes in the
// children. For example, if a group generates nodes then the number of generated nodes will
// increment the node index and the group's node count. If the parent is tracking structural
// changes in pending then restore that too.
val previousPending = pendingStack.pop()
if (previousPending != null && !inserting) {
previousPending.groupIndex++
}
this.pending = previousPending
this.nodeIndex = nodeIndexStack.pop() + expectedNodeCount
this.groupNodeCount = this.groupNodeCountStack.pop() + expectedNodeCount
}
private fun end(isNode: Boolean) {
// All the changes to the group (or node) have been recorded. All new nodes have been
// inserted but it has yet to determine which need to be removed or moved. Note that the
// changes are relative to the first change in the list of nodes that are changing.
if (inserting) {
val parent = writer.parent
updateCompoundKeyWhenWeExitGroup(
writer.groupKey(parent),
writer.groupObjectKey(parent),
writer.groupAux(parent)
)
} else {
val parent = reader.parent
updateCompoundKeyWhenWeExitGroup(
reader.groupKey(parent),
reader.groupObjectKey(parent),
reader.groupAux(parent)
)
}
var expectedNodeCount = groupNodeCount
val pending = pending
if (pending != null && pending.keyInfos.size > 0) {
// previous contains the list of keys as they were generated in the previous composition
val previous = pending.keyInfos
// current contains the list of keys in the order they need to be in the new composition
val current = pending.used
// usedKeys contains the keys that were used in the new composition, therefore if a key
// doesn't exist in this set, it needs to be removed.
val usedKeys = current.fastToSet()
val placedKeys = mutableSetOf<KeyInfo>()
var currentIndex = 0
val currentEnd = current.size
var previousIndex = 0
val previousEnd = previous.size
// Traverse the list of changes to determine startNode movement
var nodeOffset = 0
while (previousIndex < previousEnd) {
val previousInfo = previous[previousIndex]
if (!usedKeys.contains(previousInfo)) {
// If the key info was not used the group was deleted, remove the nodes in the
// group
val deleteOffset = pending.nodePositionOf(previousInfo)
recordRemoveNode(deleteOffset + pending.startIndex, previousInfo.nodes)
pending.updateNodeCount(previousInfo.location, 0)
recordReaderMoving(previousInfo.location)
reader.reposition(previousInfo.location)
recordDelete()
reader.skipGroup()
// Remove any invalidations pending for the group being removed. These are no
// longer part of the composition. The group being composed is one after the
// start of the group.
invalidations.removeRange(
previousInfo.location,
previousInfo.location + reader.groupSize(previousInfo.location)
)
previousIndex++
continue
}
if (previousInfo in placedKeys) {
// If the group was already placed in the correct location, skip it.
previousIndex++
continue
}
if (currentIndex < currentEnd) {
// At this point current should match previous unless the group is new or was
// moved.
val currentInfo = current[currentIndex]
if (currentInfo !== previousInfo) {
val nodePosition = pending.nodePositionOf(currentInfo)
placedKeys.add(currentInfo)
if (nodePosition != nodeOffset) {
val updatedCount = pending.updatedNodeCountOf(currentInfo)
recordMoveNode(
nodePosition + pending.startIndex,
nodeOffset + pending.startIndex, updatedCount
)
pending.registerMoveNode(nodePosition, nodeOffset, updatedCount)
} // else the nodes are already in the correct position
} else {
// The correct nodes are in the right location
previousIndex++
}
currentIndex++
nodeOffset += pending.updatedNodeCountOf(currentInfo)
}
}
// If there are any current nodes left they where inserted into the right location
// when the group began so the rest are ignored.
realizeMovement()
// We have now processed the entire list so move the slot table to the end of the list
// by moving to the last key and skipping it.
if (previous.size > 0) {
recordReaderMoving(reader.groupEnd)
reader.skipToGroupEnd()
}
}
// Detect removing nodes at the end. No pending is created in this case we just have more
// nodes in the previous composition than we expect (i.e. we are not yet at an end)
val removeIndex = nodeIndex
while (!reader.isGroupEnd) {
val startSlot = reader.currentGroup
recordDelete()
val nodesToRemove = reader.skipGroup()
recordRemoveNode(removeIndex, nodesToRemove)
invalidations.removeRange(startSlot, reader.currentGroup)
}
val inserting = inserting
if (inserting) {
if (isNode) {
registerInsertUpFixup()
expectedNodeCount = 1
}
reader.endEmpty()
val parentGroup = writer.parent
writer.endGroup()
if (!reader.inEmpty) {
val virtualIndex = insertedGroupVirtualIndex(parentGroup)
writer.endInsert()
writer.close()
recordInsert(insertAnchor)
this.inserting = false
if (!slotTable.isEmpty) {
updateNodeCount(virtualIndex, 0)
updateNodeCountOverrides(virtualIndex, expectedNodeCount)
}
}
} else {
if (isNode) recordUp()
recordEndGroup()
val parentGroup = reader.parent
val parentNodeCount = updatedNodeCount(parentGroup)
if (expectedNodeCount != parentNodeCount) {
updateNodeCountOverrides(parentGroup, expectedNodeCount)
}
if (isNode) {
expectedNodeCount = 1
}
reader.endGroup()
realizeMovement()
}
exitGroup(expectedNodeCount, inserting)
}
/**
* Recompose any invalidate child groups of the current parent group. This should be called
* after the group is started but on or before the first child group. It is intended to be
* called instead of [skipReaderToGroupEnd] if any child groups are invalid. If no children
* are invalid it will call [skipReaderToGroupEnd].
*/
private fun recomposeToGroupEnd() {
val wasComposing = isComposing
isComposing = true
var recomposed = false
val parent = reader.parent
val end = parent + reader.groupSize(parent)
val recomposeIndex = nodeIndex
val recomposeCompoundKey = compoundKeyHash
val oldGroupNodeCount = groupNodeCount
var oldGroup = parent
var firstInRange = invalidations.firstInRange(reader.currentGroup, end)
while (firstInRange != null) {
val location = firstInRange.location
invalidations.removeLocation(location)
if (firstInRange.isInvalid()) {
recomposed = true
reader.reposition(location)
val newGroup = reader.currentGroup
// Record the changes to the applier location
recordUpsAndDowns(oldGroup, newGroup, parent)
oldGroup = newGroup
// Calculate the node index (the distance index in the node this groups nodes are
// located in the parent node).
nodeIndex = nodeIndexOf(
location,
newGroup,
parent,
recomposeIndex
)
// Calculate the compound hash code (a semi-unique code for every group in the
// composition used to restore saved state).
compoundKeyHash = compoundKeyOf(
reader.parent(newGroup),
parent,
recomposeCompoundKey
)
// We have moved so the cached lookup of the provider is invalid
providerCache = null
// Invoke the scope's composition function
firstInRange.scope.compose(this)
// We could have moved out of a provider so the provider cache is invalid.
providerCache = null
// Restore the parent of the reader to the previous parent
reader.restoreParent(parent)
} else {
// If the invalidation is not used restore the reads that were removed when the
// the invalidation was recorded. This happens, for example, when on of a derived
// state's dependencies changed but the derived state itself was not changed.
invalidateStack.push(firstInRange.scope)
firstInRange.scope.rereadTrackedInstances()
invalidateStack.pop()
}
// Using slots.current here ensures composition always walks forward even if a component
// before the current composition is invalidated when performing this composition. Any
// such components will be considered invalid for the next composition. Skipping them
// prevents potential infinite recomposes at the cost of potentially missing a compose
// as well as simplifies the apply as it always modifies the slot table in a forward
// direction.
firstInRange = invalidations.firstInRange(reader.currentGroup, end)
}
if (recomposed) {
recordUpsAndDowns(oldGroup, parent, parent)
reader.skipToGroupEnd()
val parentGroupNodes = updatedNodeCount(parent)
nodeIndex = recomposeIndex + parentGroupNodes
groupNodeCount = oldGroupNodeCount + parentGroupNodes
} else {
// No recompositions were requested in the range, skip it.
skipReaderToGroupEnd()
}
compoundKeyHash = recomposeCompoundKey
isComposing = wasComposing
}
/**
* The index in the insertTable overlap with indexes the slotTable so the group index used to
* track newly inserted groups is set to be negative offset from -2. This reserves -1 as the
* root index which is the parent value returned by the root groups of the slot table.
*
* This function will also restore a virtual index to its index in the insertTable which is
* not needed here but could be useful for debugging.
*/
private fun insertedGroupVirtualIndex(index: Int) = -2 - index
/**
* As operations to insert and remove nodes are recorded, the number of nodes that will be in
* the group after changes are applied is maintained in a side overrides table. This method
* updates that count and then updates any parent groups that include the nodes this group
* emits.
*/
private fun updateNodeCountOverrides(group: Int, newCount: Int) {
// The value of group can be negative which indicates it is tracking an inserted group
// instead of an existing group. The index is a virtual index calculated by
// insertedGroupVirtualIndex which corresponds to the location of the groups to insert in
// the insertTable.
val currentCount = updatedNodeCount(group)
if (currentCount != newCount) {
// Update the overrides
val delta = newCount - currentCount
var current = group
var minPending = pendingStack.size - 1
while (current != -1) {
val newCurrentNodes = updatedNodeCount(current) + delta
updateNodeCount(current, newCurrentNodes)
for (pendingIndex in minPending downTo 0) {
val pending = pendingStack.peek(pendingIndex)
if (pending != null && pending.updateNodeCount(current, newCurrentNodes)) {
minPending = pendingIndex - 1
break
}
}
@Suppress("LiftReturnOrAssignment")
if (current < 0) {
current = reader.parent
} else {
if (reader.isNode(current)) break
current = reader.parent(current)
}
}
}
}
/**
* Calculates the node index (the index in the child list of a node will appear in the
* resulting tree) for [group]. Passing in [recomposeGroup] and its node index in
* [recomposeIndex] allows the calculation to exit early if there is no node group between
* [group] and [recomposeGroup].
*/
private fun nodeIndexOf(
groupLocation: Int,
group: Int,
recomposeGroup: Int,
recomposeIndex: Int
): Int {
// Find the anchor group which is either the recomposeGroup or the first parent node
var anchorGroup = reader.parent(group)
while (anchorGroup != recomposeGroup) {
if (reader.isNode(anchorGroup)) break
anchorGroup = reader.parent(anchorGroup)
}
var index = if (reader.isNode(anchorGroup)) 0 else recomposeIndex
// An early out if the group and anchor are the same
if (anchorGroup == group) return index
// Walk down from the anc ghor group counting nodes of siblings in front of this group
var current = anchorGroup
val nodeIndexLimit = index + (updatedNodeCount(anchorGroup) - reader.nodeCount(group))
loop@ while (index < nodeIndexLimit) {
if (current == groupLocation) break
current++
while (current < groupLocation) {
val end = current + reader.groupSize(current)
if (groupLocation < end) continue@loop
index += updatedNodeCount(current)
current = end
}
break
}
return index
}
private fun updatedNodeCount(group: Int): Int {
if (group < 0) return nodeCountVirtualOverrides?.let { it[group] } ?: 0
val nodeCounts = nodeCountOverrides
if (nodeCounts != null) {
val override = nodeCounts[group]
if (override >= 0) return override
}
return reader.nodeCount(group)
}
private fun updateNodeCount(group: Int, count: Int) {
if (updatedNodeCount(group) != count) {
if (group < 0) {
val virtualCounts = nodeCountVirtualOverrides ?: run {
val newCounts = HashMap<Int, Int>()
nodeCountVirtualOverrides = newCounts
newCounts
}
virtualCounts[group] = count
} else {
val nodeCounts = nodeCountOverrides ?: run {
val newCounts = IntArray(reader.size)
newCounts.fill(-1)
nodeCountOverrides = newCounts
newCounts
}
nodeCounts[group] = count
}
}
}
private fun clearUpdatedNodeCounts() {
nodeCountOverrides = null
nodeCountVirtualOverrides = null
}
/**
* Records the operations necessary to move the applier the node affected by the previous
* group to the new group.
*/
private fun recordUpsAndDowns(oldGroup: Int, newGroup: Int, commonRoot: Int) {
val reader = reader
val nearestCommonRoot = reader.nearestCommonRootOf(
oldGroup,
newGroup,
commonRoot
)
// Record ups for the nodes between oldGroup and nearestCommonRoot
var current = oldGroup
while (current > 0 && current != nearestCommonRoot) {
if (reader.isNode(current)) recordUp()
current = reader.parent(current)
}
// Record downs from nearestCommonRoot to newGroup
doRecordDownsFor(newGroup, nearestCommonRoot)
}
private fun doRecordDownsFor(group: Int, nearestCommonRoot: Int) {
if (group > 0 && group != nearestCommonRoot) {
doRecordDownsFor(reader.parent(group), nearestCommonRoot)
if (reader.isNode(group)) recordDown(reader.nodeAt(group))
}
}
/**
* Calculate the compound key (a semi-unique key produced for every group in the composition)
* for [group]. Passing in the [recomposeGroup] and [recomposeKey] allows this method to exit
* early.
*/
private fun compoundKeyOf(group: Int, recomposeGroup: Int, recomposeKey: Int): Int {
return if (group == recomposeGroup) recomposeKey else run {
val groupKey = reader.groupCompoundKeyPart(group)
if (groupKey == movableContentKey)
groupKey
else
(
compoundKeyOf(
reader.parent(group),
recomposeGroup,
recomposeKey
) rol 3
) xor groupKey
}
}
private fun SlotReader.groupCompoundKeyPart(group: Int) =
if (hasObjectKey(group)) {
groupObjectKey(group)?.let {
when (it) {
is Enum<*> -> it.ordinal
is MovableContent<*> -> movableContentKey
else -> it.hashCode()
}
} ?: 0
} else groupKey(group).let {
if (it == reuseKey) groupAux(group)?.let { aux ->
if (aux == Composer.Empty) it else aux.hashCode()
} ?: it else it
}
internal fun tryImminentInvalidation(scope: RecomposeScopeImpl, instance: Any?): Boolean {
val anchor = scope.anchor ?: return false
val location = anchor.toIndexFor(slotTable)
if (isComposing && location >= reader.currentGroup) {
// if we are invalidating a scope that is going to be traversed during this
// composition.
invalidations.insertIfMissing(location, scope, instance)
return true
}
return false
}
@TestOnly
internal fun parentKey(): Int {
return if (inserting) {
writer.groupKey(writer.parent)
} else {
reader.groupKey(reader.parent)
}
}
/**
* Skip a group. Skips the group at the current location. This is only valid to call if the
* composition is not inserting.
*/
@ComposeCompilerApi
override fun skipCurrentGroup() {
if (invalidations.isEmpty()) {
skipGroup()
} else {
val reader = reader
val key = reader.groupKey
val dataKey = reader.groupObjectKey
val aux = reader.groupAux
updateCompoundKeyWhenWeEnterGroup(key, dataKey, aux)
startReaderGroup(reader.isNode, null)
recomposeToGroupEnd()
reader.endGroup()
updateCompoundKeyWhenWeExitGroup(key, dataKey, aux)
}
}
private fun skipReaderToGroupEnd() {
groupNodeCount = reader.parentNodes
reader.skipToGroupEnd()
}
/**
* Skip to the end of the group opened by [startGroup].
*/
@ComposeCompilerApi
override fun skipToGroupEnd() {
runtimeCheck(groupNodeCount == 0) {
"No nodes can be emitted before calling skipAndEndGroup"
}
currentRecomposeScope?.scopeSkipped()
if (invalidations.isEmpty()) {
skipReaderToGroupEnd()
} else {
recomposeToGroupEnd()
}
}
@ComposeCompilerApi
override fun deactivateToEndGroup(changed: Boolean) {
runtimeCheck(groupNodeCount == 0) {
"No nodes can be emitted before calling dactivateToEndGroup"
}
if (!inserting) {
if (!changed) {
skipReaderToGroupEnd()
return
}
val start = reader.currentGroup
val end = reader.currentEnd
for (group in start until end) {
reader.forEachData(group) { index, data ->
when (data) {
is RememberObserver -> {
reader.reposition(group)
recordSlotTableOperation { _, slots, rememberManager ->
runtimeCheck(data == slots.slot(group, index)) {
"Slot table is out of sync"
}
rememberManager.forgetting(data)
slots.set(index, Composer.Empty)
}
}
is RecomposeScopeImpl -> {
val composition = data.composition
if (composition != null) {
composition.pendingInvalidScopes = true
data.release()
}
reader.reposition(group)
recordSlotTableOperation { _, slots, _ ->
runtimeCheck(data == slots.slot(group, index)) {
"Slot table is out of sync"
}
slots.set(index, Composer.Empty)
}
}
}
}
}
invalidations.removeRange(start, end)
reader.reposition(start)
reader.skipToGroupEnd()
}
}
/**
* Start a restart group. A restart group creates a recompose scope and sets it as the current
* recompose scope of the composition. If the recompose scope is invalidated then this group
* will be recomposed. A recompose scope can be invalidated by calling invalidate on the object
* returned by [androidx.compose.runtime.currentRecomposeScope].
*/
@ComposeCompilerApi
override fun startRestartGroup(key: Int): Composer {
start(key, null, false, null)
addRecomposeScope()
return this
}
private fun addRecomposeScope() {
if (inserting) {
val scope = RecomposeScopeImpl(composition as CompositionImpl)
invalidateStack.push(scope)
updateValue(scope)
scope.start(compositionToken)
} else {
val invalidation = invalidations.removeLocation(reader.parent)
val slot = reader.next()
val scope = if (slot == Composer.Empty) {
// This code is executed when a previously deactivate region is becomes active
// again. See Composer.deactivateToEndGroup()
val newScope = RecomposeScopeImpl(composition as CompositionImpl)
updateValue(newScope)
newScope
} else slot as RecomposeScopeImpl
scope.requiresRecompose = invalidation != null
invalidateStack.push(scope)
scope.start(compositionToken)
}
}
/**
* End a restart group. If the recompose scope was marked used during composition then a
* [ScopeUpdateScope] is returned that allows attaching a lambda that will produce the same
* composition as was produced by this group (including calling [startRestartGroup] and
* [endRestartGroup]).
*/
@ComposeCompilerApi
override fun endRestartGroup(): ScopeUpdateScope? {
// This allows for the invalidate stack to be out of sync since this might be called during
// exception stack unwinding that might have not called the doneJoin/endRestartGroup in the
// the correct order.
val scope = if (invalidateStack.isNotEmpty()) invalidateStack.pop()
else null
scope?.requiresRecompose = false
scope?.end(compositionToken)?.let {
record { _, _, _ -> it(composition) }
}
val result = if (scope != null &&
!scope.skipped &&
(scope.used || forceRecomposeScopes)
) {
if (scope.anchor == null) {
scope.anchor = if (inserting) {
writer.anchor(writer.parent)
} else {
reader.anchor(reader.parent)
}
}
scope.defaultsInvalid = false
scope
} else {
null
}
end(isNode = false)
return result
}
@InternalComposeApi
override fun insertMovableContent(value: MovableContent<*>, parameter: Any?) {
@Suppress("UNCHECKED_CAST")
invokeMovableContentLambda(
value as MovableContent<Any?>,
currentCompositionLocalScope(),
parameter,
force = false
)
}
private fun invokeMovableContentLambda(
content: MovableContent<Any?>,
locals: CompositionLocalMap,
parameter: Any?,
force: Boolean
) {
// Start the movable content group
startMovableGroup(movableContentKey, content)
changed(parameter)
// All movable content has a compound hash value rooted at the content itself so the hash
// value doesn't change as the content moves in the tree.
val savedCompoundKeyHash = compoundKeyHash
try {
compoundKeyHash = movableContentKey
if (inserting) writer.markGroup()
// Capture the local providers at the point of the invocation. This allows detecting
// changes to the locals as the value moves well as enables finding the correct providers
// when applying late changes which might be very complicated otherwise.
val providersChanged = if (inserting) false else reader.groupAux != locals
if (providersChanged) providerUpdates[reader.currentGroup] = locals
start(compositionLocalMapKey, compositionLocalMap, false, locals)
// Either insert a place-holder to be inserted later (either created new or moved from
// another location) or (re)compose the movable content. This is forced if a new value
// needs to be created as a late change.
if (inserting && !force) {
writerHasAProvider = true
providerCache = null
// Create an anchor to the movable group
val anchor = writer.anchor(writer.parent(writer.parent))
val reference = MovableContentStateReference(
content,
parameter,
composition,
insertTable,
anchor,
emptyList(),
currentCompositionLocalScope()
)
parentContext.insertMovableContent(reference)
} else {
val savedProvidersInvalid = providersInvalid
providersInvalid = providersChanged
invokeComposable(this, { content.content(parameter) })
providersInvalid = savedProvidersInvalid
}
} finally {
// Restore the state back to what is expected by the caller.
endGroup()
compoundKeyHash = savedCompoundKeyHash
endMovableGroup()
}
}
@InternalComposeApi
override fun insertMovableContentReferences(
references: List<Pair<MovableContentStateReference, MovableContentStateReference?>>
) {
var completed = false
try {
insertMovableContentGuarded(references)
completed = true
} finally {
if (completed) {
cleanUpCompose()
} else {
// if we finished with error, cleanup more aggressively
abortRoot()
}
}
}
private fun insertMovableContentGuarded(
references: List<Pair<MovableContentStateReference, MovableContentStateReference?>>
) {
fun positionToParentOf(slots: SlotWriter, applier: Applier<Any?>, index: Int) {
while (!slots.indexInParent(index)) {
slots.skipToGroupEnd()
if (slots.isNode(slots.parent)) applier.up()
slots.endGroup()
}
}
fun currentNodeIndex(slots: SlotWriter): Int {
val original = slots.currentGroup
// Find parent node
var current = slots.parent
while (current >= 0 && !slots.isNode(current)) {
current = slots.parent(current)
}
var index = 0
current++
while (current < original) {
if (slots.indexInGroup(original, current)) {
if (slots.isNode(current)) index = 0
current++
} else {
index += if (slots.isNode(current)) 1 else slots.nodeCount(current)
current += slots.groupSize(current)
}
}
return index
}
fun positionToInsert(slots: SlotWriter, anchor: Anchor, applier: Applier<Any?>): Int {
val destination = slots.anchorIndex(anchor)
runtimeCheck(slots.currentGroup < destination)
positionToParentOf(slots, applier, destination)
var nodeIndex = currentNodeIndex(slots)
while (slots.currentGroup < destination) {
when {
slots.indexInCurrentGroup(destination) -> {
if (slots.isNode) {
applier.down(slots.node(slots.currentGroup))
nodeIndex = 0
}
slots.startGroup()
}
else -> nodeIndex += slots.skipGroup()
}
}
runtimeCheck(slots.currentGroup == destination)
return nodeIndex
}
withChanges(lateChanges) {
record(resetSlotsInstance)
references.fastForEach { (to, from) ->
val anchor = to.anchor
val location = to.slotTable.anchorIndex(anchor)
var effectiveNodeIndex = 0
realizeUps()
// Insert content at the anchor point
record { applier, slots, _ ->
@Suppress("UNCHECKED_CAST")
applier as Applier<Any?>
effectiveNodeIndex = positionToInsert(slots, anchor, applier)
}
if (from == null) {
val toSlotTable = to.slotTable
if (toSlotTable == insertTable) {
// We are going to compose reading the insert table which will also
// perform an insert. This would then cause both a reader and a writer to
// be created simultaneously which will throw an exception. To prevent
// that we release the old insert table and replace it with a fresh one.
// This allows us to read from the old table and write to the new table.
// This occurs when the placeholder version of movable content was inserted
// but no content was available to move so we now need to create the
// content.
createFreshInsertTable()
}
to.slotTable.read { reader ->
reader.reposition(location)
writersReaderDelta = location
val offsetChanges = mutableListOf<Change>()
recomposeMovableContent {
withChanges(offsetChanges) {
withReader(reader) {
invokeMovableContentLambda(
to.content,
to.locals,
to.parameter,
force = true
)
}
}
}
if (offsetChanges.isNotEmpty()) {
record { applier, slots, rememberManager ->
val offsetApplier = if (effectiveNodeIndex > 0)
OffsetApplier(applier, effectiveNodeIndex) else applier
offsetChanges.fastForEach { change ->
change(offsetApplier, slots, rememberManager)
}
}
}
}
} else {
// If the state was already removed from the from table then it will have a
// state recorded in the recomposer, retrieve that now if we can. If not the
// state is still in its original location, recompose over it there.
val resolvedState = parentContext.movableContentStateResolve(from)
val fromTable = resolvedState?.slotTable ?: from.slotTable
val fromAnchor = resolvedState?.slotTable?.anchor(0) ?: from.anchor
val nodesToInsert = fromTable.collectNodesFrom(fromAnchor)
// Insert nodes if necessary
if (nodesToInsert.isNotEmpty()) {
record { applier, _, _ ->
val base = effectiveNodeIndex
@Suppress("UNCHECKED_CAST")
nodesToInsert.fastForEachIndexed { i, node ->
applier as Applier<Any?>
applier.insertBottomUp(base + i, node)
applier.insertTopDown(base + i, node)
}
}
if (to.slotTable == slotTable) {
// Inserting the content into the current slot table then we need to
// update the virtual node counts. Otherwise, we are inserting into
// a new slot table which is being created, not updated, so the virtual
// node counts do not need to be updated.
val group = slotTable.anchorIndex(anchor)
updateNodeCount(
group,
updatedNodeCount(group) + nodesToInsert.size
)
}
}
// Copy the slot table into the anchor location
record { _, slots, _ ->
val state = resolvedState ?: parentContext.movableContentStateResolve(from)
?: composeRuntimeError("Could not resolve state for movable content")
// The slot table contains the movable content group plus the group
// containing the movable content's table which then contains the actual
// state to be inserted. The state is at index 2 in the table (for the
// two groups) and is inserted into the provider group at offset 1 from the
// current location.
val anchors = slots.moveIntoGroupFrom(1, state.slotTable, 2)
// For all the anchors that moved, if the anchor is tracking a recompose
// scope, update it to reference its new composer.
if (anchors.isNotEmpty()) {
val toComposition = to.composition as CompositionImpl
anchors.fastForEach { anchor ->
// The recompose scope is always at slot 0 of a restart group.
val recomposeScope = slots.slot(anchor, 0) as? RecomposeScopeImpl
// Check for null as the anchor might not be for a recompose scope
recomposeScope?.adoptedBy(toComposition)
}
}
}
fromTable.read { reader ->
withReader(reader) {
val newLocation = fromTable.anchorIndex(fromAnchor)
reader.reposition(newLocation)
writersReaderDelta = newLocation
val offsetChanges = mutableListOf<Change>()
withChanges(offsetChanges) {
recomposeMovableContent(
from = from.composition,
to = to.composition,
reader.currentGroup,
invalidations = from.invalidations
) {
invokeMovableContentLambda(
to.content,
to.locals,
to.parameter,
force = true
)
}
}
if (offsetChanges.isNotEmpty()) {
record { applier, slots, rememberManager ->
val offsetApplier = if (effectiveNodeIndex > 0)
OffsetApplier(applier, effectiveNodeIndex) else applier
offsetChanges.fastForEach { change ->
change(offsetApplier, slots, rememberManager)
}
}
}
}
}
}
record(skipToGroupEndInstance)
}
record { applier, slots, _ ->
@Suppress("UNCHECKED_CAST")
applier as Applier<Any?>
positionToParentOf(slots, applier, 0)
slots.endGroup()
}
writersReaderDelta = 0
}
}
private inline fun <R> withChanges(newChanges: MutableList<Change>, block: () -> R): R {
val savedChanges = changes
try {
changes = newChanges
return block()
} finally {
changes = savedChanges
}
}
private inline fun <R> withReader(reader: SlotReader, block: () -> R): R {
val savedReader = this.reader
val savedCountOverrides = nodeCountOverrides
nodeCountOverrides = null
try {
this.reader = reader
return block()
} finally {
this.reader = savedReader
nodeCountOverrides = savedCountOverrides
}
}
private fun <R> recomposeMovableContent(
from: ControlledComposition? = null,
to: ControlledComposition? = null,
index: Int? = null,
invalidations: List<Pair<RecomposeScopeImpl, IdentityArraySet<Any>?>> = emptyList(),
block: () -> R
): R {
val savedImplicitRootStart = this.implicitRootStart
val savedIsComposing = isComposing
val savedNodeIndex = nodeIndex
try {
implicitRootStart = false
isComposing = true
nodeIndex = 0
invalidations.fastForEach { (scope, instances) ->
if (instances != null) {
instances.fastForEach { instance ->
tryImminentInvalidation(scope, instance)
}
} else {
tryImminentInvalidation(scope, null)
}
}
return from?.delegateInvalidations(to, index ?: -1, block) ?: block()
} finally {
implicitRootStart = savedImplicitRootStart
isComposing = savedIsComposing
nodeIndex = savedNodeIndex
}
}
@ComposeCompilerApi
override fun sourceInformation(sourceInformation: String) {
if (inserting && sourceInformationEnabled) {
writer.insertAux(sourceInformation)
}
}
@ComposeCompilerApi
override fun sourceInformationMarkerStart(key: Int, sourceInformation: String) {
if (sourceInformationEnabled)
start(key, objectKey = null, isNode = false, data = sourceInformation)
}
@ComposeCompilerApi
override fun sourceInformationMarkerEnd() {
if (sourceInformationEnabled)
end(isNode = false)
}
override fun disableSourceInformation() {
sourceInformationEnabled = false
}
/**
* Synchronously compose the initial composition of [content]. This collects all the changes
* which must be applied by [ControlledComposition.applyChanges] to build the tree implied by
* [content].
*/
internal fun composeContent(
invalidationsRequested: IdentityArrayMap<RecomposeScopeImpl, IdentityArraySet<Any>?>,
content: @Composable () -> Unit
) {
runtimeCheck(changes.isEmpty()) { "Expected applyChanges() to have been called" }
doCompose(invalidationsRequested, content)
}
internal fun prepareCompose(block: () -> Unit) {
runtimeCheck(!isComposing) { "Preparing a composition while composing is not supported" }
isComposing = true
try {
block()
} finally {
isComposing = false
}
}
/**
* Synchronously recompose all invalidated groups. This collects the changes which must be
* applied by [ControlledComposition.applyChanges] to have an effect.
*/
internal fun recompose(
invalidationsRequested: IdentityArrayMap<RecomposeScopeImpl, IdentityArraySet<Any>?>
): Boolean {
runtimeCheck(changes.isEmpty()) { "Expected applyChanges() to have been called" }
// even if invalidationsRequested is empty we still need to recompose if the Composer has
// some invalidations scheduled already. it can happen when during some parent composition
// there were a change for a state which was used by the child composition. such changes
// will be tracked and added into `invalidations` list.
if (
invalidationsRequested.isNotEmpty() ||
invalidations.isNotEmpty() ||
forciblyRecompose
) {
doCompose(invalidationsRequested, null)
return changes.isNotEmpty()
}
return false
}
private fun doCompose(
invalidationsRequested: IdentityArrayMap<RecomposeScopeImpl, IdentityArraySet<Any>?>,
content: (@Composable () -> Unit)?
) {
runtimeCheck(!isComposing) { "Reentrant composition is not supported" }
trace("Compose:recompose") {
snapshot = currentSnapshot()
compositionToken = snapshot.id
providerUpdates.clear()
invalidationsRequested.forEach { scope, set ->
val location = scope.anchor?.location ?: return
invalidations.add(Invalidation(scope, location, set))
}
invalidations.sortBy { it.location }
nodeIndex = 0
var complete = false
isComposing = true
try {
startRoot()
// vv Experimental for forced
@Suppress("UNCHECKED_CAST")
val savedContent = nextSlot()
if (savedContent !== content && content != null) {
updateValue(content as Any?)
}
// ^^ Experimental for forced
// Ignore reads of derivedStateOf recalculations
observeDerivedStateRecalculations(
start = {
childrenComposing++
},
done = {
childrenComposing--
},
) {
if (content != null) {
startGroup(invocationKey, invocation)
invokeComposable(this, content)
endGroup()
} else if (
(forciblyRecompose || providersInvalid) &&
savedContent != null &&
savedContent != Composer.Empty
) {
startGroup(invocationKey, invocation)
@Suppress("UNCHECKED_CAST")
invokeComposable(this, savedContent as @Composable () -> Unit)
endGroup()
} else {
skipCurrentGroup()
}
}
endRoot()
complete = true
} finally {
isComposing = false
invalidations.clear()
if (!complete) abortRoot()
}
}
}
val hasInvalidations get() = invalidations.isNotEmpty()
private val SlotReader.node get() = node(parent)
private fun SlotReader.nodeAt(index: Int) = node(index)
private fun validateNodeExpected() {
runtimeCheck(nodeExpected) {
"A call to createNode(), emitNode() or useNode() expected was not expected"
}
nodeExpected = false
}
private fun validateNodeNotExpected() {
runtimeCheck(!nodeExpected) { "A call to createNode(), emitNode() or useNode() expected" }
}
/**
* Add a raw change to the change list. Once [record] is called, the operation is realized
* into the change list. The helper routines below reduce the number of operations that must
* be realized to change the previous tree to the new tree as well as update the slot table
* to prepare for the next composition.
*/
private fun record(change: Change) {
changes.add(change)
}
/**
* Record a change ensuring, when it is applied, that the applier is focused on the current
* node.
*/
private fun recordApplierOperation(change: Change) {
realizeUps()
realizeDowns()
record(change)
}
/**
* Record a change that will insert, remove or move a slot table group. This ensures the slot
* table is prepared for the change by ensuring the parent group is started and then ended
* as the group is left.
*/
private fun recordSlotEditingOperation(change: Change) {
realizeOperationLocation()
recordSlotEditing()
record(change)
}
/**
* Record a change ensuring, when it is applied, the write matches the current slot in the
* reader.
*/
private fun recordSlotTableOperation(forParent: Boolean = false, change: Change) {
realizeOperationLocation(forParent)
record(change)
}
// Navigation of the node tree is performed by recording all the locations of the nodes as
// they are traversed by the reader and recording them in the downNodes array. When the node
// navigation is realized all the downs in the down nodes is played to the applier.
//
// If an up is recorded before the corresponding down is realized then it is simply removed
// from the downNodes stack.
private var pendingUps = 0
private var downNodes = Stack<Any?>()
private fun realizeUps() {
val count = pendingUps
if (count > 0) {
pendingUps = 0
record { applier, _, _ -> repeat(count) { applier.up() } }
}
}
private fun realizeDowns(nodes: Array<Any?>) {
record { applier, _, _ ->
for (index in nodes.indices) {
@Suppress("UNCHECKED_CAST")
val nodeApplier = applier as Applier<Any?>
nodeApplier.down(nodes[index])
}
}
}
private fun realizeDowns() {
if (downNodes.isNotEmpty()) {
@Suppress("UNCHECKED_CAST")
realizeDowns(downNodes.toArray())
downNodes.clear()
}
}
private fun recordDown(node: Any?) {
@Suppress("UNCHECKED_CAST")
downNodes.push(node)
}
private fun recordUp() {
if (downNodes.isNotEmpty()) {
downNodes.pop()
} else {
pendingUps++
}
}
// Navigating the writer slot is performed relatively as the location of a group in the writer
// might be different than it is in the reader as groups can be inserted, deleted, or moved.
//
// writersReaderDelta tracks the difference between reader's current slot the current of
// the writer must be before the recorded change is applied. Moving the writer to a location
// is performed by advancing the writer the same the number of slots traversed by the reader
// since the last write change. This works transparently for inserts. For deletes the number
// of nodes deleted needs to be added to writersReaderDelta. When slots move the delta is
// updated as if the move has already taken place. The delta is updated again once the group
// begin edited is complete.
//
// The SlotTable requires that the group that contains any moves, inserts or removes must have
// the group that contains the moved, inserted or removed groups be started with a startGroup
// and terminated with a endGroup so the effects of the inserts, deletes, and moves can be
// recorded correctly in its internal data structures. The startedGroups stack maintains the
// groups that must be closed before we can move past the started group.
/**
* The skew or delta between where the writer will be and where the reader is now. This can
* be thought of as the unrealized distance the writer must move to match the current slot in
* the reader. When an operation affects the slot table the writer location must be realized
* by moving the writer slot table the unrealized distance.
*/
private var writersReaderDelta = 0
/**
* Record whether any groups were stared. If no groups were started then the root group
* doesn't need to be started or ended either.
*/
private var startedGroup = false
/**
* During late change calculation the group start/end is handled by [insertMovableContentReferences]
* directly instead of requiring implicit starts/end groups to be inserted.
*/
private var implicitRootStart = true
/**
* A stack of the location of the groups that were started.
*/
private val startedGroups = IntStack()
private fun realizeOperationLocation(forParent: Boolean = false) {
val location = if (forParent) reader.parent else reader.currentGroup
val distance = location - writersReaderDelta
runtimeCheck(distance >= 0) {
"Tried to seek backward"
}
if (distance > 0) {
record { _, slots, _ -> slots.advanceBy(distance) }
writersReaderDelta = location
}
}
private fun recordInsert(anchor: Anchor) {
if (insertFixups.isEmpty()) {
val insertTable = insertTable
recordSlotEditingOperation { _, slots, _ ->
slots.beginInsert()
slots.moveFrom(insertTable, anchor.toIndexFor(insertTable))
slots.endInsert()
}
} else {
val fixups = insertFixups.toMutableList()
insertFixups.clear()
realizeUps()
realizeDowns()
val insertTable = insertTable
recordSlotEditingOperation { applier, slots, rememberManager ->
insertTable.write { writer ->
fixups.fastForEach { fixup ->
fixup(applier, writer, rememberManager)
}
}
slots.beginInsert()
slots.moveFrom(insertTable, anchor.toIndexFor(insertTable))
slots.endInsert()
}
}
}
private fun recordFixup(change: Change) {
insertFixups.add(change)
}
private val insertUpFixups = Stack<Change>()
private fun recordInsertUpFixup(change: Change) {
insertUpFixups.push(change)
}
private fun registerInsertUpFixup() {
insertFixups.add(insertUpFixups.pop())
}
/**
* When a group is removed the reader will move but the writer will not so to ensure both the
* writer and reader are tracking the same slot we advance the [writersReaderDelta] to
* account for the removal.
*/
private fun recordDelete() {
// It is import that the movable content is reported first so it can be removed before the
// group itself is removed.
reportFreeMovableContent(reader.currentGroup)
recordSlotEditingOperation(change = removeCurrentGroupInstance)
writersReaderDelta += reader.groupSize
}
/**
* Report any movable content that the group contains as being removed and ready to be moved.
* Returns true if the group itself was removed.
*
* Returns the number of nodes left in place which is used to calculate the node index of
* any nested calls.
*
* @param groupBeingRemoved The group that is being removed from the table or 0 if the entire
* table is being removed.
*/
private fun reportFreeMovableContent(groupBeingRemoved: Int) {
fun reportGroup(group: Int, needsNodeDelete: Boolean, nodeIndex: Int): Int {
return if (reader.hasMark(group)) {
// If the group has a mark then it is either a movable content group or a
// composition context group
val key = reader.groupKey(group)
val objectKey = reader.groupObjectKey(group)
if (key == movableContentKey && objectKey is MovableContent<*>) {
// If the group is a movable content block schedule it to be removed and report
// that it is free to be moved to the parentContext. Nested movable content is
// recomposed if necessary once the group has been claimed by another insert.
// If the nested movable content ends up being removed this is reported during
// that recomposition so there is no need to look at child movable content here.
@Suppress("UNCHECKED_CAST")
val movableContent = objectKey as MovableContent<Any?>
val parameter = reader.groupGet(group, 0)
val anchor = reader.anchor(group)
val end = group + reader.groupSize(group)
val invalidations = this.invalidations.filterToRange(group, end).fastMap {
it.scope to it.instances
}
val reference = MovableContentStateReference(
movableContent,
parameter,
composition,
slotTable,
anchor,
invalidations,
currentCompositionLocalScope(group)
)
parentContext.deletedMovableContent(reference)
recordSlotEditing()
record { _, slots, _ -> releaseMovableGroupAtCurrent(reference, slots) }
if (needsNodeDelete) {
realizeMovement()
realizeUps()
realizeDowns()
val nodeCount = if (reader.isNode(group)) 1 else reader.nodeCount(group)
if (nodeCount > 0) {
recordRemoveNode(nodeIndex, nodeCount)
}
0 // These nodes were deleted
} else reader.nodeCount(group)
} else if (key == referenceKey && objectKey == reference) {
// Group is a composition context reference. As this is being removed assume
// all movable groups in the composition that have this context will also be
// released whe the compositions are disposed.
val contextHolder = reader.groupGet(group, 0) as? CompositionContextHolder
if (contextHolder != null) {
// The contextHolder can be EMPTY in cases wher the content has been
// deactivated. Content is deactivated if the content is just being
// held onto for recycling and is not otherwise active. In this case
// the composers we are likely to find here have already been disposed.
val compositionContext = contextHolder.ref
compositionContext.composers.forEach { composer ->
composer.reportAllMovableContent()
}
}
reader.nodeCount(group)
} else reader.nodeCount(group)
} else if (reader.containsMark(group)) {
// Traverse the group freeing the child movable content. This group is known to
// have at least one child that contains movable content because the group is
// marked as containing a mark.
val size = reader.groupSize(group)
val end = group + size
var current = group + 1
var runningNodeCount = 0
while (current < end) {
// A tree is not disassembled when it is removed, the root nodes of the
// sub-trees are removed, therefore, if we enter a node that contains movable
// content, the nodes should be removed so some future composition can
// re-insert them at a new location. Otherwise the applier will attempt to
// insert a node that already has a parent. If there is no node between the
// group removed and this group then the nodes will be removed by normal
// recomposition.
val isNode = reader.isNode(current)
if (isNode) {
realizeMovement()
recordDown(reader.node(current))
}
runningNodeCount += reportGroup(
group = current,
needsNodeDelete = isNode || needsNodeDelete,
nodeIndex = if (isNode) 0 else nodeIndex + runningNodeCount
)
if (isNode) {
realizeMovement()
recordUp()
}
current += reader.groupSize(current)
}
runningNodeCount
} else reader.nodeCount(group)
}
reportGroup(groupBeingRemoved, needsNodeDelete = false, nodeIndex = 0)
realizeMovement()
}
/**
* Release the reference the movable group stored in [slots] to the recomposer for to be used
* to insert to insert to other locations.
*/
private fun releaseMovableGroupAtCurrent(
reference: MovableContentStateReference,
slots: SlotWriter
) {
val slotTable = SlotTable()
// Write a table that as if it was written by a calling
// invokeMovableContentLambda because this might be removed from the
// composition before the new composition can be composed to receive it. When
// the new composition receives the state it must recompose over the state by
// calling invokeMovableContentLambda.
slotTable.write { writer ->
writer.beginInsert()
// This is the prefix created by invokeMovableContentLambda
writer.startGroup(movableContentKey, reference.content)
writer.markGroup()
writer.update(reference.parameter)
// Move the content into current location
slots.moveTo(reference.anchor, 1, writer)
// skip the group that was just inserted.
writer.skipGroup()
// End the group that represents the call to invokeMovableContentLambda
writer.endGroup()
writer.endInsert()
}
val state = MovableContentState(slotTable)
parentContext.movableContentStateReleased(reference, state)
}
/**
* Called during composition to report all the content of the composition will be released
* as this composition is to be disposed.
*/
private fun reportAllMovableContent() {
if (slotTable.containsMark()) {
val changes = mutableListOf<Change>()
deferredChanges = changes
slotTable.read { reader ->
this.reader = reader
withChanges(changes) {
reportFreeMovableContent(0)
realizeUps()
if (startedGroup) {
record(skipToGroupEndInstance)
recordEndRoot()
}
}
}
}
}
/**
* Called when reader current is moved directly, such as when a group moves, to [location].
*/
private fun recordReaderMoving(location: Int) {
val distance = reader.currentGroup - writersReaderDelta
// Ensure the next skip will account for the distance we have already travelled.
writersReaderDelta = location - distance
}
private fun recordSlotEditing() {
// During initial composition (when the slot table is empty), no group needs
// to be started.
if (reader.size > 0) {
val reader = reader
val location = reader.parent
if (startedGroups.peekOr(invalidGroupLocation) != location) {
if (!startedGroup && implicitRootStart) {
// We need to ensure the root group is started.
recordSlotTableOperation(change = startRootGroup)
startedGroup = true
}
if (location > 0) {
val anchor = reader.anchor(location)
startedGroups.push(location)
recordSlotTableOperation { _, slots, _ -> slots.ensureStarted(anchor) }
}
}
}
}
private fun recordEndGroup() {
val location = reader.parent
val currentStartedGroup = startedGroups.peekOr(-1)
runtimeCheck(currentStartedGroup <= location) { "Missed recording an endGroup" }
if (startedGroups.peekOr(-1) == location) {
startedGroups.pop()
recordSlotTableOperation(change = endGroupInstance)
}
}
private fun recordEndRoot() {
if (startedGroup) {
recordSlotTableOperation(change = endGroupInstance)
startedGroup = false
}
}
private fun finalizeCompose() {
realizeUps()
runtimeCheck(pendingStack.isEmpty()) { "Start/end imbalance" }
runtimeCheck(startedGroups.isEmpty()) { "Missed recording an endGroup()" }
cleanUpCompose()
}
private fun cleanUpCompose() {
pending = null
nodeIndex = 0
groupNodeCount = 0
writersReaderDelta = 0
compoundKeyHash = 0
nodeExpected = false
startedGroup = false
startedGroups.clear()
invalidateStack.clear()
clearUpdatedNodeCounts()
}
internal fun verifyConsistent() {
insertTable.verifyWellFormed()
}
private var previousRemove = -1
private var previousMoveFrom = -1
private var previousMoveTo = -1
private var previousCount = 0
private fun recordRemoveNode(nodeIndex: Int, count: Int) {
if (count > 0) {
runtimeCheck(nodeIndex >= 0) { "Invalid remove index $nodeIndex" }
if (previousRemove == nodeIndex) previousCount += count
else {
realizeMovement()
previousRemove = nodeIndex
previousCount = count
}
}
}
private fun recordMoveNode(from: Int, to: Int, count: Int) {
if (count > 0) {
if (previousCount > 0 && previousMoveFrom == from - previousCount &&
previousMoveTo == to - previousCount
) {
previousCount += count
} else {
realizeMovement()
previousMoveFrom = from
previousMoveTo = to
previousCount = count
}
}
}
private fun realizeMovement() {
val count = previousCount
previousCount = 0
if (count > 0) {
if (previousRemove >= 0) {
val removeIndex = previousRemove
previousRemove = -1
recordApplierOperation { applier, _, _ -> applier.remove(removeIndex, count) }
} else {
val from = previousMoveFrom
previousMoveFrom = -1
val to = previousMoveTo
previousMoveTo = -1
recordApplierOperation { applier, _, _ -> applier.move(from, to, count) }
}
}
}
/**
* A holder that will dispose of its [CompositionContext] when it leaves the composition
* that will not have its reference made visible to user code.
*/
// This warning becomes an error if its advice is followed since Composer needs its type param
@Suppress("RemoveRedundantQualifierName")
private class CompositionContextHolder(
val ref: ComposerImpl.CompositionContextImpl
) : RememberObserver {
override fun onRemembered() { }
override fun onAbandoned() {
ref.dispose()
}
override fun onForgotten() {
ref.dispose()
}
}
private inner class CompositionContextImpl(
override val compoundHashKey: Int,
override val collectingParameterInformation: Boolean
) : CompositionContext() {
var inspectionTables: MutableSet<MutableSet<CompositionData>>? = null
val composers = mutableSetOf<ComposerImpl>()
fun dispose() {
if (composers.isNotEmpty()) {
inspectionTables?.let {
for (composer in composers) {
for (table in it)
table.remove(composer.slotTable)
}
}
composers.clear()
}
}
override fun registerComposer(composer: Composer) {
super.registerComposer(composer as ComposerImpl)
composers.add(composer)
}
override fun unregisterComposer(composer: Composer) {
inspectionTables?.forEach { it.remove((composer as ComposerImpl).slotTable) }
composers.remove(composer)
}
override fun registerComposition(composition: ControlledComposition) {
parentContext.registerComposition(composition)
}
override fun unregisterComposition(composition: ControlledComposition) {
parentContext.unregisterComposition(composition)
}
override val effectCoroutineContext: CoroutineContext
get() = parentContext.effectCoroutineContext
@Suppress("OPT_IN_MARKER_ON_WRONG_TARGET")
@OptIn(ExperimentalComposeApi::class)
@get:OptIn(ExperimentalComposeApi::class)
override val recomposeCoroutineContext: CoroutineContext
get() = composition.recomposeCoroutineContext
override fun composeInitial(
composition: ControlledComposition,
content: @Composable () -> Unit
) {
parentContext.composeInitial(composition, content)
}
override fun invalidate(composition: ControlledComposition) {
// Invalidate ourselves with our parent before we invalidate a child composer.
// This ensures that when we are scheduling recompositions, parents always
// recompose before their children just in case a recomposition in the parent
// would also cause other recomposition in the child.
// If the parent ends up having no real invalidations to process we will skip work
// for that composer along a fast path later.
// This invalidation process could be made more efficient as it's currently N^2 with
// subcomposition meta-tree depth thanks to the double recursive parent walk
// performed here, but we currently assume a low N.
parentContext.invalidate([email protected])
parentContext.invalidate(composition)
}
override fun invalidateScope(scope: RecomposeScopeImpl) {
parentContext.invalidateScope(scope)
}
// This is snapshot state not because we need it to be observable, but because
// we need changes made to it in composition to be visible for the rest of the current
// composition and not become visible outside of the composition process until composition
// succeeds.
private var compositionLocalScope by mutableStateOf<CompositionLocalMap>(
persistentHashMapOf()
)
override fun getCompositionLocalScope(): CompositionLocalMap = compositionLocalScope
fun updateCompositionLocalScope(scope: CompositionLocalMap) {
compositionLocalScope = scope
}
override fun recordInspectionTable(table: MutableSet<CompositionData>) {
(
inspectionTables ?: HashSet<MutableSet<CompositionData>>().also {
inspectionTables = it
}
).add(table)
}
override fun startComposing() {
childrenComposing++
}
override fun doneComposing() {
childrenComposing--
}
override fun insertMovableContent(reference: MovableContentStateReference) {
parentContext.insertMovableContent(reference)
}
override fun deletedMovableContent(reference: MovableContentStateReference) {
parentContext.deletedMovableContent(reference)
}
override fun movableContentStateResolve(
reference: MovableContentStateReference
): MovableContentState? = parentContext.movableContentStateResolve(reference)
override fun movableContentStateReleased(
reference: MovableContentStateReference,
data: MovableContentState
) {
parentContext.movableContentStateReleased(reference, data)
}
}
private fun updateCompoundKeyWhenWeEnterGroup(groupKey: Int, dataKey: Any?, data: Any?) {
if (dataKey == null)
if (data != null && groupKey == reuseKey && data != Composer.Empty)
updateCompoundKeyWhenWeEnterGroupKeyHash(data.hashCode())
else
updateCompoundKeyWhenWeEnterGroupKeyHash(groupKey)
else if (dataKey is Enum<*>)
updateCompoundKeyWhenWeEnterGroupKeyHash(dataKey.ordinal)
else
updateCompoundKeyWhenWeEnterGroupKeyHash(dataKey.hashCode())
}
private fun updateCompoundKeyWhenWeEnterGroupKeyHash(keyHash: Int) {
compoundKeyHash = (compoundKeyHash rol 3) xor keyHash
}
private fun updateCompoundKeyWhenWeExitGroup(groupKey: Int, dataKey: Any?, data: Any?) {
if (dataKey == null)
if (data != null && groupKey == reuseKey && data != Composer.Empty)
updateCompoundKeyWhenWeExitGroupKeyHash(data.hashCode())
else
updateCompoundKeyWhenWeExitGroupKeyHash(groupKey)
else if (dataKey is Enum<*>)
updateCompoundKeyWhenWeExitGroupKeyHash(dataKey.ordinal)
else
updateCompoundKeyWhenWeExitGroupKeyHash(dataKey.hashCode())
}
private fun updateCompoundKeyWhenWeExitGroupKeyHash(groupKey: Int) {
compoundKeyHash = (compoundKeyHash xor groupKey.hashCode()) ror 3
}
override val recomposeScope: RecomposeScope? get() = currentRecomposeScope
override val recomposeScopeIdentity: Any? get() = currentRecomposeScope?.anchor
override fun rememberedValue(): Any? = nextSlot()
override fun updateRememberedValue(value: Any?) = updateValue(value)
override fun recordUsed(scope: RecomposeScope) { (scope as? RecomposeScopeImpl)?.used = true }
}
/**
* A helper receiver scope class used by [ComposeNode] to help write code to initialized and update a
* node.
*
* @see ComposeNode
*/
@kotlin.jvm.JvmInline
value class Updater<T> constructor(
@PublishedApi internal val composer: Composer
) {
/**
* Set the value property of the emitted node.
*
* Schedules [block] to be run when the node is first created or when [value] is different
* than the previous composition.
*
* @see update
*/
@Suppress("NOTHING_TO_INLINE") // Inlining the compare has noticeable impact
inline fun set(
value: Int,
noinline block: T.(value: Int) -> Unit
) = with(composer) {
if (inserting || rememberedValue() != value) {
updateRememberedValue(value)
composer.apply(value, block)
}
}
/**
* Set the value property of the emitted node.
*
* Schedules [block] to be run when the node is first created or when [value] is different
* than the previous composition.
*
* @see update
*/
fun <V> set(
value: V,
block: T.(value: V) -> Unit
) = with(composer) {
if (inserting || rememberedValue() != value) {
updateRememberedValue(value)
composer.apply(value, block)
}
}
/**
* Update the value of a property of the emitted node.
*
* Schedules [block] to be run when [value] is different than the previous composition. It is
* different than [set] in that it does not run when the node is created. This is used when
* initial value set by the [ComposeNode] in the constructor callback already has the correct value.
* For example, use [update} when [value] is passed into of the classes constructor
* parameters.
*
* @see set
*/
@Suppress("NOTHING_TO_INLINE") // Inlining the compare has noticeable impact
inline fun update(
value: Int,
noinline block: T.(value: Int) -> Unit
) = with(composer) {
val inserting = inserting
if (inserting || rememberedValue() != value) {
updateRememberedValue(value)
if (!inserting) apply(value, block)
}
}
/**
* Update the value of a property of the emitted node.
*
* Schedules [block] to be run when [value] is different than the previous composition. It is
* different than [set] in that it does not run when the node is created. This is used when
* initial value set by the [ComposeNode] in the constructor callback already has the correct value.
* For example, use [update} when [value] is passed into of the classes constructor
* parameters.
*
* @see set
*/
fun <V> update(
value: V,
block: T.(value: V) -> Unit
) = with(composer) {
val inserting = inserting
if (inserting || rememberedValue() != value) {
updateRememberedValue(value)
if (!inserting) apply(value, block)
}
}
/**
* Initialize emitted node.
*
* Schedule [block] to be executed after the node is created.
*
* This is only executed once. The can be used to call a method or set a value on a node
* instance that is required to be set after one or more other properties have been set.
*
* @see reconcile
*/
fun init(block: T.() -> Unit) {
if (composer.inserting) composer.apply<Unit, T>(Unit) {
block()
}
}
/**
* Reconcile the node to the current state.
*
* This is used when [set] and [update] are insufficient to update the state of the node
* based on changes passed to the function calling [ComposeNode].
*
* Schedules [block] to execute. As this unconditionally schedules [block] to executed it
* might be executed unnecessarily as no effort is taken to ensure it only executes when the
* values [block] captures have changed. It is highly recommended that [set] and [update] be
* used instead as they will only schedule their blocks to executed when the value passed to
* them has changed.
*/
@Suppress("MemberVisibilityCanBePrivate")
fun reconcile(block: T.() -> Unit) {
composer.apply<Unit, T>(Unit) {
this.block()
}
}
}
@kotlin.jvm.JvmInline
value class SkippableUpdater<T> constructor(
@PublishedApi internal val composer: Composer
) {
inline fun update(block: Updater<T>.() -> Unit) {
composer.startReplaceableGroup(0x1e65194f)
Updater<T>(composer).block()
composer.endReplaceableGroup()
}
}
internal fun SlotWriter.removeCurrentGroup(rememberManager: RememberManager) {
// Notify the lifecycle manager of any observers leaving the slot table
// The notification order should ensure that listeners are notified of leaving
// in opposite order that they are notified of entering.
// To ensure this order, we call `enters` as a pre-order traversal
// of the group tree, and then call `leaves` in the inverse order.
for (slot in groupSlots()) {
when (slot) {
is RememberObserver -> {
rememberManager.forgetting(slot)
}
is RecomposeScopeImpl -> {
val composition = slot.composition
if (composition != null) {
composition.pendingInvalidScopes = true
slot.release()
}
}
}
}
removeGroup()
}
// Mutable list
private fun <K, V> multiMap() = HashMap<K, LinkedHashSet<V>>()
private fun <K, V> HashMap<K, LinkedHashSet<V>>.put(key: K, value: V) = getOrPut(key) {
LinkedHashSet()
}.add(value)
private fun <K, V> HashMap<K, LinkedHashSet<V>>.remove(key: K, value: V) =
get(key)?.let {
it.remove(value)
if (it.isEmpty()) remove(key)
}
private fun <K, V> HashMap<K, LinkedHashSet<V>>.pop(key: K) = get(key)?.firstOrNull()?.also {
remove(key, it)
}
private fun getKey(value: Any?, left: Any?, right: Any?): Any? = (value as? JoinedKey)?.let {
if (it.left == left && it.right == right) value
else getKey(it.left, left, right) ?: getKey(
it.right,
left,
right
)
}
// Invalidation helpers
private fun MutableList<Invalidation>.findLocation(location: Int): Int {
var low = 0
var high = size - 1
while (low <= high) {
val mid = (low + high).ushr(1) // safe from overflows
val midVal = get(mid)
val cmp = midVal.location.compareTo(location)
when {
cmp < 0 -> low = mid + 1
cmp > 0 -> high = mid - 1
else -> return mid // key found
}
}
return -(low + 1) // key not found
}
private fun MutableList<Invalidation>.findInsertLocation(location: Int): Int =
findLocation(location).let { if (it < 0) -(it + 1) else it }
private fun MutableList<Invalidation>.insertIfMissing(
location: Int,
scope: RecomposeScopeImpl,
instance: Any?
) {
val index = findLocation(location)
if (index < 0) {
add(
-(index + 1),
Invalidation(
scope,
location,
instance?.let { i ->
IdentityArraySet<Any>().also { it.add(i) }
}
)
)
} else {
if (instance == null) {
get(index).instances = null
} else {
get(index).instances?.add(instance)
}
}
}
private fun MutableList<Invalidation>.firstInRange(start: Int, end: Int): Invalidation? {
val index = findInsertLocation(start)
if (index < size) {
val firstInvalidation = get(index)
if (firstInvalidation.location < end) return firstInvalidation
}
return null
}
private fun MutableList<Invalidation>.removeLocation(location: Int): Invalidation? {
val index = findLocation(location)
return if (index >= 0) removeAt(index) else null
}
private fun MutableList<Invalidation>.removeRange(start: Int, end: Int) {
val index = findInsertLocation(start)
while (index < size) {
val validation = get(index)
if (validation.location < end) removeAt(index)
else break
}
}
private fun MutableList<Invalidation>.filterToRange(
start: Int,
end: Int
): MutableList<Invalidation> {
val result = mutableListOf<Invalidation>()
var index = findInsertLocation(start)
while (index < size) {
val invalidation = get(index)
if (invalidation.location < end) result.add(invalidation)
else break
index++
}
return result
}
private fun Boolean.asInt() = if (this) 1 else 0
private fun Int.asBool() = this != 0
private fun SlotTable.collectNodesFrom(anchor: Anchor): List<Any?> {
val result = mutableListOf<Any?>()
read { reader ->
val index = anchorIndex(anchor)
fun collectFromGroup(group: Int) {
if (reader.isNode(group)) {
result.add(reader.node(group))
} else {
var current = group + 1
val end = group + reader.groupSize(group)
while (current < end) {
collectFromGroup(current)
current += reader.groupSize(current)
}
}
}
collectFromGroup(index)
}
return result
}
private fun SlotReader.distanceFrom(index: Int, root: Int): Int {
var count = 0
var current = index
while (current > 0 && current != root) {
current = parent(current)
count++
}
return count
}
// find the nearest common root
private fun SlotReader.nearestCommonRootOf(a: Int, b: Int, common: Int): Int {
// Early outs, to avoid calling distanceFrom in trivial cases
if (a == b) return a // A group is the nearest common root of itself
if (a == common || b == common) return common // If either is common then common is nearest
if (parent(a) == b) return b // if b is a's parent b is the nearest common root
if (parent(b) == a) return a // if a is b's parent a is the nearest common root
if (parent(a) == parent(b)) return parent(a) // if a an b share a parent it is common
// Find the nearest using distance from common
var currentA = a
var currentB = b
val aDistance = distanceFrom(a, common)
val bDistance = distanceFrom(b, common)
repeat(aDistance - bDistance) { currentA = parent(currentA) }
repeat(bDistance - aDistance) { currentB = parent(currentB) }
// Both ca and cb are now the same distance from a known common root,
// therefore, the first parent that is the same is the lowest common root.
while (currentA != currentB) {
currentA = parent(currentA)
currentB = parent(currentB)
}
// ca == cb so it doesn't matter which is returned
return currentA
}
private val removeCurrentGroupInstance: Change = { _, slots, rememberManager ->
slots.removeCurrentGroup(rememberManager)
}
private val skipToGroupEndInstance: Change = { _, slots, _ -> slots.skipToGroupEnd() }
private val endGroupInstance: Change = { _, slots, _ -> slots.endGroup() }
private val startRootGroup: Change = { _, slots, _ -> slots.ensureStarted(0) }
private val resetSlotsInstance: Change = { _, slots, _ -> slots.reset() }
private val KeyInfo.joinedKey: Any get() = if (objectKey != null) JoinedKey(key, objectKey) else key
/*
* Integer keys are arbitrary values in the biload range. The do not need to be unique as if
* there is a chance they will collide with a compiler generated key they are paired with a
* OpaqueKey to ensure they are unique.
*/
// rootKey doesn't need a corresponding OpaqueKey as it never has sibling nodes and will always
// a unique key.
private const val rootKey = 100
// An arbitrary key value for a node.
private const val nodeKey = 125
// An arbitrary key value for a node used to force the node to be replaced.
private const val nodeKeyReplace = 126
// An arbitrary key value for a node used to force the node to be replaced.
private const val defaultsKey = -127
@PublishedApi
internal const val invocationKey = 200
@PublishedApi
internal val invocation: Any = OpaqueKey("provider")
@PublishedApi
internal const val providerKey = 201
@PublishedApi
internal val provider: Any = OpaqueKey("provider")
@PublishedApi
internal const val compositionLocalMapKey = 202
@PublishedApi
internal val compositionLocalMap: Any = OpaqueKey("compositionLocalMap")
@PublishedApi
internal const val providerValuesKey = 203
@PublishedApi
internal val providerValues: Any = OpaqueKey("providerValues")
@PublishedApi
internal const val providerMapsKey = 204
@PublishedApi
internal val providerMaps: Any = OpaqueKey("providers")
@PublishedApi
internal const val referenceKey = 206
@PublishedApi
internal val reference: Any = OpaqueKey("reference")
@PublishedApi
internal const val reuseKey = 207
private const val invalidGroupLocation = -2
internal class ComposeRuntimeError(override val message: String) : IllegalStateException()
internal inline fun runtimeCheck(value: Boolean, lazyMessage: () -> Any) {
if (!value) {
val message = lazyMessage()
composeRuntimeError(message.toString())
}
}
internal fun runtimeCheck(value: Boolean) = runtimeCheck(value) { "Check failed" }
internal fun composeRuntimeError(message: String): Nothing {
throw ComposeRuntimeError(
"Compose Runtime internal error. Unexpected or incorrect use of the Compose " +
"internal runtime API ($message). Please report to Google or use " +
"https://goo.gle/compose-feedback"
)
}
| apache-2.0 | a70012e994efdaf1c39833a3a2c239ba | 37.280198 | 104 | 0.609636 | 5.018691 | false | false | false | false |
androidx/androidx | compose/ui/ui-graphics/src/desktopTest/kotlin/androidx/compose/ui/graphics/canvas/DesktopCanvasTest.kt | 3 | 9553 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.graphics.canvas
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.ClipOp
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.DesktopGraphicsTest
import androidx.compose.ui.graphics.FilterQuality
import androidx.compose.ui.graphics.Matrix
import androidx.compose.ui.graphics.Paint
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.VertexMode
import androidx.compose.ui.graphics.Vertices
import androidx.compose.ui.graphics.loadResourceBitmap
import androidx.compose.ui.graphics.withSave
import androidx.compose.ui.graphics.withSaveLayer
import androidx.compose.ui.test.InternalTestApi
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import org.junit.Test
@OptIn(InternalTestApi::class)
class DesktopCanvasTest : DesktopGraphicsTest() {
private val canvas: Canvas = initCanvas(widthPx = 16, heightPx = 16)
@Test
fun drawArc() {
canvas.drawArc(
left = 0f,
top = 0f,
right = 16f,
bottom = 16f,
startAngle = 0f,
sweepAngle = 90f,
useCenter = true,
paint = redPaint
)
canvas.drawArc(
left = 0f,
top = 0f,
right = 16f,
bottom = 16f,
startAngle = 90f,
sweepAngle = 90f,
useCenter = true,
paint = bluePaint
)
canvas.drawArc(
left = 0f,
top = 0f,
right = 16f,
bottom = 16f,
startAngle = 180f,
sweepAngle = 90f,
useCenter = false,
paint = greenPaint
)
canvas.drawArc(
left = 0f,
top = 0f,
right = 16f,
bottom = 16f,
startAngle = 270f,
sweepAngle = 90f,
useCenter = false,
paint = cyanPaint
)
screenshotRule.snap(surface)
}
@Test
fun drawCircle() {
canvas.drawCircle(Offset(8f, 8f), radius = 4f, paint = redPaint)
screenshotRule.snap(surface)
}
@Test
fun drawImage() {
canvas.drawImage(
image = loadResourceBitmap("androidx/compose/desktop/test.png"),
topLeftOffset = Offset(2f, 4f),
paint = redPaint
)
canvas.drawImage(
image = loadResourceBitmap("androidx/compose/desktop/test.png"),
topLeftOffset = Offset(-2f, 0f),
paint = redPaint
)
screenshotRule.snap(surface)
}
@Test
fun drawImageRect() {
canvas.drawImageRect(
image = loadResourceBitmap("androidx/compose/desktop/test.png"),
srcOffset = IntOffset(0, 2),
srcSize = IntSize(2, 4),
dstOffset = IntOffset(0, 4),
dstSize = IntSize(4, 12),
paint = redPaint.apply {
filterQuality = FilterQuality.None
}
)
screenshotRule.snap(surface)
}
@Test
fun drawLine() {
canvas.drawLine(
Offset(-4f, -4f), Offset(4f, 4f),
Paint().apply {
color = Color.Red
strokeWidth = 1f
strokeCap = StrokeCap.Butt
}
)
canvas.drawLine(
Offset(8f, 4f), Offset(8f, 12f),
Paint().apply {
color = Color.Blue
strokeWidth = 4f
strokeCap = StrokeCap.Butt
}
)
canvas.drawLine(
Offset(12f, 4f), Offset(12f, 12f),
Paint().apply {
color = Color.Green
strokeWidth = 4f
strokeCap = StrokeCap.Round
}
)
canvas.drawLine(
Offset(4f, 4f), Offset(4f, 12f),
Paint().apply {
color = Color.Black.copy(alpha = 0.5f)
strokeWidth = 4f
strokeCap = StrokeCap.Square
}
)
// should draw antialiased two-pixel line
canvas.drawLine(
Offset(4f, 4f), Offset(4f, 12f),
Paint().apply {
color = Color.Yellow
strokeWidth = 1f
strokeCap = StrokeCap.Butt
}
)
// should draw aliased one-pixel line
canvas.drawLine(
Offset(4f, 4f), Offset(4f, 12f),
Paint().apply {
color = Color.Yellow
strokeWidth = 1f
strokeCap = StrokeCap.Butt
isAntiAlias = false
}
)
// shouldn't draw any line
canvas.drawLine(
Offset(4f, 4f), Offset(4f, 12f),
Paint().apply {
color = Color.Yellow
strokeWidth = 0f
strokeCap = StrokeCap.Butt
isAntiAlias = false
}
)
screenshotRule.snap(surface)
}
@Test
fun drawOval() {
canvas.drawOval(left = 0f, top = 4f, right = 16f, bottom = 12f, paint = redPaint)
screenshotRule.snap(surface)
}
@Test
fun drawRect() {
canvas.drawRect(left = 2f, top = 0f, right = 6f, bottom = 8f, paint = redPaint)
canvas.drawRect(left = -4f, top = -4f, right = 4f, bottom = 4f, paint = bluePaint)
canvas.drawRect(left = 1f, top = 1f, right = 1f, bottom = 1f, paint = bluePaint)
screenshotRule.snap(surface)
}
@Test
fun drawRoundRect() {
canvas.drawRoundRect(
left = 0f,
top = 4f,
right = 16f,
bottom = 12f,
radiusX = 6f,
radiusY = 4f,
paint = redPaint
)
screenshotRule.snap(surface)
}
@Test
fun saveLayer() {
canvas.drawRect(0f, 0f, 16f, 16f, redPaint)
canvas.withSaveLayer(
Rect(left = 4f, top = 8f, right = 12f, bottom = 16f),
redPaint.apply {
blendMode = BlendMode.Plus
}
) {
canvas.drawLine(Offset(4f, 0f), Offset(4f, 16f), bluePaint)
}
screenshotRule.snap(surface)
}
@Test
fun transform() {
canvas.withSave {
canvas.translate(4f, 2f)
canvas.drawRect(left = 0f, top = 0f, right = 4f, bottom = 4f, paint = redPaint)
canvas.rotate(45f)
canvas.drawLine(Offset(0f, 0f), Offset(4f, 0f), paint = bluePaint)
}
canvas.withSave {
canvas.rotate(90f)
canvas.translate(8f, 0f)
canvas.drawRect(left = 0f, top = -4f, right = 4f, bottom = 0f, paint = greenPaint)
}
canvas.withSave {
canvas.translate(8f, 8f)
canvas.skew(1f, 0f)
canvas.drawRect(left = 0f, top = 0f, right = 4f, bottom = 4f, paint = yellowPaint)
}
canvas.withSave {
canvas.translate(8f, 8f)
canvas.skew(0f, 1f)
canvas.drawRect(left = 0f, top = 0f, right = 4f, bottom = 4f, paint = magentaPaint)
}
canvas.withSave {
canvas.concat(
Matrix().apply {
translate(12f, 2f)
}
)
canvas.drawRect(left = 0f, top = 0f, right = 4f, bottom = 4f, paint = cyanPaint)
}
screenshotRule.snap(surface)
}
@Test
fun clipRect() {
canvas.withSave {
canvas.clipRect(
left = 4f,
top = 4f,
right = 12f,
bottom = 12f,
clipOp = ClipOp.Intersect
)
canvas.drawRect(left = -4f, top = -4f, right = 20f, bottom = 20f, paint = redPaint)
}
canvas.drawRect(left = 4f, top = 0f, right = 8f, bottom = 4f, paint = bluePaint)
canvas.clipRect(left = 2f, top = 2f, right = 14f, bottom = 14f, clipOp = ClipOp.Difference)
canvas.drawRect(left = -4f, top = -4f, right = 20f, bottom = 20f, paint = greenPaint)
screenshotRule.snap(surface)
}
@Test
fun drawVertices() {
val positions = listOf(
Offset(0f, 0f),
Offset(16f, 0f),
Offset(8f, 8f),
Offset(16f, 8f),
Offset(0f, 16f),
Offset(16f, 16f),
)
val colors = listOf(
Color.Red, Color.Green, Color.Blue, Color.Cyan, Color.Magenta, Color.Yellow
)
val indices = listOf(0, 1, 2, 3, 4, 5)
canvas.drawVertices(
Vertices(VertexMode.Triangles, positions, positions, colors, indices),
BlendMode.SrcOver,
Paint()
)
screenshotRule.snap(surface)
}
}
| apache-2.0 | 898f0e4b0906a73393bcf633ab25c20f | 27.948485 | 99 | 0.533968 | 4.121225 | false | true | false | false |
androidx/androidx | room/room-paging/src/main/java/androidx/room/paging/LimitOffsetPagingSource.kt | 3 | 4831 | /*
* 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.room.paging
import android.database.Cursor
import androidx.annotation.NonNull
import androidx.annotation.RestrictTo
import androidx.paging.PagingSource
import androidx.paging.PagingState
import androidx.room.RoomDatabase
import androidx.room.RoomSQLiteQuery
import androidx.room.getQueryDispatcher
import androidx.room.paging.util.INITIAL_ITEM_COUNT
import androidx.room.paging.util.INVALID
import androidx.room.paging.util.ThreadSafeInvalidationObserver
import androidx.room.paging.util.getClippedRefreshKey
import androidx.room.paging.util.queryDatabase
import androidx.room.paging.util.queryItemCount
import androidx.room.withTransaction
import androidx.sqlite.db.SupportSQLiteQuery
import kotlinx.coroutines.withContext
import java.util.concurrent.atomic.AtomicInteger
/**
* An implementation of [PagingSource] to perform a LIMIT OFFSET query
*
* This class is used for Paging3 to perform Query and RawQuery in Room to return a PagingSource
* for Pager's consumption. Registers observers on tables lazily and automatically invalidates
* itself when data changes.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
abstract class LimitOffsetPagingSource<Value : Any>(
private val sourceQuery: RoomSQLiteQuery,
private val db: RoomDatabase,
vararg tables: String,
) : PagingSource<Int, Value>() {
constructor(
supportSQLiteQuery: SupportSQLiteQuery,
db: RoomDatabase,
vararg tables: String,
) : this(
sourceQuery = RoomSQLiteQuery.copyFrom(supportSQLiteQuery),
db = db,
tables = tables,
)
internal val itemCount: AtomicInteger = AtomicInteger(INITIAL_ITEM_COUNT)
private val observer = ThreadSafeInvalidationObserver(
tables = tables,
onInvalidated = ::invalidate
)
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Value> {
return withContext(db.getQueryDispatcher()) {
observer.registerIfNecessary(db)
val tempCount = itemCount.get()
// if itemCount is < 0, then it is initial load
if (tempCount == INITIAL_ITEM_COUNT) {
initialLoad(params)
} else {
nonInitialLoad(params, tempCount)
}
}
}
/**
* For the very first time that this PagingSource's [load] is called. Executes the count
* query (initializes [itemCount]) and db query within a transaction to ensure initial load's
* data integrity.
*
* For example, if the database gets updated after the count query but before the db query
* completes, the paging source may not invalidate in time, but this method will return
* data based on the original database that the count was performed on to ensure a valid
* initial load.
*/
private suspend fun initialLoad(params: LoadParams<Int>): LoadResult<Int, Value> {
return db.withTransaction {
val tempCount = queryItemCount(sourceQuery, db)
itemCount.set(tempCount)
queryDatabase(
params = params,
sourceQuery = sourceQuery,
db = db,
itemCount = tempCount,
convertRows = ::convertRows
)
}
}
private suspend fun nonInitialLoad(
params: LoadParams<Int>,
tempCount: Int,
): LoadResult<Int, Value> {
val loadResult = queryDatabase(
params = params,
sourceQuery = sourceQuery,
db = db,
itemCount = tempCount,
convertRows = ::convertRows
)
// manually check if database has been updated. If so, the observer's
// invalidation callback will invalidate this paging source
db.invalidationTracker.refreshVersionsSync()
@Suppress("UNCHECKED_CAST")
return if (invalid) INVALID as LoadResult.Invalid<Int, Value> else loadResult
}
@NonNull
protected abstract fun convertRows(cursor: Cursor): List<Value>
override fun getRefreshKey(state: PagingState<Int, Value>): Int? {
return state.getClippedRefreshKey()
}
override val jumpingSupported: Boolean
get() = true
}
| apache-2.0 | 6fe71816aa251e90b8ff52312038f645 | 35.323308 | 98 | 0.688677 | 4.787909 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/bukkit/SpigotModuleType.kt | 1 | 1557 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.bukkit
import com.demonwav.mcdev.asset.PlatformAssets
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.platform.AbstractModuleType
import com.demonwav.mcdev.platform.PlatformType
import com.demonwav.mcdev.platform.bukkit.generation.BukkitEventGenerationPanel
import com.demonwav.mcdev.platform.bukkit.util.BukkitConstants
import com.demonwav.mcdev.platform.bungeecord.util.BungeeCordConstants
import com.demonwav.mcdev.util.CommonColors
import com.intellij.psi.PsiClass
object SpigotModuleType : AbstractModuleType<BukkitModule<SpigotModuleType>>("org.spigotmc", "spigot-api") {
private const val ID = "SPIGOT_MODULE_TYPE"
init {
CommonColors.applyStandardColors(colorMap, BukkitConstants.CHAT_COLOR_CLASS)
CommonColors.applyStandardColors(colorMap, BungeeCordConstants.CHAT_COLOR_CLASS)
}
override val platformType = PlatformType.SPIGOT
override val icon = PlatformAssets.SPIGOT_ICON
override val id = ID
override val ignoredAnnotations = BukkitModuleType.IGNORED_ANNOTATIONS
override val listenerAnnotations = BukkitModuleType.LISTENER_ANNOTATIONS
override val isEventGenAvailable = true
override fun generateModule(facet: MinecraftFacet): BukkitModule<SpigotModuleType> = BukkitModule(facet, this)
override fun getEventGenerationPanel(chosenClass: PsiClass) = BukkitEventGenerationPanel(chosenClass)
}
| mit | 865a0d3ed7cb648720f977e2c7e7b972 | 36.97561 | 114 | 0.802184 | 4.325 | false | false | false | false |
hashicorp/terraform-provider-azuread | .teamcity/components/build_config_pull_request.kt | 1 | 1408 | import jetbrains.buildServer.configs.kotlin.v2019_2.*
class pullRequest(displayName: String, environment: String) {
val displayName = displayName
val environment = environment
fun buildConfiguration(providerName : String) : BuildType {
return BuildType {
// TC needs a consistent ID for dynamically generated packages
id(uniqueID(providerName))
name = displayName
vcs {
root(providerRepository)
cleanCheckout = true
}
steps {
var packageName = "\"%SERVICES%\""
ConfigureGoEnv()
DownloadTerraformBinary()
RunAcceptanceTestsForPullRequest(packageName)
}
failureConditions {
errorMessage = true
}
features {
Golang()
}
params {
TerraformAcceptanceTestParameters(defaultParallelism, "TestAcc", "12")
TerraformAcceptanceTestsFlag()
TerraformShouldPanicForSchemaErrors()
TerraformCoreBinaryTesting()
ReadOnlySettings()
text("SERVICES", "portal")
}
}
}
fun uniqueID(provider : String) : String {
return "%s_PR_%s".format(provider.toUpperCase(), environment.toUpperCase())
}
}
| mpl-2.0 | c538e3c59dc937b20fa344e18437a287 | 27.16 | 86 | 0.546165 | 5.966102 | false | true | false | false |
wordpress-mobile/AztecEditor-Android | aztec/src/main/kotlin/org/wordpress/aztec/formatting/InlineFormatter.kt | 1 | 20458 | package org.wordpress.aztec.formatting
import android.graphics.Typeface
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import androidx.annotation.ColorRes
import org.wordpress.android.util.AppLog
import org.wordpress.aztec.AztecAttributes
import org.wordpress.aztec.AztecPart
import org.wordpress.aztec.AztecText
import org.wordpress.aztec.AztecTextFormat
import org.wordpress.aztec.Constants
import org.wordpress.aztec.ITextFormat
import org.wordpress.aztec.spans.AztecCodeSpan
import org.wordpress.aztec.spans.AztecStrikethroughSpan
import org.wordpress.aztec.spans.AztecStyleBoldSpan
import org.wordpress.aztec.spans.AztecStyleCiteSpan
import org.wordpress.aztec.spans.AztecStyleItalicSpan
import org.wordpress.aztec.spans.AztecStyleEmphasisSpan
import org.wordpress.aztec.spans.AztecStyleStrongSpan
import org.wordpress.aztec.spans.AztecStyleSpan
import org.wordpress.aztec.spans.AztecUnderlineSpan
import org.wordpress.aztec.spans.HighlightSpan
import org.wordpress.aztec.spans.IAztecExclusiveInlineSpan
import org.wordpress.aztec.spans.IAztecInlineSpan
import org.wordpress.aztec.spans.MarkSpan
import org.wordpress.aztec.watchers.TextChangedEvent
/**
* <b>Important</b> - use [applySpan] to add new spans to the editor. This method will
* make sure any attributes belonging to the span are processed.
*/
class InlineFormatter(editor: AztecText, val codeStyle: CodeStyle, private val highlightStyle: HighlightStyle) : AztecFormatter(editor) {
data class CodeStyle(val codeBackground: Int, val codeBackgroundAlpha: Float, val codeColor: Int)
data class HighlightStyle(@ColorRes val color: Int)
fun toggle(textFormat: ITextFormat) {
if (!containsInlineStyle(textFormat)) {
val inlineSpan = makeInlineSpan(textFormat)
if (inlineSpan is IAztecExclusiveInlineSpan) {
// If text format is exclusive, remove all the inclusive text formats already applied
removeAllInclusiveFormats()
} else {
// If text format is inclusive, remove all the exclusive text formats already applied
removeAllExclusiveFormats()
}
applyInlineStyle(textFormat)
} else {
removeInlineStyle(textFormat)
}
}
private fun removeAllInclusiveFormats() {
editableText.getSpans(selectionStart, selectionEnd, IAztecInlineSpan::class.java).filter {
it !is IAztecExclusiveInlineSpan
}.forEach { removeInlineStyle(it) }
}
/**
* Removes all formats in the list but if none found, applies the first one
*/
fun toggleAny(textFormats: Set<ITextFormat>) {
if (!textFormats
.filter { containsInlineStyle(it) }
.fold(false) { _, containedTextFormat -> removeInlineStyle(containedTextFormat); true }) {
removeAllExclusiveFormats()
applyInlineStyle(textFormats.first())
}
}
private fun removeAllExclusiveFormats() {
editableText.getSpans(selectionStart, selectionEnd, IAztecExclusiveInlineSpan::class.java)
.forEach { removeInlineStyle(it) }
}
fun handleInlineStyling(textChangedEvent: TextChangedEvent) {
if (textChangedEvent.isEndOfBufferMarker()) return
// because we use SPAN_INCLUSIVE_INCLUSIVE for inline styles
// we need to make sure unselected styles are not applied
clearInlineStyles(textChangedEvent.inputStart, textChangedEvent.inputEnd, textChangedEvent.isNewLine())
if (textChangedEvent.isNewLine()) return
if (editor.formattingIsApplied()) {
for (item in editor.selectedStyles) {
when (item) {
AztecTextFormat.FORMAT_BOLD,
AztecTextFormat.FORMAT_STRONG,
AztecTextFormat.FORMAT_ITALIC,
AztecTextFormat.FORMAT_EMPHASIS,
AztecTextFormat.FORMAT_CITE,
AztecTextFormat.FORMAT_STRIKETHROUGH,
AztecTextFormat.FORMAT_UNDERLINE,
AztecTextFormat.FORMAT_CODE -> {
applyInlineStyle(item, textChangedEvent.inputStart, textChangedEvent.inputEnd)
}
AztecTextFormat.FORMAT_HIGHLIGHT -> {
applyInlineStyle(item, textChangedEvent.inputStart, textChangedEvent.inputEnd)
}
AztecTextFormat.FORMAT_MARK -> {
// For cases of an empty mark tag, either at the beginning of the text or in between
if (textChangedEvent.inputStart == 0 && textChangedEvent.inputEnd == 1) {
applyMarkInlineStyle(textChangedEvent.inputStart, textChangedEvent.inputEnd)
} else {
applyInlineStyle(item, textChangedEvent.inputStart, textChangedEvent.inputEnd)
}
}
else -> {
// do nothing
}
}
}
}
editor.setFormattingChangesApplied()
}
private fun clearInlineStyles(start: Int, end: Int, ignoreSelectedStyles: Boolean) {
val newStart = if (start > end) end else start
// if there is END_OF_BUFFER_MARKER at the end of or range, extend the range to include it
// remove lingering empty spans when removing characters
if (start > end) {
editableText.getSpans(newStart, end, IAztecInlineSpan::class.java)
.filter { editableText.getSpanStart(it) == editableText.getSpanEnd(it) }
.forEach { editableText.removeSpan(it) }
return
}
editableText.getSpans(newStart, end, IAztecInlineSpan::class.java).forEach {
if (!editor.selectedStyles.contains(spanToTextFormat(it)) || ignoreSelectedStyles || (newStart == 0 && end == 0) ||
(newStart > end && editableText.length > end && editableText[end] == '\n')) {
removeInlineStyle(it, newStart, end)
}
}
}
private fun applyInlineStyle(textFormat: ITextFormat, start: Int = selectionStart, end: Int = selectionEnd, attrs: AztecAttributes = AztecAttributes()) {
val spanToApply = makeInlineSpan(textFormat)
spanToApply.attributes = attrs
if (start >= end) {
return
}
var precedingSpan: IAztecInlineSpan? = null
var followingSpan: IAztecInlineSpan? = null
if (start >= 1) {
val previousSpans = editableText.getSpans(start - 1, start, IAztecInlineSpan::class.java)
previousSpans.forEach {
if (isSameInlineSpanType(it, spanToApply)) {
precedingSpan = it
return@forEach
}
}
if (precedingSpan != null) {
val spanStart = editableText.getSpanStart(precedingSpan)
val spanEnd = editableText.getSpanEnd(precedingSpan)
if (spanEnd > start) {
// ensure css style is applied
(precedingSpan as IAztecInlineSpan).applyInlineStyleAttributes(editableText, start, end)
return // we are adding text inside span - no need to do anything special
} else {
applySpan(precedingSpan as IAztecInlineSpan, spanStart, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
}
}
if (editor.length() > end) {
val nextSpans = editableText.getSpans(end, end + 1, IAztecInlineSpan::class.java)
nextSpans.forEach {
if (isSameInlineSpanType(it, spanToApply)) {
followingSpan = it
return@forEach
}
}
if (followingSpan != null) {
val spanEnd = editableText.getSpanEnd(followingSpan)
applySpan(followingSpan as IAztecInlineSpan, start, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
editableText.setSpan(followingSpan, start, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
}
if (precedingSpan == null && followingSpan == null) {
var existingSpanOfSameStyle: IAztecInlineSpan? = null
val spans = editableText.getSpans(start, end, IAztecInlineSpan::class.java)
spans.forEach {
if (isSameInlineSpanType(it, spanToApply)) {
existingSpanOfSameStyle = it
return@forEach
}
}
// if we already have same span within selection - reuse its attributes
if (existingSpanOfSameStyle != null) {
editableText.removeSpan(existingSpanOfSameStyle)
spanToApply.attributes = attrs
}
applySpan(spanToApply, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
joinStyleSpans(start, end)
}
private fun applyMarkInlineStyle(start: Int = selectionStart, end: Int = selectionEnd) {
val previousSpans = editableText.getSpans(start, end, MarkSpan::class.java)
previousSpans.forEach {
it.applyInlineStyleAttributes(editableText, start, end)
}
}
private fun applySpan(span: IAztecInlineSpan, start: Int, end: Int, type: Int) {
if (start > end || start < 0 || end > editableText.length) {
// If an external logger is available log the error there.
val extLogger = editor.externalLogger
if (extLogger != null) {
extLogger.log("InlineFormatter.applySpan - setSpan has end before start." +
" Start:" + start + " End:" + end)
extLogger.log("Logging the whole content" + editor.toPlainHtml())
}
// Now log in the default log
AppLog.w(AppLog.T.EDITOR, "InlineFormatter.applySpan - setSpan has end before start." +
" Start:" + start + " End:" + end)
AppLog.w(AppLog.T.EDITOR, "Logging the whole content" + editor.toPlainHtml())
return
}
editableText.setSpan(span, start, end, type)
span.applyInlineStyleAttributes(editableText, start, end)
}
fun spanToTextFormat(span: IAztecInlineSpan): ITextFormat? {
return when (span::class.java) {
AztecStyleBoldSpan::class.java -> AztecTextFormat.FORMAT_BOLD
AztecStyleStrongSpan::class.java -> AztecTextFormat.FORMAT_STRONG
AztecStyleItalicSpan::class.java -> AztecTextFormat.FORMAT_ITALIC
AztecStyleEmphasisSpan::class.java -> AztecTextFormat.FORMAT_EMPHASIS
AztecStyleCiteSpan::class.java -> AztecTextFormat.FORMAT_CITE
AztecStrikethroughSpan::class.java -> AztecTextFormat.FORMAT_STRIKETHROUGH
AztecUnderlineSpan::class.java -> AztecTextFormat.FORMAT_UNDERLINE
AztecCodeSpan::class.java -> AztecTextFormat.FORMAT_CODE
MarkSpan::class.java -> AztecTextFormat.FORMAT_MARK
HighlightSpan::class.java -> AztecTextFormat.FORMAT_HIGHLIGHT
else -> null
}
}
fun removeInlineStyle(spanToRemove: IAztecInlineSpan, start: Int = selectionStart, end: Int = selectionEnd) {
val textFormat = spanToTextFormat(spanToRemove) ?: return
val spans = editableText.getSpans(start, end, IAztecInlineSpan::class.java)
val list = ArrayList<AztecPart>()
spans.forEach {
if (isSameInlineSpanType(it, spanToRemove)) {
list.add(AztecPart(editableText.getSpanStart(it), editableText.getSpanEnd(it), it.attributes))
editableText.removeSpan(it)
}
}
// remove the CSS style span
removeInlineCssStyle()
list.forEach {
if (it.isValid) {
if (it.start < start) {
applyInlineStyle(textFormat, it.start, start, it.attr)
}
if (it.end > end) {
applyInlineStyle(textFormat, end, it.end, it.attr)
}
}
}
joinStyleSpans(start, end)
}
fun removeInlineCssStyle(start: Int = selectionStart, end: Int = selectionEnd) {
val spans = editableText.getSpans(start, end, ForegroundColorSpan::class.java)
spans.forEach {
editableText.removeSpan(it)
}
}
fun removeInlineStyle(textFormat: ITextFormat, start: Int = selectionStart, end: Int = selectionEnd) {
removeInlineStyle(makeInlineSpan(textFormat), start, end)
}
fun isSameInlineSpanType(firstSpan: IAztecInlineSpan, secondSpan: IAztecInlineSpan): Boolean {
// special check for StyleSpans
if (firstSpan is StyleSpan && secondSpan is StyleSpan) {
return firstSpan.style == secondSpan.style
}
return firstSpan.javaClass == secondSpan.javaClass
}
// TODO: Check if there is more efficient way to tidy spans
fun joinStyleSpans(start: Int, end: Int) {
// joins spans on the left
if (start > 1) {
val spansInSelection = editableText.getSpans(start, end, IAztecInlineSpan::class.java)
val spansBeforeSelection = editableText.getSpans(start - 1, start, IAztecInlineSpan::class.java)
spansInSelection.forEach { innerSpan ->
val inSelectionSpanEnd = editableText.getSpanEnd(innerSpan)
val inSelectionSpanStart = editableText.getSpanStart(innerSpan)
if (inSelectionSpanEnd == -1 || inSelectionSpanStart == -1) return@forEach
spansBeforeSelection.forEach { outerSpan ->
val outerSpanStart = editableText.getSpanStart(outerSpan)
if (isSameInlineSpanType(innerSpan, outerSpan) && inSelectionSpanEnd >= outerSpanStart) {
editableText.removeSpan(outerSpan)
applySpan(innerSpan, outerSpanStart, inSelectionSpanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
}
}
}
// joins spans on the right
if (editor.length() > end) {
val spansInSelection = editableText.getSpans(start, end, IAztecInlineSpan::class.java)
val spansAfterSelection = editableText.getSpans(end, end + 1, IAztecInlineSpan::class.java)
spansInSelection.forEach { innerSpan ->
val inSelectionSpanEnd = editableText.getSpanEnd(innerSpan)
val inSelectionSpanStart = editableText.getSpanStart(innerSpan)
if (inSelectionSpanEnd == -1 || inSelectionSpanStart == -1) return@forEach
spansAfterSelection.forEach { outerSpan ->
val outerSpanEnd = editableText.getSpanEnd(outerSpan)
if (isSameInlineSpanType(innerSpan, outerSpan) && outerSpanEnd >= inSelectionSpanStart) {
editableText.removeSpan(outerSpan)
applySpan(innerSpan, inSelectionSpanStart, outerSpanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
}
}
}
// joins spans withing selected text
val spansInSelection = editableText.getSpans(start, end, IAztecInlineSpan::class.java)
val spansToUse = editableText.getSpans(start, end, IAztecInlineSpan::class.java)
spansInSelection.forEach { appliedSpan ->
val spanStart = editableText.getSpanStart(appliedSpan)
val spanEnd = editableText.getSpanEnd(appliedSpan)
var neighbourSpan: IAztecInlineSpan? = null
spansToUse.forEach inner@ {
val aSpanStart = editableText.getSpanStart(it)
val aSpanEnd = editableText.getSpanEnd(it)
if (isSameInlineSpanType(it, appliedSpan)) {
if (aSpanStart == spanEnd || aSpanEnd == spanStart) {
neighbourSpan = it
return@inner
}
}
}
if (neighbourSpan != null) {
val neighbourSpanStart = editableText.getSpanStart(neighbourSpan)
val neighbourSpanEnd = editableText.getSpanEnd(neighbourSpan)
if (neighbourSpanStart == -1 || neighbourSpanEnd == -1)
return@forEach
// span we want to join is on the left
if (spanStart == neighbourSpanEnd) {
applySpan(appliedSpan, neighbourSpanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
} else if (spanEnd == neighbourSpanStart) {
applySpan(appliedSpan, spanStart, neighbourSpanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
editableText.removeSpan(neighbourSpan)
}
}
}
fun makeInlineSpan(textFormat: ITextFormat): IAztecInlineSpan {
return when (textFormat) {
AztecTextFormat.FORMAT_BOLD -> AztecStyleBoldSpan()
AztecTextFormat.FORMAT_STRONG -> AztecStyleStrongSpan()
AztecTextFormat.FORMAT_ITALIC -> AztecStyleItalicSpan()
AztecTextFormat.FORMAT_EMPHASIS -> AztecStyleEmphasisSpan()
AztecTextFormat.FORMAT_CITE -> AztecStyleCiteSpan()
AztecTextFormat.FORMAT_STRIKETHROUGH -> AztecStrikethroughSpan()
AztecTextFormat.FORMAT_UNDERLINE -> AztecUnderlineSpan()
AztecTextFormat.FORMAT_CODE -> AztecCodeSpan(codeStyle)
AztecTextFormat.FORMAT_HIGHLIGHT -> {
HighlightSpan(highlightStyle = highlightStyle, context = editor.context)
}
AztecTextFormat.FORMAT_MARK -> MarkSpan()
else -> AztecStyleSpan(Typeface.NORMAL)
}
}
fun containsInlineStyle(textFormat: ITextFormat, start: Int = selectionStart, end: Int = selectionEnd): Boolean {
val spanToCheck = makeInlineSpan(textFormat)
if (start > end) {
return false
}
if (start == end) {
if (start - 1 < 0 || start + 1 > editableText.length) {
return false
} else {
val before = editableText.getSpans(start - 1, start, IAztecInlineSpan::class.java)
.firstOrNull { isSameInlineSpanType(it, spanToCheck) }
val after = editableText.getSpans(start, start + 1, IAztecInlineSpan::class.java)
.firstOrNull { isSameInlineSpanType(it, spanToCheck) }
return before != null && after != null && isSameInlineSpanType(before, after)
}
} else {
val builder = StringBuilder()
// Make sure no duplicate characters be added
for (i in start until end) {
val spans = editableText.getSpans(i, i + 1, IAztecInlineSpan::class.java)
for (span in spans) {
if (isSameInlineSpanType(span, spanToCheck)) {
builder.append(editableText.subSequence(i, i + 1).toString())
break
}
}
}
val originalText = editableText.subSequence(start, end).replace("\n".toRegex(), "")
val textOfCombinedSpans = builder.toString().replace("\n".toRegex(), "")
return originalText.isNotEmpty() && originalText == textOfCombinedSpans
}
}
fun tryRemoveLeadingInlineStyle() {
val selectionStart = editor.selectionStart
val selectionEnd = editor.selectionEnd
if (selectionStart == 1 && selectionEnd == selectionStart) {
editableText.getSpans(0, 0, IAztecInlineSpan::class.java).forEach {
if (editableText.getSpanEnd(it) == selectionEnd && editableText.getSpanEnd(it) == selectionStart) {
editableText.removeSpan(it)
}
}
} else if (editor.length() == 1 && editor.text[0] == Constants.END_OF_BUFFER_MARKER) {
editableText.getSpans(0, 1, IAztecInlineSpan::class.java).forEach {
if (editableText.getSpanStart(it) == 1 && editableText.getSpanEnd(it) == 1) {
editableText.removeSpan(it)
}
}
}
}
}
| mpl-2.0 | 411dba6cbf9defc2587f982f8916e6e9 | 43.37744 | 157 | 0.611594 | 4.916607 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/ui/modules/editor/EditorPresenter.kt | 2 | 7148 | package ru.fantlab.android.ui.modules.editor
import android.annotation.SuppressLint
import com.github.kittinunf.fuel.core.ProgressCallback
import io.reactivex.Observable
import io.reactivex.functions.Consumer
import ru.fantlab.android.R
import ru.fantlab.android.data.dao.model.Response
import ru.fantlab.android.data.dao.model.TopicMessage
import ru.fantlab.android.data.dao.model.TopicMessageDraft
import ru.fantlab.android.helper.BundleConstant.EDITOR_DRAFT_TYPE
import ru.fantlab.android.helper.BundleConstant.EDITOR_EDIT_RESPONSE
import ru.fantlab.android.helper.BundleConstant.EDITOR_EDIT_TOPIC_MESSAGE
import ru.fantlab.android.helper.BundleConstant.EDITOR_MESSAGE_TYPE
import ru.fantlab.android.helper.BundleConstant.EDITOR_NEW_COMMENT
import ru.fantlab.android.helper.BundleConstant.EDITOR_NEW_MESSAGE
import ru.fantlab.android.helper.BundleConstant.EDITOR_NEW_RESPONSE
import ru.fantlab.android.helper.BundleConstant.EDITOR_NEW_TOPIC_DRAFT_MESSAGE
import ru.fantlab.android.helper.BundleConstant.EDITOR_NEW_TOPIC_MESSAGE
import ru.fantlab.android.helper.InputHelper
import ru.fantlab.android.helper.PrefGetter
import ru.fantlab.android.helper.implementError
import ru.fantlab.android.helper.observe
import ru.fantlab.android.provider.rest.DataManager
import ru.fantlab.android.provider.rest.DataManager.getTopicAttachUrl
import ru.fantlab.android.provider.rest.DataManager.getTopicDraftAttachUrl
import ru.fantlab.android.provider.rest.DataManager.sendTopicAttach
import ru.fantlab.android.ui.base.mvp.presenter.BasePresenter
import java.io.File
class EditorPresenter : BasePresenter<EditorMvp.View>(), EditorMvp.Presenter {
override fun onHandleSubmission(savedText: CharSequence?, extraType: String?,
itemId: Int?, reviewComment: Response?, mode: String) {
if (extraType == null || itemId == null) {
throw NullPointerException("not have required parameters")
}
when (extraType) {
EDITOR_NEW_RESPONSE -> {
onEditorNewResponse(itemId, savedText, mode)
}
EDITOR_EDIT_RESPONSE -> {
val extraId = view?.getExtraIds()
if (extraId != null) onEditorEditResponse(itemId, extraId, savedText)
}
EDITOR_NEW_MESSAGE -> {
if (itemId == PrefGetter.getLoggedUser()?.id) {
sendToView { it.showErrorMessage("Ошибка") }
return
}
onEditorNewMessage(itemId, savedText, mode)
}
EDITOR_NEW_TOPIC_MESSAGE -> {
if (itemId < 1) {
sendToView { it.showErrorMessage("Ошибка") }
return
}
onEditorNewTopicMessage(itemId, savedText, mode)
}
EDITOR_EDIT_TOPIC_MESSAGE -> {
if (itemId < 1) {
sendToView { it.showErrorMessage("Ошибка") }
return
}
onEditorEditTopicMessage(itemId, savedText)
}
EDITOR_NEW_COMMENT -> {
onEditorNewComment(itemId, savedText)
}
}
}
override fun onEditorNewResponse(id: Int, savedText: CharSequence?, mode: String) {
if (!InputHelper.isEmpty(savedText)) {
makeRestCall(
DataManager.sendResponse(id, savedText, mode).toObservable(),
Consumer { result -> sendToView { it.onSendMessageResult(result) } }
)
}
}
override fun onEditorEditResponse(workId: Int, commentId: Int, newText: CharSequence?) {
if (!InputHelper.isEmpty(newText)) {
makeRestCall(
DataManager.editResponse(workId, commentId, newText).toObservable(),
Consumer { result -> sendToView { it.onSendMessageResult(result) } }
)
}
}
override fun onEditorNewMessage(id: Int, savedText: CharSequence?, mode: String) {
if (!InputHelper.isEmpty(savedText)) {
makeRestCall(
DataManager.sendMessage(id, savedText, mode).toObservable(),
Consumer { result -> sendToView { it.onSendMessageResult(result) } }
)
}
}
override fun onEditorNewTopicMessage(topicId: Int, savedText: CharSequence?, mode: String) {
if (!InputHelper.isEmpty(savedText)) {
when (mode) {
EDITOR_MESSAGE_TYPE -> makeRestCall(
DataManager.sendTopicMessage(topicId, savedText).toObservable(),
Consumer { result ->
if (view?.getAttachesList()?.isNullOrEmpty() == true)
sendToView { it.onSendNewTopicMessage(result.message) }
else
onUploadAttach(EDITOR_NEW_TOPIC_MESSAGE, result.message)
}
)
EDITOR_DRAFT_TYPE -> makeRestCall(
DataManager.sendTopicMessageDraft(view?.getExtraIds()
?: -1, savedText).toObservable(),
Consumer { result ->
if (view?.getAttachesList()?.isNullOrEmpty() == true)
sendToView { it.onSendNewTopicMessageDraft(result.message) }
else
onUploadAttach(EDITOR_NEW_TOPIC_DRAFT_MESSAGE, result.message)
}
)
}
}
}
override fun onEditorEditTopicMessage(messageId: Int, savedText: CharSequence?) {
if (!InputHelper.isEmpty(savedText)) {
makeRestCall(
DataManager.editTopicMessage(messageId, savedText).toObservable(),
Consumer { _ -> sendToView { it.onEditTopicMessage(messageId, savedText.toString()) } }
)
}
}
override fun onEditorNewComment(id: Int, savedText: CharSequence?) {}
@SuppressLint("CheckResult")
override fun <T> onUploadAttach(type: String, message: T) {
sendToView { it.initAttachUpload() }
Observable.fromIterable(view?.getAttachesList())
.flatMap { attach ->
sendToView { it.onPrepareUploadFile(attach) }
when (type) {
EDITOR_NEW_TOPIC_MESSAGE -> getTopicAttachUrl((message as TopicMessage).message.id, attach.filename, attach.filepath).toObservable()
EDITOR_NEW_TOPIC_DRAFT_MESSAGE -> getTopicDraftAttachUrl(view?.getExtraIds() ?: -1, attach.filename, attach.filepath).toObservable()
else -> null
}
}
.doOnNext { attach ->
sendToView { it.onNotifyUploadAttach(attach.third, attach.second, 0) }
}
.flatMap { attach ->
var lastUpdate = 0L
val handler: ProgressCallback = { readBytes, totalBytes ->
if (System.currentTimeMillis() - lastUpdate > 800) {
lastUpdate = System.currentTimeMillis()
val progress = readBytes.toFloat() / totalBytes.toFloat() * 100
sendToView { it.onNotifyUploadAttach(attach.third, attach.second, progress.toInt()) }
}
}
when (type) {
EDITOR_NEW_TOPIC_MESSAGE -> {
sendTopicAttach(attach.first, attach.second, File(attach.third), handler)
}
else -> sendTopicAttach(attach.first, attach.second, File(attach.third), handler)
}.toObservable()
}
.observe()
.doOnComplete {
when (type) {
EDITOR_NEW_TOPIC_MESSAGE -> sendToView { it.onSendNewTopicMessage(message as TopicMessage) }
EDITOR_NEW_TOPIC_DRAFT_MESSAGE -> sendToView { it.onSendNewTopicMessageDraft(message as TopicMessageDraft) }
}
}
.subscribe({ result ->
if (result.first == 200)
sendToView { it.onAttachUploaded(result.second) }
else
sendToView { it.showMessage(R.string.error, R.string.request_error) }
}, { throwable ->
throwable.implementError(view)
when (type) {
EDITOR_NEW_TOPIC_MESSAGE -> sendToView { it.onSendNewTopicMessage(message as TopicMessage) }
EDITOR_NEW_TOPIC_DRAFT_MESSAGE -> sendToView { it.onSendNewTopicMessageDraft(message as TopicMessageDraft) }
}
})
}
}
| gpl-3.0 | 7552a827a6371f00da14276c44747d3e | 36.925532 | 138 | 0.71683 | 3.76452 | false | false | false | false |
EmmyLua/IntelliJ-EmmyLua | src/main/java/com/tang/intellij/lua/psi/search/LuaShortNamesManager.kt | 2 | 2725 | /*
* Copyright (c) 2017. tangzx([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.tang.intellij.lua.psi.search
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.util.Processor
import com.tang.intellij.lua.psi.LuaClass
import com.tang.intellij.lua.psi.LuaClassMember
import com.tang.intellij.lua.psi.LuaTypeAlias
import com.tang.intellij.lua.psi.LuaTypeDef
import com.tang.intellij.lua.search.SearchContext
import com.tang.intellij.lua.ty.ITyClass
abstract class LuaShortNamesManager {
companion object {
val EP_NAME = ExtensionPointName.create<LuaShortNamesManager>("com.tang.intellij.lua.luaShortNamesManager")
private val KEY = Key.create<LuaShortNamesManager>("com.tang.intellij.lua.luaShortNamesManager")
fun getInstance(project: Project): LuaShortNamesManager {
var instance = project.getUserData(KEY)
if (instance == null) {
instance = CompositeLuaShortNamesManager()
project.putUserData(KEY, instance)
}
return instance
}
}
abstract fun findClass(name: String, context: SearchContext): LuaClass?
abstract fun findMember(type: ITyClass, fieldName: String, context: SearchContext): LuaClassMember?
abstract fun processAllClassNames(project: Project, processor: Processor<String>): Boolean
abstract fun processClassesWithName(name: String, context: SearchContext, processor: Processor<LuaClass>): Boolean
abstract fun getClassMembers(clazzName: String, context: SearchContext): Collection<LuaClassMember>
abstract fun processAllMembers(type: ITyClass, fieldName: String, context: SearchContext, processor: Processor<LuaClassMember>): Boolean
open fun findAlias(name: String, context: SearchContext): LuaTypeAlias? {
return null
}
open fun processAllAlias(project: Project, processor: Processor<String>): Boolean {
return true
}
open fun findTypeDef(name: String, context: SearchContext): LuaTypeDef? {
return findClass(name, context) ?: findAlias(name, context)
}
} | apache-2.0 | 6f675d0c07d9bc52432435f6f215327f | 38.507246 | 140 | 0.74055 | 4.409385 | false | false | false | false |
develar/mapsforge-tile-server | mapsforge-ex/src/TileServerDatabaseRenderer.kt | 1 | 8068 | package org.mapsforge.map.layer.renderer
import org.mapsforge.core.graphics.Bitmap
import org.mapsforge.core.graphics.GraphicFactory
import org.mapsforge.core.graphics.Paint
import org.mapsforge.core.graphics.Position
import org.mapsforge.core.mapelements.MapElementContainer
import org.mapsforge.core.mapelements.SymbolContainer
import org.mapsforge.core.model.Point
import org.mapsforge.core.model.Tag
import org.mapsforge.core.model.Tile
import org.mapsforge.core.util.MercatorProjection
import org.mapsforge.map.reader.MapDatabase
import org.mapsforge.map.reader.MapReadResult
import org.mapsforge.map.reader.PointOfInterest
import org.mapsforge.map.rendertheme.RenderCallback
import org.mapsforge.map.rendertheme.rule.RenderTheme
import java.util.ArrayList
import java.util.Arrays
import java.util.Collections
import java.util.HashSet
public class TileServerDatabaseRenderer(private val mapDatabase:MapDatabase?, private val graphicFactory:GraphicFactory) : RenderCallback {
private val currentLabels = ArrayList<MapElementContainer>()
private val currentWayLabels = HashSet<MapElementContainer>()
private var drawingLayers:List<MutableList<ShapePaintContainer>>? = null
private val ways = arrayOfNulls<ArrayList<MutableList<ShapePaintContainer>>>(LAYERS)
private val canvas = graphicFactory.createCanvas() as CanvasEx
public var renderTheme:RenderTheme? = null
set (value) {
if ($renderTheme == value) {
return;
}
$renderTheme = value
val levels = value!!.getLevels()
for (i in 0..LAYERS - 1) {
var innerWayList = ways[i]
if (innerWayList == null) {
innerWayList = ArrayList<MutableList<ShapePaintContainer>>(levels)
ways[i] = innerWayList
}
else {
innerWayList.ensureCapacity(levels)
}
for (j in 0..levels - 1) {
innerWayList.add(ArrayList<ShapePaintContainer>(0))
}
}
}
companion object {
private val LAYERS = 11
private val TAG_NATURAL_WATER = Tag("natural", "water")
private fun getTilePixelCoordinates(tileSize:Int):Array<Point> {
val emptyPoint = Point(0.0, 0.0)
return array(emptyPoint, Point(tileSize.toDouble(), 0.0), Point(tileSize.toDouble(), tileSize.toDouble()), Point(0.0, tileSize.toDouble()), emptyPoint)
}
private fun getValidLayer(layer:Byte):Int {
if (layer < 0) {
return 0
}
else
if (layer >= LAYERS) {
return LAYERS - 1
}
else {
return layer.toInt()
}
}
private fun collisionFreeOrdered(input:List<MapElementContainer>):List<MapElementContainer> {
// sort items by priority (highest first)
input.sortBy(Collections.reverseOrder())
// in order of priority, see if an item can be drawn, i.e. none of the items
// in the currentItemsToDraw list clashes with it.
val output = ArrayList<MapElementContainer>(input.size())
for (item in input) {
var hasSpace = true
for (outputElement in output) {
if (outputElement.clashesWith(item)) {
hasSpace = false
break
}
}
if (hasSpace) {
item.incrementRefCount()
output.add(item)
}
}
return output
}
}
public fun renderTile(tile:Tile):ByteArray {
@suppress("CAST_NEVER_SUCCEEDS")
val ways = this.ways as Array<List<MutableList<ShapePaintContainer>>>
if (mapDatabase != null) {
processReadMapData(ways, mapDatabase.readMapData(tile), tile)
}
canvas.reset()
drawWays(ways, canvas)
// now draw the ways and the labels
drawMapElements(currentWayLabels, tile, canvas)
drawMapElements(collisionFreeOrdered(currentLabels), tile, canvas)
// clear way list
for (innerWayList in ways) {
for (shapePaintContainers in innerWayList) {
shapePaintContainers.clear()
}
}
currentLabels.clear()
currentWayLabels.clear()
return canvas.build()
}
override fun renderArea(way:PolylineContainer, fill:Paint, stroke:Paint?, level:Int) {
drawingLayers!![level].add(ShapePaintContainer(way, fill, stroke, 0f))
}
override fun renderAreaCaption(way:PolylineContainer, priority:Int, caption:String, horizontalOffset:Float, verticalOffset:Float, fill:Paint, stroke:Paint?, position:Position, maxTextWidth:Int) {
val centerPoint = way.getCenterAbsolute().offset(horizontalOffset.toDouble(), verticalOffset.toDouble())
currentLabels.add(graphicFactory.createPointTextContainer(centerPoint, priority, caption, fill, stroke, null, position, maxTextWidth))
}
override fun renderAreaSymbol(way:PolylineContainer, priority:Int, symbol:Bitmap) {
currentLabels.add(SymbolContainer(way.getCenterAbsolute(), priority, symbol))
}
override fun renderPointOfInterestCaption(poi:PointOfInterest, priority:Int, caption:String, horizontalOffset:Float, verticalOffset:Float, fill:Paint, stroke:Paint?, position:Position, maxTextWidth:Int, tile:Tile) {
val poiPosition = MercatorProjection.getPixelAbsolute(poi.position, tile.zoomLevel, tile.tileSize)
currentLabels.add(graphicFactory.createPointTextContainer(poiPosition.offset(horizontalOffset.toDouble(), verticalOffset.toDouble()), priority, caption, fill, stroke, null, position, maxTextWidth))
}
override fun renderPointOfInterestCircle(poi:PointOfInterest, radius:Float, fill:Paint, stroke:Paint?, level:Int, tile:Tile) {
val poiPosition = MercatorProjection.getPixelRelativeToTile(poi.position, tile)
drawingLayers!![level].add(ShapePaintContainer(CircleContainer(poiPosition, radius), fill, stroke, 0f))
}
override fun renderPointOfInterestSymbol(poi:PointOfInterest, priority:Int, symbol:Bitmap, tile:Tile) {
val poiPosition = MercatorProjection.getPixelAbsolute(poi.position, tile.zoomLevel, tile.tileSize)
currentLabels.add(SymbolContainer(poiPosition, priority, symbol))
}
override fun renderWay(way:PolylineContainer, stroke:Paint, dy:Float, level:Int) {
drawingLayers!![level].add(ShapePaintContainer(way, null, stroke, dy))
}
override fun renderWaySymbol(way:PolylineContainer, priority:Int, symbol:Bitmap, dy:Float, alignCenter:Boolean, repeat:Boolean, repeatGap:Float, repeatStart:Float, rotate:Boolean) {
WayDecorator.renderSymbol(symbol, priority, dy, alignCenter, repeat, repeatGap, repeatStart, rotate, way.getCoordinatesAbsolute(), currentLabels)
}
override fun renderWayText(way:PolylineContainer, priority:Int, textKey:String, dy:Float, fill:Paint, stroke:Paint?) {
WayDecorator.renderText(textKey, priority, dy, fill, stroke, way.getCoordinatesAbsolute(), currentWayLabels)
}
private fun processReadMapData(ways:Array<List<MutableList<ShapePaintContainer>>>, mapReadResult:MapReadResult?, tile:Tile) {
if (mapReadResult == null) {
return
}
for (pointOfInterest in mapReadResult.pointOfInterests) {
renderPointOfInterest(ways, pointOfInterest, tile)
}
for (way in mapReadResult.ways) {
renderWay(ways, PolylineContainer(way, tile))
}
if (mapReadResult.isWater) {
renderWaterBackground(ways, tile)
}
}
private fun renderPointOfInterest(ways:Array<List<MutableList<ShapePaintContainer>>>, pointOfInterest:PointOfInterest, tile:Tile) {
drawingLayers = ways[getValidLayer(pointOfInterest.layer)]
renderTheme!!.matchNode(this, pointOfInterest, tile)
}
private fun renderWaterBackground(ways:Array<List<MutableList<ShapePaintContainer>>>, tile:Tile) {
drawingLayers = ways[0]
val coordinates = getTilePixelCoordinates(tile.tileSize)
renderTheme!!.matchClosedWay(this, PolylineContainer(coordinates, tile, Arrays.asList(TAG_NATURAL_WATER)))
}
private fun renderWay(ways:Array<List<MutableList<ShapePaintContainer>>>, way:PolylineContainer) {
drawingLayers = ways[getValidLayer(way.getLayer())]
if (way.isClosedWay()) {
renderTheme!!.matchClosedWay(this, way)
}
else {
renderTheme!!.matchLinearWay(this, way)
}
}
} | mit | 23bb606b8f1c18538c6aa38382fba38c | 37.980676 | 217 | 0.725706 | 4.093354 | false | false | false | false |
xdtianyu/CallerInfo | app/src/main/java/org/xdty/callerinfo/view/CallerAdapter.kt | 1 | 4660 | package org.xdty.callerinfo.view
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.View.OnLongClickListener
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.Adapter
import org.xdty.callerinfo.R
import org.xdty.callerinfo.contract.MainContract.Presenter
import org.xdty.callerinfo.model.TextColorPair
import org.xdty.callerinfo.model.db.InCall
import org.xdty.callerinfo.utils.Utils
import org.xdty.callerinfo.view.CallerAdapter.ViewHolder
class CallerAdapter(internal var mPresenter: Presenter) : Adapter<ViewHolder>() {
private var mList: List<InCall> = ArrayList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.card_item, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val inCall = mList[position]
holder.bind(inCall)
}
override fun getItemCount(): Int {
return mList.size
}
override fun onViewRecycled(holder: ViewHolder) {
super.onViewRecycled(holder)
}
fun replaceData(inCalls: List<InCall>) {
mList = inCalls
notifyDataSetChanged()
}
fun getItem(position: Int): InCall {
return mList[position]
}
inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view), OnClickListener, OnLongClickListener {
private val cardView: CardView = view.findViewById(R.id.card_view)
private val text: TextView = view.findViewById(R.id.text)
private val number: TextView = view.findViewById(R.id.number)
private val detail: LinearLayout = view.findViewById(R.id.detail)
private val time: TextView = view.findViewById(R.id.time)
private val ringTime: TextView = view.findViewById(R.id.ring_time)
private val duration: TextView = view.findViewById(R.id.duration)
internal var inCall: InCall? = null
fun setAlpha(alpha: Float) {
cardView.alpha = alpha
}
fun bind(inCall: InCall) {
val caller = mPresenter.getCaller(inCall.number)
if (caller.isEmpty) {
if (caller.isOffline) {
if (caller.hasGeo()) {
text.text = caller.geo
} else {
text.setText(R.string.loading)
}
number.text = inCall.number
cardView.setCardBackgroundColor(
ContextCompat.getColor(cardView.context, R.color.blue_light))
} else {
text.setText(R.string.loading_error)
number.text = inCall.number
cardView.setCardBackgroundColor(
ContextCompat.getColor(cardView.context, R.color.graphite))
}
} else {
val t = TextColorPair.from(caller)
text.text = t.text
cardView.setCardBackgroundColor(t.color)
number.text = if (TextUtils.isEmpty(
caller.contactName)) caller.number else caller.contactName
}
cardView.alpha = 1f
if (inCall.isExpanded) {
detail.visibility = View.VISIBLE
} else {
detail.visibility = View.GONE
}
this.inCall = inCall
time.text = Utils.readableDate(inCall.time)
ringTime.text = Utils.readableTime(inCall.ringTime)
duration.text = Utils.readableTime(inCall.duration)
}
override fun onClick(v: View) {
if (detail.visibility == View.VISIBLE) {
detail.visibility = View.GONE
inCall!!.isExpanded = false
} else {
detail.visibility = View.VISIBLE
inCall!!.isExpanded = true
}
}
override fun onLongClick(view: View): Boolean {
mPresenter.itemOnLongClicked(inCall!!)
return true
}
init {
cardView.setOnClickListener(this)
cardView.setOnLongClickListener(this)
}
}
companion object {
private val TAG = CallerAdapter::class.java.simpleName
}
} | gpl-3.0 | 275c8dd575e086d82a4105a96c2edd26 | 35.131783 | 110 | 0.615451 | 4.779487 | false | false | false | false |
ligee/kotlin-jupyter | src/main/kotlin/org/jetbrains/kotlinx/jupyter/libraries/libraryParsingUtil.kt | 1 | 3488 | package org.jetbrains.kotlinx.jupyter.libraries
import org.jetbrains.kotlinx.jupyter.api.libraries.LibraryReference
import org.jetbrains.kotlinx.jupyter.api.libraries.LibraryResolutionInfo
import org.jetbrains.kotlinx.jupyter.api.libraries.Variable
import java.io.File
import java.net.URL
/**
* Split a command argument into a list of library calls
*/
fun splitLibraryCalls(text: String): List<String> {
return libraryCommaRanges(text)
.mapNotNull { (from, to) ->
if (from >= to) null
else text.substring(from + 1, to).trim().takeIf { it.isNotEmpty() }
}
}
fun libraryCommaRanges(text: String): List<Pair<Int, Int>> {
return libraryCommaIndices(text, withFirst = true, withLast = true).zipWithNext()
}
/**
* Need special processing of ',' to skip call argument delimiters in brackets
* E.g. "use lib1(3), lib2(2, 5)" should split into "lib1(3)" and "lib(2, 5)", not into "lib1(3)", "lib(2", "5)"
*/
fun libraryCommaIndices(text: String, withFirst: Boolean = false, withLast: Boolean = false): List<Int> {
return buildList {
var i = 0
var commaDepth = 0
val delimiters = charArrayOf(',', '(', ')')
if (withFirst) add(-1)
while (true) {
i = text.indexOfAny(delimiters, i)
if (i == -1) {
if (withLast) add(text.length)
break
}
when (text[i]) {
',' -> if (commaDepth == 0) {
add(i)
}
'(' -> commaDepth++
')' -> commaDepth--
}
i++
}
}
}
fun parseReferenceWithArgs(str: String): Pair<LibraryReference, List<Variable>> {
val (fullName, vars) = parseLibraryName(str)
val reference = parseReference(fullName)
return reference to vars
}
private fun parseResolutionInfo(string: String): LibraryResolutionInfo {
// In case of empty string after `@`: %use lib@
if (string.isBlank()) return AbstractLibraryResolutionInfo.Default()
val (type, vars) = parseCall(string, Brackets.SQUARE)
return defaultParsers[type]?.getInfo(vars) ?: AbstractLibraryResolutionInfo.Default(type)
}
private fun parseReference(string: String): LibraryReference {
val sepIndex = string.indexOf('@')
if (sepIndex == -1) return LibraryReference(AbstractLibraryResolutionInfo.Default(), string)
val nameString = string.substring(0, sepIndex)
val infoString = string.substring(sepIndex + 1)
val info = parseResolutionInfo(infoString)
return LibraryReference(info, nameString)
}
private val defaultParsers = listOf(
LibraryResolutionInfoParser.make("ref", listOf(Parameter.Required("ref"))) { args ->
AbstractLibraryResolutionInfo.getInfoByRef(args["ref"] ?: error("Argument 'ref' should be specified"))
},
LibraryResolutionInfoParser.make("file", listOf(Parameter.Required("path"))) { args ->
AbstractLibraryResolutionInfo.ByFile(File(args["path"] ?: error("Argument 'path' should be specified")))
},
LibraryResolutionInfoParser.make("dir", listOf(Parameter.Required("dir"))) { args ->
AbstractLibraryResolutionInfo.ByDir(File(args["dir"] ?: error("Argument 'dir' should be specified")))
},
LibraryResolutionInfoParser.make("url", listOf(Parameter.Required("url"))) { args ->
AbstractLibraryResolutionInfo.ByURL(URL(args["url"] ?: error("Argument 'url' should be specified")))
},
).associateBy { it.name }
| apache-2.0 | d452c8422cafd29b8316948776e430ef | 37.755556 | 112 | 0.65195 | 4.108363 | false | false | false | false |
sybila/ode-generator | src/main/java/com/github/sybila/ode/model/RampApproximation.kt | 1 | 1602 | package com.github.sybila.ode.model
import java.util.*
/**
* Approximation of continuous function using linear ramps.
*/
data class RampApproximation(
override val varIndex: Int,
val thresholds: DoubleArray, //thresholds between ramps - SORTED!
val values: DoubleArray //value of function in corresponding threshold
) : Evaluable {
override fun eval(value: Double): Double {
if (value <= thresholds.first()) return values.first()
if (value >= thresholds.last()) return values.last()
val position = Arrays.binarySearch(thresholds, value)
if (position >= 0) { //evaluated value is one of the thresholds
return values[position]
} else { //position points to -1 * (upper threshold)
val iH = -position-1 //note that this must be a valid index, otherwise some conditions above would fire
val iL = iH-1
return values[iL] + (value - thresholds[iL]) / (thresholds[iH] - thresholds[iL]) * (values[iH] - values[iL])
}
}
override fun toString(): String
= "Approx($varIndex)[${thresholds.joinToString()}]{${values.joinToString()}}"
override fun equals(other: Any?): Boolean {
return other is RampApproximation &&
this.varIndex == other.varIndex &&
Arrays.equals(this.thresholds, other.thresholds) &&
Arrays.equals(this.values, other.values)
}
override fun hashCode(): Int {
return varIndex + 31 * Arrays.hashCode(thresholds) + 47 * Arrays.hashCode(values)
}
} | gpl-3.0 | e2c50af7f093908574eae5ea68261993 | 39.075 | 120 | 0.621723 | 4.226913 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/osm/splitway/OsmQuestSplitWayTable.kt | 1 | 774 | package de.westnordost.streetcomplete.data.osm.splitway
object OsmQuestSplitWayTable {
const val NAME = "osm_split_ways"
object Columns {
const val QUEST_ID = "quest_id"
const val QUEST_TYPE = "quest_type"
const val WAY_ID = "way_id"
const val SPLITS = "splits"
const val SOURCE = "source"
const val QUEST_TYPES_ON_WAY = "quest_types_on_way"
}
const val CREATE = """
CREATE TABLE $NAME (
${Columns.QUEST_ID} int PRIMARY KEY,
${Columns.QUEST_TYPE} varchar(255) NOT NULL,
${Columns.WAY_ID} int NOT NULL,
${Columns.SPLITS} blob NOT NULL,
${Columns.SOURCE} varchar(255) NOT NULL,
${Columns.QUEST_TYPES_ON_WAY} text
);"""
}
| gpl-3.0 | e45cfc243c80090182bc4523615cdc7d | 31.25 | 59 | 0.578811 | 3.812808 | false | false | false | false |
BrandonWilliamsCS/DulyNoted-Android | DulyNoted/app/src/main/java/com/brandonwilliamscs/dulynoted/model/DulyNotedModel.kt | 1 | 4947 | package com.brandonwilliamscs.dulynoted.model
import com.brandonwilliamscs.apputil.MultiplexedEvent
import com.brandonwilliamscs.apputil.StateMachine
import com.brandonwilliamscs.dulynoted.model.music.PitchClass
import com.brandonwilliamscs.dulynoted.view.events.InternalReaction
import com.brandonwilliamscs.dulynoted.view.events.UserIntent
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.Scheduler
import java.util.concurrent.TimeUnit
/**
* The root of all app logic for Duly Noted.
* Houses the state machine and reports "internal" events to it, when appropriate.
* Created by Brandon on 9/28/2017.
*/
class DulyNotedModel(scheduler: Scheduler) {
/**
* Encapsulates the application's initial state.
*/
val initialState = DulyNotedState(PitchClass.getRandomPitchClass(), null)
/**
* Rely on the state machine for the complexity of the event/model interactions.
* Oddly enough, there are no side-effects within the state machine, because it's all RX.
*/
val stateMachine = StateMachine(initialState, this::processEvent, scheduler)
// The following are just pass-through properties.
val viewEventObserver: Observer<UserIntent> get() = stateMachine.viewEventObserver
val stateChangeObservable: Observable<DulyNotedState> get() = stateMachine.stateChangeObservable
/**
* Respond to the user guessing an answer
* @param state the state at the time of the event
* @param answerPitchClass the answer guessed
*/
fun guessAnswer(state: DulyNotedState, answerPitchClass: PitchClass): DulyNotedState {
return if (state.currentGuess?.isCorrect == true)
// Ignore key presses if we already have the correct answer highlighted
state
else {
if (answerPitchClass == state.currentPromptPitchClass) {
// Also, signal that we'd like to move on to the next prompt.
// TODO: take 500 from a preference
delayInternalEvent(InternalReaction.FinishReportingAnswer, 500)
}
state.updateGuess(answerPitchClass)
}
}
/**
* Clear the current slide and create a new one.
* @param state the state at the time of the event
*/
fun finishReportingAnswer(state: DulyNotedState): DulyNotedState
// TODO: allow true
= state.nextSlide(PitchClass.getRandomPitchClass(false, state.currentPromptPitchClass))
/**
* Selects a transformation function based on the incoming event and applies it to the provided state.
* @param startState the state to transform
* @param event the event used to indicate which transformation to apply
*/
fun processEvent(startState: DulyNotedState, event: MultiplexedEvent<UserIntent, InternalReaction>): DulyNotedState {
return if (event.isViewEvent) processUserIntent(startState, event.fromView)
else processInternalReaction(startState, event.fromModel)
}
/**
* Selects a transformation function based on a user intent.
* @param startState the state to transform
* @param userIntent the user intent that indicates which transformation to apply
*/
private fun processUserIntent(startState: DulyNotedState, userIntent: UserIntent): DulyNotedState {
return when (userIntent) {
is UserIntent.GuessAnswer -> guessAnswer(startState, userIntent.pitchClass)
}
}
/**
* Selects a transformation function based on an internal reaction.
* @param startState the state to transform
* @param internalReaction the internal reaction event used to indicate which transformation to apply
*/
private fun processInternalReaction(startState: DulyNotedState, internalReaction: InternalReaction): DulyNotedState {
return when (internalReaction) {
InternalReaction.FinishReportingAnswer -> finishReportingAnswer(startState)
}
}
/**
* Utility for emitting an event after a delay.
*/
private fun delayInternalEvent(event: InternalReaction, delayMS: Long) {
stateMachine.modelEventObserver.onNext(Observable.timer(delayMS, TimeUnit.MILLISECONDS).map { event })
}
}
// Side-effect! Technically, random number generation isn't pure.
/**
* Generate a random pitch class, optionally allowing for sharpened semi-tones.
* @param includeAllSemiTones whether or not to include sharpened classes, or just the base letters.
*/
fun PitchClass.Companion.getRandomPitchClass(
includeAllSemiTones: Boolean = false,
excludeValue: PitchClass? = null
): PitchClass {
val adjustmentRange = if (includeAllSemiTones) 12 else 7
var newValue: PitchClass
do {
val adjustment = (Math.random() * adjustmentRange).toInt()
newValue = PitchClass.C.increasePitch(adjustment, includeAllSemiTones)
} while (newValue == excludeValue)
return newValue
}
| apache-2.0 | d0086844d598966f6e9c5c48f9f57109 | 40.571429 | 121 | 0.717809 | 4.436771 | false | false | false | false |
WangDaYeeeeee/GeometricWeather | app/src/main/java/wangdaye/com/geometricweather/main/MainActivityModels.kt | 1 | 1923 | package wangdaye.com.geometricweather.main
import wangdaye.com.geometricweather.common.basic.models.Location
class Indicator(val total: Int, val index: Int) {
override fun equals(other: Any?): Boolean {
return if (other is Indicator) {
other.index == index && other.total == total
} else {
false
}
}
override fun hashCode(): Int {
var result = total
result = 31 * result + index
return result
}
}
class PermissionsRequest(
val permissionList: List<String>,
val target: Location?,
val triggeredByUser: Boolean
) {
private var consumed = false
fun consume(): Boolean {
if (consumed) {
return false
}
consumed = true
return true
}
}
class SelectableLocationList(
val locationList: List<Location>,
val selectedId: String,
) {
override fun equals(other: Any?): Boolean {
if (other is SelectableLocationList) {
return locationList == other.locationList
&& selectedId == other.selectedId
}
return false
}
override fun hashCode(): Int {
var result = locationList.hashCode()
result = 31 * result + selectedId.hashCode()
return result
}
}
enum class MainMessage {
LOCATION_FAILED,
WEATHER_REQ_FAILED,
}
class DayNightLocation(
val location: Location,
val daylight: Boolean = location.isDaylight
) {
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
if (other is DayNightLocation) {
return location == other.location
&& daylight == other.daylight
}
return false
}
override fun hashCode(): Int {
var result = location.hashCode()
result = 31 * result + daylight.hashCode()
return result
}
} | lgpl-3.0 | 18654299dccbb5c7eaaa64da393dca08 | 21.114943 | 65 | 0.583983 | 4.667476 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupManager.kt | 1 | 18794 | package eu.kanade.tachiyomi.data.backup
import android.content.Context
import android.content.Intent
import android.net.Uri
import com.github.salomonbrys.kotson.*
import com.google.gson.*
import com.hippo.unifile.UniFile
import eu.kanade.tachiyomi.data.backup.BackupCreateService.Companion.BACKUP_CATEGORY
import eu.kanade.tachiyomi.data.backup.BackupCreateService.Companion.BACKUP_CATEGORY_MASK
import eu.kanade.tachiyomi.data.backup.BackupCreateService.Companion.BACKUP_CHAPTER
import eu.kanade.tachiyomi.data.backup.BackupCreateService.Companion.BACKUP_CHAPTER_MASK
import eu.kanade.tachiyomi.data.backup.BackupCreateService.Companion.BACKUP_HISTORY
import eu.kanade.tachiyomi.data.backup.BackupCreateService.Companion.BACKUP_HISTORY_MASK
import eu.kanade.tachiyomi.data.backup.BackupCreateService.Companion.BACKUP_TRACK
import eu.kanade.tachiyomi.data.backup.BackupCreateService.Companion.BACKUP_TRACK_MASK
import eu.kanade.tachiyomi.data.backup.models.Backup
import eu.kanade.tachiyomi.data.backup.models.Backup.CATEGORIES
import eu.kanade.tachiyomi.data.backup.models.Backup.CHAPTERS
import eu.kanade.tachiyomi.data.backup.models.Backup.CURRENT_VERSION
import eu.kanade.tachiyomi.data.backup.models.Backup.HISTORY
import eu.kanade.tachiyomi.data.backup.models.Backup.MANGA
import eu.kanade.tachiyomi.data.backup.models.Backup.TRACK
import eu.kanade.tachiyomi.data.backup.models.DHistory
import eu.kanade.tachiyomi.data.backup.serializer.*
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.*
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.data.preference.getOrDefault
import eu.kanade.tachiyomi.data.track.TrackManager
import eu.kanade.tachiyomi.source.Source
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.source.online.all.EHentai
import eu.kanade.tachiyomi.util.sendLocalBroadcast
import eu.kanade.tachiyomi.util.syncChaptersWithSource
import exh.eh.EHentaiThrottleManager
import rx.Observable
import timber.log.Timber
import uy.kohesive.injekt.injectLazy
class BackupManager(val context: Context, version: Int = CURRENT_VERSION) {
/**
* Database.
*/
internal val databaseHelper: DatabaseHelper by injectLazy()
/**
* Source manager.
*/
internal val sourceManager: SourceManager by injectLazy()
/**
* Tracking manager
*/
internal val trackManager: TrackManager by injectLazy()
/**
* Version of parser
*/
var version: Int = version
private set
/**
* Json Parser
*/
var parser: Gson = initParser()
/**
* Preferences
*/
private val preferences: PreferencesHelper by injectLazy()
/**
* Set version of parser
*
* @param version version of parser
*/
internal fun setVersion(version: Int) {
this.version = version
parser = initParser()
}
private fun initParser(): Gson = when (version) {
1 -> GsonBuilder().create()
2 -> GsonBuilder()
.registerTypeAdapter<MangaImpl>(MangaTypeAdapter.build())
.registerTypeHierarchyAdapter<ChapterImpl>(ChapterTypeAdapter.build())
.registerTypeAdapter<CategoryImpl>(CategoryTypeAdapter.build())
.registerTypeAdapter<DHistory>(HistoryTypeAdapter.build())
.registerTypeHierarchyAdapter<TrackImpl>(TrackTypeAdapter.build())
.create()
else -> throw Exception("Json version unknown")
}
/**
* Create backup Json file from database
*
* @param uri path of Uri
* @param isJob backup called from job
*/
fun createBackup(uri: Uri, flags: Int, isJob: Boolean) {
// Create root object
val root = JsonObject()
// Create manga array
val mangaEntries = JsonArray()
// Create category array
val categoryEntries = JsonArray()
// Add value's to root
root[Backup.VERSION] = Backup.CURRENT_VERSION
root[Backup.MANGAS] = mangaEntries
root[CATEGORIES] = categoryEntries
databaseHelper.inTransaction {
// Get manga from database
val mangas = getFavoriteManga()
// Backup library manga and its dependencies
mangas.forEach { manga ->
mangaEntries.add(backupMangaObject(manga, flags))
}
// Backup categories
if ((flags and BACKUP_CATEGORY_MASK) == BACKUP_CATEGORY) {
backupCategories(categoryEntries)
}
}
try {
// When BackupCreatorJob
if (isJob) {
// Get dir of file and create
var dir = UniFile.fromUri(context, uri)
dir = dir.createDirectory("automatic")
// Delete older backups
val numberOfBackups = numberOfBackups()
val backupRegex = Regex("""tachiyomi_\d+-\d+-\d+_\d+-\d+.json""")
dir.listFiles { _, filename -> backupRegex.matches(filename) }
.orEmpty()
.sortedByDescending { it.name }
.drop(numberOfBackups - 1)
.forEach { it.delete() }
// Create new file to place backup
val newFile = dir.createFile(Backup.getDefaultFilename())
?: throw Exception("Couldn't create backup file")
newFile.openOutputStream().bufferedWriter().use {
parser.toJson(root, it)
}
} else {
val file = UniFile.fromUri(context, uri)
?: throw Exception("Couldn't create backup file")
file.openOutputStream().bufferedWriter().use {
parser.toJson(root, it)
}
// Show completed dialog
val intent = Intent(BackupConst.INTENT_FILTER).apply {
putExtra(BackupConst.ACTION, BackupConst.ACTION_BACKUP_COMPLETED_DIALOG)
putExtra(BackupConst.EXTRA_URI, file.uri.toString())
}
context.sendLocalBroadcast(intent)
}
} catch (e: Exception) {
Timber.e(e)
if (!isJob) {
// Show error dialog
val intent = Intent(BackupConst.INTENT_FILTER).apply {
putExtra(BackupConst.ACTION, BackupConst.ACTION_ERROR_BACKUP_DIALOG)
putExtra(BackupConst.EXTRA_ERROR_MESSAGE, e.message)
}
context.sendLocalBroadcast(intent)
}
}
}
/**
* Backup the categories of library
*
* @param root root of categories json
*/
internal fun backupCategories(root: JsonArray) {
val categories = databaseHelper.getCategories().executeAsBlocking()
categories.forEach { root.add(parser.toJsonTree(it)) }
}
/**
* Convert a manga to Json
*
* @param manga manga that gets converted
* @return [JsonElement] containing manga information
*/
internal fun backupMangaObject(manga: Manga, options: Int): JsonElement {
// Entry for this manga
val entry = JsonObject()
// Backup manga fields
entry[MANGA] = parser.toJsonTree(manga)
// Check if user wants chapter information in backup
if (options and BACKUP_CHAPTER_MASK == BACKUP_CHAPTER) {
// Backup all the chapters
val chapters = databaseHelper.getChapters(manga).executeAsBlocking()
if (!chapters.isEmpty()) {
val chaptersJson = parser.toJsonTree(chapters)
if (chaptersJson.asJsonArray.size() > 0) {
entry[CHAPTERS] = chaptersJson
}
}
}
// Check if user wants category information in backup
if (options and BACKUP_CATEGORY_MASK == BACKUP_CATEGORY) {
// Backup categories for this manga
val categoriesForManga = databaseHelper.getCategoriesForManga(manga).executeAsBlocking()
if (!categoriesForManga.isEmpty()) {
val categoriesNames = categoriesForManga.map { it.name }
entry[CATEGORIES] = parser.toJsonTree(categoriesNames)
}
}
// Check if user wants track information in backup
if (options and BACKUP_TRACK_MASK == BACKUP_TRACK) {
val tracks = databaseHelper.getTracks(manga).executeAsBlocking()
if (!tracks.isEmpty()) {
entry[TRACK] = parser.toJsonTree(tracks)
}
}
// Check if user wants history information in backup
if (options and BACKUP_HISTORY_MASK == BACKUP_HISTORY) {
val historyForManga = databaseHelper.getHistoryByMangaId(manga.id!!).executeAsBlocking()
if (!historyForManga.isEmpty()) {
val historyData = historyForManga.mapNotNull { history ->
val url = databaseHelper.getChapter(history.chapter_id).executeAsBlocking()?.url
url?.let { DHistory(url, history.last_read) }
}
val historyJson = parser.toJsonTree(historyData)
if (historyJson.asJsonArray.size() > 0) {
entry[HISTORY] = historyJson
}
}
}
return entry
}
fun restoreMangaNoFetch(manga: Manga, dbManga: Manga) {
manga.id = dbManga.id
manga.copyFrom(dbManga)
manga.favorite = true
insertManga(manga)
}
/**
* [Observable] that fetches manga information
*
* @param source source of manga
* @param manga manga that needs updating
* @return [Observable] that contains manga
*/
fun restoreMangaFetchObservable(source: Source, manga: Manga): Observable<Manga> {
return source.fetchMangaDetails(manga)
.map { networkManga ->
manga.copyFrom(networkManga)
manga.favorite = true
manga.initialized = true
manga.id = insertManga(manga)
manga
}
}
/**
* [Observable] that fetches chapter information
*
* @param source source of manga
* @param manga manga that needs updating
* @return [Observable] that contains manga
*/
fun restoreChapterFetchObservable(source: Source, manga: Manga, chapters: List<Chapter>, throttleManager: EHentaiThrottleManager): Observable<Pair<List<Chapter>, List<Chapter>>> {
return (if(source is EHentai) {
source.fetchChapterList(manga, throttleManager::throttle)
} else {
source.fetchChapterList(manga)
}).map { syncChaptersWithSource(databaseHelper, it, manga, source) }
.doOnNext {
if (it.first.isNotEmpty()) {
chapters.forEach { it.manga_id = manga.id }
insertChapters(chapters)
}
}
}
/**
* Restore the categories from Json
*
* @param jsonCategories array containing categories
*/
internal fun restoreCategories(jsonCategories: JsonArray) {
// Get categories from file and from db
val dbCategories = databaseHelper.getCategories().executeAsBlocking()
val backupCategories = parser.fromJson<List<CategoryImpl>>(jsonCategories)
// Iterate over them
backupCategories.forEach { category ->
// Used to know if the category is already in the db
var found = false
for (dbCategory in dbCategories) {
// If the category is already in the db, assign the id to the file's category
// and do nothing
if (category.nameLower == dbCategory.nameLower) {
category.id = dbCategory.id
found = true
break
}
}
// If the category isn't in the db, remove the id and insert a new category
// Store the inserted id in the category
if (!found) {
// Let the db assign the id
category.id = null
val result = databaseHelper.insertCategory(category).executeAsBlocking()
category.id = result.insertedId()?.toInt()
}
}
}
/**
* Restores the categories a manga is in.
*
* @param manga the manga whose categories have to be restored.
* @param categories the categories to restore.
*/
internal fun restoreCategoriesForManga(manga: Manga, categories: List<String>) {
val dbCategories = databaseHelper.getCategories().executeAsBlocking()
val mangaCategoriesToUpdate = ArrayList<MangaCategory>()
for (backupCategoryStr in categories) {
for (dbCategory in dbCategories) {
if (backupCategoryStr.toLowerCase() == dbCategory.nameLower) {
mangaCategoriesToUpdate.add(MangaCategory.create(manga, dbCategory))
break
}
}
}
// Update database
if (!mangaCategoriesToUpdate.isEmpty()) {
val mangaAsList = ArrayList<Manga>()
mangaAsList.add(manga)
databaseHelper.deleteOldMangasCategories(mangaAsList).executeAsBlocking()
databaseHelper.insertMangasCategories(mangaCategoriesToUpdate).executeAsBlocking()
}
}
/**
* Restore history from Json
*
* @param history list containing history to be restored
*/
internal fun restoreHistoryForManga(history: List<DHistory>) {
// List containing history to be updated
val historyToBeUpdated = ArrayList<History>()
for ((url, lastRead) in history) {
val dbHistory = databaseHelper.getHistoryByChapterUrl(url).executeAsBlocking()
// Check if history already in database and update
if (dbHistory != null) {
dbHistory.apply {
last_read = Math.max(lastRead, dbHistory.last_read)
}
historyToBeUpdated.add(dbHistory)
} else {
// If not in database create
databaseHelper.getChapter(url).executeAsBlocking()?.let {
val historyToAdd = History.create(it).apply {
last_read = lastRead
}
historyToBeUpdated.add(historyToAdd)
}
}
}
databaseHelper.updateHistoryLastRead(historyToBeUpdated).executeAsBlocking()
}
/**
* Restores the sync of a manga.
*
* @param manga the manga whose sync have to be restored.
* @param tracks the track list to restore.
*/
internal fun restoreTrackForManga(manga: Manga, tracks: List<Track>) {
// Fix foreign keys with the current manga id
tracks.map { it.manga_id = manga.id!! }
// Get tracks from database
val dbTracks = databaseHelper.getTracks(manga).executeAsBlocking()
val trackToUpdate = ArrayList<Track>()
for (track in tracks) {
val service = trackManager.getService(track.sync_id)
if (service != null && service.isLogged) {
var isInDatabase = false
for (dbTrack in dbTracks) {
if (track.sync_id == dbTrack.sync_id) {
// The sync is already in the db, only update its fields
if (track.media_id != dbTrack.media_id) {
dbTrack.media_id = track.media_id
}
if (track.library_id != dbTrack.library_id) {
dbTrack.library_id = track.library_id
}
dbTrack.last_chapter_read = Math.max(dbTrack.last_chapter_read, track.last_chapter_read)
isInDatabase = true
trackToUpdate.add(dbTrack)
break
}
}
if (!isInDatabase) {
// Insert new sync. Let the db assign the id
track.id = null
trackToUpdate.add(track)
}
}
}
// Update database
if (!trackToUpdate.isEmpty()) {
databaseHelper.insertTracks(trackToUpdate).executeAsBlocking()
}
}
/**
* Restore the chapters for manga if chapters already in database
*
* @param manga manga of chapters
* @param chapters list containing chapters that get restored
* @return boolean answering if chapter fetch is not needed
*/
internal fun restoreChaptersForManga(manga: Manga, chapters: List<Chapter>): Boolean {
val dbChapters = databaseHelper.getChapters(manga).executeAsBlocking()
// Return if fetch is needed
if (dbChapters.isEmpty() || dbChapters.size < chapters.size)
return false
for (chapter in chapters) {
val pos = dbChapters.indexOf(chapter)
if (pos != -1) {
val dbChapter = dbChapters[pos]
chapter.id = dbChapter.id
chapter.copyFrom(dbChapter)
break
}
}
// Filter the chapters that couldn't be found.
chapters.filter { it.id != null }
chapters.map { it.manga_id = manga.id }
insertChapters(chapters)
return true
}
/**
* Returns manga
*
* @return [Manga], null if not found
*/
internal fun getMangaFromDatabase(manga: Manga): Manga? =
databaseHelper.getManga(manga.url, manga.source).executeAsBlocking()
/**
* Returns list containing manga from library
*
* @return [Manga] from library
*/
internal fun getFavoriteManga(): List<Manga> =
databaseHelper.getFavoriteMangas().executeAsBlocking()
/**
* Inserts manga and returns id
*
* @return id of [Manga], null if not found
*/
internal fun insertManga(manga: Manga): Long? =
databaseHelper.insertManga(manga).executeAsBlocking().insertedId()
/**
* Inserts list of chapters
*/
private fun insertChapters(chapters: List<Chapter>) {
databaseHelper.updateChaptersBackup(chapters).executeAsBlocking()
}
/**
* Return number of backups.
*
* @return number of backups selected by user
*/
fun numberOfBackups(): Int = preferences.numberOfBackups().getOrDefault()
}
| apache-2.0 | 5dec068a5c1f7032f14e822ed4c67cd4 | 36.363817 | 183 | 0.596201 | 5.093225 | false | false | false | false |
apollostack/apollo-android | apollo-api/src/commonMain/kotlin/com/apollographql/apollo3/api/internal/json/JsonScope.kt | 1 | 2842 | /*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.apollographql.apollo3.api.internal.json
/** Lexical scoping elements within a JSON reader or writer. */
object JsonScope {
/** An array with no elements requires no separators or newlines before it is closed. */
const val EMPTY_ARRAY = 1
/** A array with at least one value requires a comma and newline before the next element. */
const val NONEMPTY_ARRAY = 2
/** An object with no name/value pairs requires no separators or newlines before it is closed. */
const val EMPTY_OBJECT = 3
/** An object whose most recent element is a key. The next element must be a value. */
const val DANGLING_NAME = 4
/** An object with at least one name/value pair requires a separator before the next element. */
const val NONEMPTY_OBJECT = 5
/** No object or array has been started. */
const val EMPTY_DOCUMENT = 6
/** A document with at an array or object. */
const val NONEMPTY_DOCUMENT = 7
/** A document that's been closed and cannot be accessed. */
const val CLOSED = 8
/**
* Renders the path in a JSON document to a string.
*
* The [pathNames] and [pathIndices] parameters corresponds directly to stack:
* - [pathIndices] where the stack contains an object (EMPTY_OBJECT, DANGLING_NAME or NONEMPTY_OBJECT),
* - [pathNames] contains the name at this scope.
*
* Where it contains an array (EMPTY_ARRAY, NONEMPTY_ARRAY) [pathIndices] contains the current index
* in that array. Otherwise the value is undefined, and we take advantage of that by incrementing
* pathIndices when doing so isn't useful.
*/
fun getPath(stackSize: Int, stack: IntArray, pathNames: Array<String?>, pathIndices: IntArray): String {
val result = StringBuilder()
var isRoot = true
for (i in 0 until stackSize) {
when (stack[i]) {
EMPTY_ARRAY, NONEMPTY_ARRAY -> result.append('.').append(pathIndices[i])
EMPTY_OBJECT, DANGLING_NAME, NONEMPTY_OBJECT -> {
if (!isRoot) {
result.append('.')
}
if (pathNames[i] != null) {
result.append(pathNames[i])
isRoot = false
}
}
NONEMPTY_DOCUMENT, EMPTY_DOCUMENT, CLOSED -> Unit
}
}
return result.toString()
}
}
| mit | 74b8c9b9c6fdaee23205de80f632cd9c | 40.794118 | 106 | 0.677692 | 4.089209 | false | false | false | false |
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective.kt | 1 | 6374 | package info.nightscout.androidaps.plugins.constraints.objectives.objectives
import android.content.Context
import android.graphics.Color
import android.text.util.Linkify
import android.widget.CheckBox
import android.widget.TextView
import androidx.annotation.StringRes
import androidx.fragment.app.FragmentActivity
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.shared.sharedPreferences.SP
import java.util.*
import javax.inject.Inject
import kotlin.math.floor
abstract class Objective(injector: HasAndroidInjector, spName: String, @StringRes objective: Int, @StringRes gate: Int) {
@Inject lateinit var sp: SP
@Inject lateinit var rh: ResourceHelper
@Inject lateinit var dateUtil: DateUtil
private val spName: String
@StringRes val objective: Int
@StringRes val gate: Int
var startedOn: Long = 0
set(value) {
field = value
sp.putLong("Objectives_" + spName + "_started", startedOn)
}
var accomplishedOn: Long = 0
set(value) {
field = value
sp.putLong("Objectives_" + spName + "_accomplished", value)
}
var tasks: MutableList<Task> = ArrayList()
var hasSpecialInput = false
val isCompleted: Boolean
get() {
for (task in tasks) {
if (!task.shouldBeIgnored() && !task.isCompleted()) return false
}
return true
}
init {
injector.androidInjector().inject(this)
this.spName = spName
this.objective = objective
this.gate = gate
startedOn = sp.getLong("Objectives_" + spName + "_started", 0L)
accomplishedOn = sp.getLong("Objectives_" + spName + "_accomplished", 0L)
if (accomplishedOn - dateUtil.now() > T.hours(3).msecs() || startedOn - dateUtil.now() > T.hours(3).msecs()) { // more than 3 hours in the future
startedOn = 0
accomplishedOn = 0
}
}
fun isCompleted(trueTime: Long): Boolean {
for (task in tasks) {
if (!task.shouldBeIgnored() && !task.isCompleted(trueTime)) return false
}
return true
}
val isAccomplished: Boolean
get() = accomplishedOn != 0L && accomplishedOn < dateUtil.now()
val isStarted: Boolean
get() = startedOn != 0L
open fun specialActionEnabled(): Boolean {
return true
}
open fun specialAction(activity: FragmentActivity, input: String) {}
abstract inner class Task(var objective: Objective, @StringRes val task: Int) {
var hints = ArrayList<Hint>()
abstract fun isCompleted(): Boolean
open fun isCompleted(trueTime: Long): Boolean = isCompleted()
open val progress: String
get() = rh.gs(if (isCompleted()) R.string.completed_well_done else R.string.not_completed_yet)
fun hint(hint: Hint): Task {
hints.add(hint)
return this
}
open fun shouldBeIgnored(): Boolean = false
}
inner class MinimumDurationTask internal constructor(objective: Objective, private val minimumDuration: Long) : Task(objective, R.string.time_elapsed) {
override fun isCompleted(): Boolean =
objective.isStarted && System.currentTimeMillis() - objective.startedOn >= minimumDuration
override fun isCompleted(trueTime: Long): Boolean {
return objective.isStarted && trueTime - objective.startedOn >= minimumDuration
}
override val progress: String
get() = (getDurationText(System.currentTimeMillis() - objective.startedOn)
+ " / " + getDurationText(minimumDuration))
private fun getDurationText(duration: Long): String {
val days = floor(duration.toDouble() / T.days(1).msecs()).toInt()
val hours = floor(duration.toDouble() / T.hours(1).msecs()).toInt()
val minutes = floor(duration.toDouble() / T.mins(1).msecs()).toInt()
return when {
days > 0 -> rh.gq(R.plurals.days, days, days)
hours > 0 -> rh.gq(R.plurals.hours, hours, hours)
else -> rh.gq(R.plurals.minutes, minutes, minutes)
}
}
}
inner class ExamTask internal constructor(objective: Objective, @StringRes task: Int, @StringRes val question: Int, private val spIdentifier: String) : Task(objective, task) {
var options = ArrayList<Option>()
var answered: Boolean = false
set(value) {
field = value
sp.putBoolean("ExamTask_$spIdentifier", value)
}
var disabledTo: Long = 0
set(value) {
field = value
sp.putLong("DisabledTo_$spIdentifier", value)
}
init {
answered = sp.getBoolean("ExamTask_$spIdentifier", false)
disabledTo = sp.getLong("DisabledTo_$spIdentifier", 0L)
}
override fun isCompleted(): Boolean = answered
fun isEnabledAnswer(): Boolean = disabledTo < dateUtil.now()
fun option(option: Option): ExamTask {
options.add(option)
return this
}
}
inner class Option internal constructor(@StringRes var option: Int, var isCorrect: Boolean) {
var cb: CheckBox? = null // TODO: change it, this will block releasing memory
fun generate(context: Context): CheckBox {
cb = CheckBox(context)
cb?.setText(option)
return cb!!
}
fun evaluate(): Boolean {
val selection = cb!!.isChecked
return if (selection && isCorrect) true else !selection && !isCorrect
}
}
inner class Hint internal constructor(@StringRes var hint: Int) {
fun generate(context: Context): TextView {
val textView = TextView(context)
textView.setText(hint)
textView.autoLinkMask = Linkify.WEB_URLS
textView.linksClickable = true
textView.setLinkTextColor(rh.gac(context, R.attr.colorSecondary))
Linkify.addLinks(textView, Linkify.WEB_URLS)
return textView
}
}
} | agpl-3.0 | c13d56113dba021a6e5b8f866b0bbdae | 33.646739 | 179 | 0.620803 | 4.562634 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/base/fe10/highlighting/src/org/jetbrains/kotlin/idea/highlighter/CalculatingIntentionAction.kt | 3 | 1297 | // 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.highlighter
import com.intellij.codeInsight.intention.AbstractEmptyIntentionAction
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.icons.AllIcons
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Iconable
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.idea.base.fe10.highlighting.KotlinBaseFe10HighlightingBundle
import javax.swing.Icon
class CalculatingIntentionAction : AbstractEmptyIntentionAction(), LowPriorityAction, Iconable {
override fun getText(): String = KotlinBaseFe10HighlightingBundle.message("intention.calculating.text")
override fun getFamilyName(): String = KotlinBaseFe10HighlightingBundle.message("intention.calculating.text")
override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean = true
override fun equals(other: Any?): Boolean = this === other || other is CalculatingIntentionAction
override fun hashCode(): Int = 42
override fun getIcon(@Iconable.IconFlags flags: Int): Icon = AllIcons.Actions.Preview
}
| apache-2.0 | c525f8de491c960cc3b089501a32ec9f | 47.037037 | 158 | 0.809561 | 4.583039 | false | false | false | false |
k9mail/k-9 | app/k9mail/src/main/java/com/fsck/k9/notification/K9NotificationResourceProvider.kt | 1 | 5323 | package com.fsck.k9.notification
import android.content.Context
import com.fsck.k9.R
class K9NotificationResourceProvider(private val context: Context) : NotificationResourceProvider {
override val iconWarning: Int = R.drawable.notification_icon_warning
override val iconMarkAsRead: Int = R.drawable.notification_action_mark_as_read
override val iconDelete: Int = R.drawable.notification_action_delete
override val iconReply: Int = R.drawable.notification_action_reply
override val iconNewMail: Int = R.drawable.notification_icon_new_mail
override val iconSendingMail: Int = R.drawable.notification_icon_check_mail
override val iconCheckingMail: Int = R.drawable.notification_icon_check_mail
override val wearIconMarkAsRead: Int = R.drawable.notification_action_mark_as_read
override val wearIconDelete: Int = R.drawable.notification_action_delete
override val wearIconArchive: Int = R.drawable.notification_action_archive
override val wearIconReplyAll: Int = R.drawable.notification_action_reply
override val wearIconMarkAsSpam: Int = R.drawable.notification_action_mark_as_spam
override val pushChannelName: String
get() = context.getString(R.string.notification_channel_push_title)
override val pushChannelDescription: String
get() = context.getString(R.string.notification_channel_push_description)
override val messagesChannelName: String
get() = context.getString(R.string.notification_channel_messages_title)
override val messagesChannelDescription: String
get() = context.getString(R.string.notification_channel_messages_description)
override val miscellaneousChannelName: String
get() = context.getString(R.string.notification_channel_miscellaneous_title)
override val miscellaneousChannelDescription: String
get() = context.getString(R.string.notification_channel_miscellaneous_description)
override fun authenticationErrorTitle(): String =
context.getString(R.string.notification_authentication_error_title)
override fun authenticationErrorBody(accountName: String): String =
context.getString(R.string.notification_authentication_error_text, accountName)
override fun certificateErrorTitle(): String = context.getString(R.string.notification_certificate_error_public)
override fun certificateErrorTitle(accountName: String): String =
context.getString(R.string.notification_certificate_error_title, accountName)
override fun certificateErrorBody(): String = context.getString(R.string.notification_certificate_error_text)
override fun newMailTitle(): String = context.getString(R.string.notification_new_title)
override fun newMailUnreadMessageCount(unreadMessageCount: Int, accountName: String): String =
context.getString(R.string.notification_new_one_account_fmt, unreadMessageCount, accountName)
override fun newMessagesTitle(newMessagesCount: Int): String =
context.resources.getQuantityString(
R.plurals.notification_new_messages_title,
newMessagesCount, newMessagesCount
)
override fun additionalMessages(overflowMessagesCount: Int, accountName: String): String =
context.getString(R.string.notification_additional_messages, overflowMessagesCount, accountName)
override fun previewEncrypted(): String = context.getString(R.string.preview_encrypted)
override fun noSubject(): String = context.getString(R.string.general_no_subject)
override fun recipientDisplayName(recipientDisplayName: String): String =
context.getString(R.string.message_to_fmt, recipientDisplayName)
override fun noSender(): String = context.getString(R.string.general_no_sender)
override fun sendFailedTitle(): String = context.getString(R.string.send_failure_subject)
override fun sendingMailTitle(): String = context.getString(R.string.notification_bg_send_title)
override fun sendingMailBody(accountName: String): String =
context.getString(R.string.notification_bg_send_ticker, accountName)
override fun checkingMailTicker(accountName: String, folderName: String): String =
context.getString(R.string.notification_bg_sync_ticker, accountName, folderName)
override fun checkingMailTitle(): String =
context.getString(R.string.notification_bg_sync_title)
override fun checkingMailSeparator(): String =
context.getString(R.string.notification_bg_title_separator)
override fun actionMarkAsRead(): String = context.getString(R.string.notification_action_mark_as_read)
override fun actionMarkAllAsRead(): String = context.getString(R.string.notification_action_mark_all_as_read)
override fun actionDelete(): String = context.getString(R.string.notification_action_delete)
override fun actionDeleteAll(): String = context.getString(R.string.notification_action_delete_all)
override fun actionReply(): String = context.getString(R.string.notification_action_reply)
override fun actionArchive(): String = context.getString(R.string.notification_action_archive)
override fun actionArchiveAll(): String = context.getString(R.string.notification_action_archive_all)
override fun actionMarkAsSpam(): String = context.getString(R.string.notification_action_spam)
}
| apache-2.0 | 258afa01ec7f5e0ed216e685ad31366e | 52.23 | 116 | 0.773248 | 4.530213 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/KtIconProvider.kt | 2 | 4963 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.Iconable
import com.intellij.psi.PsiClass
import com.intellij.ui.RowIcon
import com.intellij.util.PlatformIcons
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.symbols.*
import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolKind
import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithModality
import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithVisibility
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.descriptors.Visibilities
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtDeclaration
import javax.swing.Icon
object KtIconProvider {
private val LOG = Logger.getInstance(KtIconProvider::class.java)
// KtAnalysisSession is unused, but we want to keep it here to force all access to this method has a KtAnalysisSession
@Suppress("UnusedReceiverParameter")
fun KtAnalysisSession.getIcon(ktSymbol: KtSymbol): Icon? {
// logic copied from org.jetbrains.kotlin.idea.KotlinDescriptorIconProvider
val declaration = ktSymbol.psi
return if (declaration?.isValid == true) {
val isClass = declaration is PsiClass || declaration is KtClass
val flags = if (isClass) 0 else Iconable.ICON_FLAG_VISIBILITY
if (declaration is KtDeclaration) {
// kotlin declaration
// visibility and abstraction better detect by a descriptor
getIcon(ktSymbol, flags) ?: declaration.getIcon(flags)
} else {
// Use Java icons if it's not Kotlin declaration
declaration.getIcon(flags)
}
} else {
getIcon(ktSymbol, 0)
}
}
private fun getIcon(symbol: KtSymbol, flags: Int): Icon? {
var result: Icon = getBaseIcon(symbol) ?: return null
if (flags and Iconable.ICON_FLAG_VISIBILITY > 0) {
val rowIcon = RowIcon(2)
rowIcon.setIcon(result, 0)
rowIcon.setIcon(getVisibilityIcon(symbol), 1)
result = rowIcon
}
return result
}
private fun getBaseIcon(symbol: KtSymbol): Icon? {
val isAbstract = (symbol as? KtSymbolWithModality)?.modality == Modality.ABSTRACT
return when (symbol) {
is KtPackageSymbol -> PlatformIcons.PACKAGE_ICON
is KtFunctionLikeSymbol -> {
val isExtension = symbol.isExtension
val isMember = symbol.symbolKind == KtSymbolKind.CLASS_MEMBER
when {
isExtension && isAbstract -> KotlinIcons.ABSTRACT_EXTENSION_FUNCTION
isExtension && !isAbstract -> KotlinIcons.EXTENSION_FUNCTION
isMember && isAbstract -> PlatformIcons.ABSTRACT_METHOD_ICON
isMember && !isAbstract -> PlatformIcons.METHOD_ICON
else -> KotlinIcons.FUNCTION
}
}
is KtClassOrObjectSymbol -> {
when (symbol.classKind) {
KtClassKind.CLASS -> when {
isAbstract -> KotlinIcons.ABSTRACT_CLASS
else -> KotlinIcons.CLASS
}
KtClassKind.ENUM_CLASS, KtClassKind.ENUM_ENTRY -> KotlinIcons.ENUM
KtClassKind.ANNOTATION_CLASS -> KotlinIcons.ANNOTATION
KtClassKind.INTERFACE -> KotlinIcons.INTERFACE
KtClassKind.ANONYMOUS_OBJECT, KtClassKind.OBJECT, KtClassKind.COMPANION_OBJECT -> KotlinIcons.OBJECT
}
}
is KtValueParameterSymbol -> KotlinIcons.PARAMETER
is KtLocalVariableSymbol -> when {
symbol.isVal -> KotlinIcons.VAL
else -> KotlinIcons.VAR
}
is KtPropertySymbol -> when {
symbol.isVal -> KotlinIcons.FIELD_VAL
else -> KotlinIcons.FIELD_VAR
}
is KtTypeParameterSymbol -> PlatformIcons.CLASS_ICON
is KtTypeAliasSymbol -> KotlinIcons.TYPE_ALIAS
else -> {
LOG.warn("No icon for symbol: $symbol")
null
}
}
}
private fun getVisibilityIcon(symbol: KtSymbol): Icon? {
return when ((symbol as? KtSymbolWithVisibility)?.visibility?.normalize()) {
Visibilities.Public -> PlatformIcons.PUBLIC_ICON
Visibilities.Protected -> PlatformIcons.PROTECTED_ICON
Visibilities.Private, Visibilities.PrivateToThis -> PlatformIcons.PRIVATE_ICON
Visibilities.Internal -> PlatformIcons.PACKAGE_LOCAL_ICON
else -> null
}
}
}
| apache-2.0 | cc04aebcc6c75f40f565d53a66c6b878 | 43.3125 | 122 | 0.630667 | 5.336559 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/jetpack/backup/download/BackupDownloadStates.kt | 1 | 3986 | package org.wordpress.android.ui.jetpack.backup.download
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import org.wordpress.android.R
import org.wordpress.android.fluxc.model.activity.ActivityLogModel
import org.wordpress.android.ui.jetpack.backup.download.StateType.COMPLETE
import org.wordpress.android.ui.jetpack.backup.download.StateType.DETAILS
import org.wordpress.android.ui.jetpack.backup.download.StateType.ERROR
import org.wordpress.android.ui.jetpack.backup.download.StateType.PROGRESS
import org.wordpress.android.ui.jetpack.backup.download.ToolbarState.CompleteToolbarState
import org.wordpress.android.ui.jetpack.backup.download.ToolbarState.DetailsToolbarState
import org.wordpress.android.ui.jetpack.backup.download.ToolbarState.ErrorToolbarState
import org.wordpress.android.ui.jetpack.backup.download.ToolbarState.ProgressToolbarState
import org.wordpress.android.ui.jetpack.common.JetpackListItemState
import java.util.Date
abstract class BackupDownloadUiState(open val type: StateType) {
abstract val items: List<JetpackListItemState>
abstract val toolbarState: ToolbarState
data class ErrorState(
val errorType: BackupDownloadErrorTypes,
override val items: List<JetpackListItemState>
) : BackupDownloadUiState(ERROR) {
override val toolbarState: ToolbarState = ErrorToolbarState
}
sealed class ContentState(override val type: StateType) : BackupDownloadUiState(type) {
data class DetailsState(
val activityLogModel: ActivityLogModel,
override val items: List<JetpackListItemState>,
override val type: StateType
) : ContentState(DETAILS) {
override val toolbarState: ToolbarState = DetailsToolbarState
}
data class ProgressState(
override val items: List<JetpackListItemState>,
override val type: StateType
) : ContentState(PROGRESS) {
override val toolbarState: ToolbarState = ProgressToolbarState
}
data class CompleteState(
override val items: List<JetpackListItemState>,
override val type: StateType
) : ContentState(COMPLETE) {
override val toolbarState: ToolbarState = CompleteToolbarState
}
}
}
enum class StateType(val id: Int) {
DETAILS(0),
PROGRESS(1),
COMPLETE(2),
ERROR(3)
}
sealed class ToolbarState {
abstract val title: Int
@DrawableRes val icon: Int = R.drawable.ic_close_24px
object DetailsToolbarState : ToolbarState() {
@StringRes override val title: Int = R.string.backup_download_details_page_title
}
object ProgressToolbarState : ToolbarState() {
@StringRes override val title: Int = R.string.backup_download_progress_page_title
}
object CompleteToolbarState : ToolbarState() {
@StringRes override val title: Int = R.string.backup_download_complete_page_title
}
object ErrorToolbarState : ToolbarState() {
@StringRes override val title: Int = R.string.backup_download_complete_failed_title
}
}
sealed class BackupDownloadRequestState {
data class Success(
val requestRewindId: String,
val rewindId: String,
val downloadId: Long?
) : BackupDownloadRequestState()
data class Progress(
val rewindId: String,
val progress: Int?,
val published: Date? = null
) : BackupDownloadRequestState()
data class Complete(
val rewindId: String,
val downloadId: Long,
val url: String?,
val published: Date? = null,
val validUntil: Date? = null,
val isValid: Boolean = false
) : BackupDownloadRequestState()
object Empty : BackupDownloadRequestState()
sealed class Failure : BackupDownloadRequestState() {
object NetworkUnavailable : Failure()
object RemoteRequestFailure : Failure()
object OtherRequestRunning : Failure()
}
}
| gpl-2.0 | b2efd766d4827d24d55ff80e68479971 | 35.236364 | 91 | 0.716257 | 4.92707 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/KotlinIdeFileIconProviderService.kt | 1 | 997 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea
import com.intellij.psi.PsiModifierListOwner
import com.intellij.psi.impl.ElementPresentationUtil
import com.intellij.ui.IconManager
import com.intellij.util.PlatformIcons
import javax.swing.Icon
class KotlinIdeFileIconProviderService : KotlinIconProviderService() {
override fun getFileIcon(): Icon = KotlinIcons.FILE
override fun getBuiltInFileIcon(): Icon = KotlinIcons.FILE
override fun getLightVariableIcon(element: PsiModifierListOwner, flags: Int): Icon {
val iconManager = IconManager.getInstance()
val elementFlags = ElementPresentationUtil.getFlags(element, false)
val baseIcon = iconManager.createLayeredIcon(element, PlatformIcons.VARIABLE_ICON, elementFlags)
return ElementPresentationUtil.addVisibilityIcon(element, flags, baseIcon)
}
} | apache-2.0 | 76bcca86e50564b082686e276b5a8e59 | 42.391304 | 158 | 0.789368 | 4.658879 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/blockingCallsDetection/FlowOnIoContextFix.kt | 1 | 3371 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections.blockingCallsDetection
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
import com.intellij.psi.util.parentOfType
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.findFlowOnCall
import org.jetbrains.kotlin.idea.util.ImportInsertHelperImpl
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.resolve.calls.util.getFirstArgumentExpression
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
internal class FlowOnIoContextFix : LocalQuickFix {
override fun getFamilyName(): String {
return KotlinBundle.message("intention.flow.on.dispatchers.io")
}
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val callExpression = descriptor.psiElement?.parentOfType<KtCallExpression>() ?: return
val flowOnCallOrNull = callExpression.findFlowOnCall()
val ktPsiFactory = KtPsiFactory(project, true)
if (flowOnCallOrNull == null) {
val callWithFlowReceiver = callExpression.parentOfType<KtCallExpression>() ?: return
val resolvedCall = callWithFlowReceiver.resolveToCall(BodyResolveMode.PARTIAL) ?: return
if (!CoroutineBlockingCallInspectionUtils.isInsideFlowChain(resolvedCall)) return
val dotQualifiedParent = callWithFlowReceiver.parentOfType<KtDotQualifiedExpression>()
val refactoredElement =
if (dotQualifiedParent == null) {
val flowOnExpression =
ktPsiFactory.createExpression("${callWithFlowReceiver.text}\n.flowOn(kotlinx.coroutines.Dispatchers.IO)")
callWithFlowReceiver.replaced(flowOnExpression)
} else {
val flowOnExpression =
ktPsiFactory.createExpression("${dotQualifiedParent.text}\n.flowOn(kotlinx.coroutines.Dispatchers.IO)")
dotQualifiedParent.replaced(flowOnExpression)
}
addImportExplicitly(project, refactoredElement.containingKtFile, "kotlinx.coroutines.flow.flowOn")
CoroutineBlockingCallInspectionUtils.postProcessQuickFix(refactoredElement, project)
} else {
val replacedArgument = flowOnCallOrNull.getFirstArgumentExpression()
?.replaced(ktPsiFactory.createExpression("kotlinx.coroutines.Dispatchers.IO")) ?: return
CoroutineBlockingCallInspectionUtils.postProcessQuickFix(replacedArgument, project)
}
}
private fun addImportExplicitly(project: Project, file: KtFile, @Suppress("SameParameterValue") fqnToImport: String) {
ImportInsertHelperImpl.addImport(project, file, FqName(fqnToImport))
}
} | apache-2.0 | 389babbcd10c3bf56d76f1bc8158a87c | 54.278689 | 158 | 0.749629 | 5.333861 | false | false | false | false |
mdaniel/intellij-community | plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/tree/ContentRootCollectorTest.kt | 1 | 31842 | // 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.idea.maven.importing.tree
import com.intellij.maven.testFramework.MavenTestCase
import junit.framework.TestCase
import org.jetbrains.idea.maven.importing.workspaceModel.ContentRootCollector
import org.jetbrains.idea.maven.importing.workspaceModel.ContentRootCollector.collect
import org.jetbrains.jps.model.java.JavaResourceRootType
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
import org.junit.Test
class ContentRootCollectorTest : MavenTestCase() {
@Test
fun `test simple content root`() {
val baseContentRoot = "/home/a/b/c/maven"
val sourceMain = "/home/a/b/c/maven/src/main/java"
val resourceMain = "/home/a/b/c/maven/src/main/resources"
val sourceTest = "/home/a/b/c/maven/src/test/java"
val target = "/home/a/b/c/maven/target"
val generatedSourceFolder = "/home/a/b/c/maven/target/generated-sources/java"
val generatedTestSourceFolder = "/home/a/b/c/maven/target/generated-sources-test/java"
val annotationProcessorDirectory = "/home/a/b/c/maven/target/annotation-processor/java"
val annotationProcessorTestDirectory = "/home/a/b/c/maven/target/annotation-processor-test/java"
val contentRoots = collect(projectRoots = listOf(baseContentRoot),
mainSourceFolders = listOf(sourceMain),
mainResourceFolders = listOf(resourceMain),
testSourceFolders = listOf(sourceTest),
mainGeneratedSourceFolders = listOf(generatedSourceFolder),
testGeneratedSourceFolders = listOf(generatedTestSourceFolder),
mainAnnotationSourceFolders = listOf(annotationProcessorDirectory),
testAnnotationSourceFolders = listOf(annotationProcessorTestDirectory),
excludeFolders = listOf(target))
assertContentRoots(contentRoots,
listOf(ContentRootTestData(
expectedPath = baseContentRoot,
expectedMainSourceFolders = listOf(sourceMain),
expectedMainResourcesFolders = listOf(resourceMain),
expectedTestSourceFolders = listOf(sourceTest),
expectedMainGeneratedFolders = listOf(generatedSourceFolder,
annotationProcessorDirectory),
expectedTestGeneratedFolders = listOf(generatedTestSourceFolder,
annotationProcessorTestDirectory),
expectedExcludes = listOf(target)))
)
}
@Test
fun `test do not register nested sources`() {
val baseContentRoot = "/home"
val source = "/home/source"
val nestedSource = "/home/source/dir/nested"
val contentRoots = collect(projectRoots = listOf(baseContentRoot),
mainSourceFolders = listOf(source, nestedSource))
assertContentRoots(contentRoots,
listOf(ContentRootTestData(expectedPath = baseContentRoot,
expectedMainSourceFolders = listOf(source)))
)
}
@Test
fun `test source folders override resource folders`() {
val root = "/home"
val sourceMain = "/home/main/source"
val sourceTest = "/home/test/source"
val contentRoots = collect(projectRoots = listOf(root),
mainSourceFolders = listOf(sourceMain),
mainResourceFolders = listOf(sourceMain),
testSourceFolders = listOf(sourceTest),
testResourceFolders = listOf(sourceTest))
assertContentRoots(contentRoots,
listOf(ContentRootTestData(
expectedPath = root,
expectedMainSourceFolders = listOf(sourceMain),
expectedMainResourcesFolders = listOf(),
expectedTestSourceFolders = listOf(sourceTest),
expectedTestResourcesFolders = listOf()))
)
}
@Test
fun `test source folders override test folders`() {
val root = "/home"
val sourceMain = "/home/main/source"
val resourceMain = "/home/main/resource"
val generatedSourceFolder = "/home/main/generated-sources"
val annotationProcessorDirectory = "/home/main/annotation-sources"
val contentRoots = collect(projectRoots = listOf(root),
mainSourceFolders = listOf(sourceMain),
mainResourceFolders = listOf(resourceMain),
testSourceFolders = listOf(sourceMain),
testResourceFolders = listOf(resourceMain),
mainGeneratedSourceFolders = listOf(generatedSourceFolder),
testGeneratedSourceFolders = listOf(generatedSourceFolder),
mainAnnotationSourceFolders = listOf(annotationProcessorDirectory),
testAnnotationSourceFolders = listOf(annotationProcessorDirectory))
assertContentRoots(contentRoots,
listOf(ContentRootTestData(
expectedPath = root,
expectedMainSourceFolders = listOf(sourceMain),
expectedMainResourcesFolders = listOf(resourceMain),
expectedTestSourceFolders = listOf(),
expectedTestResourcesFolders = listOf(),
expectedMainGeneratedFolders = listOf(generatedSourceFolder,
annotationProcessorDirectory),
expectedTestGeneratedFolders = listOf()))
)
}
@Test
fun `test do not register nested content root`() {
val root1 = "/home"
val source1 = "/home/source"
val root2 = "/home/source/dir/nested"
val source2 = "/home/source/dir/nested/source"
val contentRoots = collect(projectRoots = listOf(root1, root2),
mainSourceFolders = listOf(source1, source2))
assertContentRoots(contentRoots,
listOf(ContentRootTestData(expectedPath = root1,
expectedMainSourceFolders = listOf(source1)))
)
}
@Test
fun `test do not register nested generated folder under a source folder`() {
val root = "/project/"
val source = "/project/source"
val nestedGeneratedFolder = "/project/source/generated"
val nestedAnnotationProcessorFolder = "/project/source/annotation"
val contentRoots = collect(projectRoots = listOf(root),
mainSourceFolders = listOf(source),
mainGeneratedSourceFolders = listOf(nestedGeneratedFolder),
mainAnnotationSourceFolders = listOf(nestedAnnotationProcessorFolder))
assertContentRoots(contentRoots,
listOf(ContentRootTestData(
expectedPath = root,
expectedMainSourceFolders = listOf(source),
expectedMainGeneratedFolders = listOf()))
)
}
@Test
fun `test do not register generated folder when there is a nested source or generated folder`() {
val root = "/project/"
val generatedWithNestedSourceFolder = "/project/generated-with-sources"
val source = "/project/generated-with-sources/source"
val generatedWithNestedGeneratedFolder = "/project/generated-with-generated"
val generatedNestedFoldersHolder = "/project/generated-with-generated/generated"
val generatedNoNestedFolders = "/project/target/generated-no-subsources/"
val contentRoots = collect(projectRoots = listOf(root),
mainSourceFolders = listOf(source),
mainGeneratedSourceFolders = listOf(generatedWithNestedSourceFolder,
generatedWithNestedGeneratedFolder,
generatedNestedFoldersHolder,
generatedNoNestedFolders))
assertContentRoots(contentRoots,
listOf(ContentRootTestData(
expectedPath = root,
expectedMainSourceFolders = listOf(source),
expectedMainGeneratedFolders = listOf(generatedNestedFoldersHolder,
generatedNoNestedFolders)))
)
}
@Test
fun `test do not register generated folder with a nested source, but create a root`() {
val root = "/root1/"
val generatedWithNestedSourceFolder = "/generated-with-sources"
val source = "/generated-with-sources/source"
val generatedWithNestedGeneratedFolder = "/generated-with-generated"
val generatedNestedFoldersHolder = "/generated-with-generated/generated"
val contentRoots = collect(
projectRoots = listOf(root),
mainSourceFolders = listOf(source),
mainGeneratedSourceFolders = listOf(generatedWithNestedSourceFolder,
generatedWithNestedGeneratedFolder,
generatedNestedFoldersHolder),
)
assertContentRoots(contentRoots,
listOf(ContentRootTestData(expectedPath = root,
expectedMainSourceFolders = listOf(),
expectedMainGeneratedFolders = listOf()),
ContentRootTestData(expectedPath = generatedWithNestedSourceFolder,
expectedMainSourceFolders = listOf(source),
expectedMainGeneratedFolders = listOf()),
ContentRootTestData(expectedPath = generatedWithNestedGeneratedFolder,
expectedMainSourceFolders = listOf(),
expectedMainGeneratedFolders = listOf(generatedNestedFoldersHolder)))
)
}
@Test
fun `test do not register annotation processor folder when there is parent generated or source folder`() {
val root = "/project/"
val source = "/project/source"
val generated = "/project/generated"
val annotation = "/project/annotation"
val annotationUnderSource = "/project/source/annotation"
val annotationUnderGenerated = "/project/generated/annotation"
val annotationUnderAnnotation = "/project/annotation/annotation"
val contentRoots = collect(listOf(root),
listOf(source),
mainGeneratedSourceFolders = listOf(generated),
mainAnnotationSourceFolders = listOf(annotation,
annotationUnderSource,
annotationUnderGenerated,
annotationUnderAnnotation))
assertContentRoots(contentRoots,
listOf(ContentRootTestData(
expectedPath = root,
expectedMainSourceFolders = listOf(source),
expectedMainGeneratedFolders = listOf(generated, annotation)))
)
}
@Test
fun `test folders outside of the content root`() {
val baseContentRoot = "/home/content"
val source = "/home/source"
val generated = "/home/generated"
val target = "/home/target" // will not be registered
val contentRoots = collect(projectRoots = listOf(baseContentRoot),
mainSourceFolders = listOf(source),
mainGeneratedSourceFolders = listOf(generated),
excludeFolders = listOf(target))
assertContentRoots(contentRoots,
listOf(ContentRootTestData(expectedPath = baseContentRoot),
ContentRootTestData(expectedPath = source, expectedMainSourceFolders = listOf(source)),
ContentRootTestData(expectedPath = generated, expectedMainGeneratedFolders = listOf(generated)))
)
}
@Test
fun `test exclude folders`() {
val contentRoots = collect(projectRoots = listOf("/home"),
mainSourceFolders = listOf("/home/src",
"/home/exclude1/src",
"/home/exclude6"),
mainGeneratedSourceFolders = listOf("/home/exclude2/annotations", "/home/exclude4/generated"),
testGeneratedSourceFolders = listOf("/home/exclude3/annotations-test", "/home/exclude5/generated-test"),
excludeFolders = listOf("/home/exclude1",
"/home/exclude2",
"/home/exclude3",
"/home/exclude4",
"/home/exclude5",
"/home/exclude6",
"/home/exclude7")
)
assertContentRoots(contentRoots,
listOf(ContentRootTestData(
expectedPath = "/home",
expectedMainSourceFolders = listOf("/home/src",
"/home/exclude1/src",
"/home/exclude6"),
expectedMainGeneratedFolders = listOf("/home/exclude2/annotations",
"/home/exclude4/generated"),
expectedTestGeneratedFolders = listOf("/home/exclude3/annotations-test",
"/home/exclude5/generated-test"),
expectedExcludes = listOf("/home/exclude1",
"/home/exclude2",
"/home/exclude3",
"/home/exclude4",
"/home/exclude5",
"/home/exclude7")))
)
}
@Test
fun `test do not register content root for a single exclude folder`() {
val contentRoots = collect(projectRoots = listOf(),
mainSourceFolders = listOf("/root/src"),
mainGeneratedSourceFolders = listOf("/root/generated"),
excludeFolders = listOf("/root/exclude"))
assertContentRoots(contentRoots,
listOf(
ContentRootTestData(
expectedPath = "/root/src",
expectedMainSourceFolders = listOf("/root/src"),
expectedMainGeneratedFolders = listOf(),
expectedExcludes = listOf()),
ContentRootTestData(
expectedPath = "/root/generated",
expectedMainSourceFolders = listOf(),
expectedMainGeneratedFolders = listOf("/root/generated"),
expectedExcludes = listOf()))
)
}
@Test
fun `test do not register nested exclude folder`() {
val root = "/root"
val exclude = "/root/exclude"
val nestedExclude = "/root/exclude/exclude"
val nestedExcludeAndPreventSubfolders = "/root/exclude/exclude-no-subfolders"
val excludeAndPreventSubfolders = "/root/exclude-no-subfolders"
val excludeAndPreventSubfolders_NestedExclude = "/root/exclude-no-subfolders/exclude"
val excludeAndPreventSubfolders_NestedExcludeAndPreventSubfolders = "/root/exclude-no-subfolders/exclude-no-subfolders"
val contentRoots = collect(projectRoots = listOf(root),
excludeFolders = listOf(exclude,
nestedExclude,
excludeAndPreventSubfolders_NestedExclude),
excludeAndPreventSubfoldersFolders = listOf(nestedExcludeAndPreventSubfolders,
excludeAndPreventSubfolders,
excludeAndPreventSubfolders_NestedExcludeAndPreventSubfolders))
assertContentRoots(contentRoots,
listOf(ContentRootTestData(
expectedPath = root,
expectedExcludes = listOf(exclude, excludeAndPreventSubfolders)))
)
}
@Test
fun `test do not register exclude folder pointing to a root`() {
val contentRoots = collect(projectRoots = listOf("/root"),
mainSourceFolders = listOf("/root/src"),
mainGeneratedSourceFolders = listOf("/root/generated"),
excludeFolders = listOf("/root"))
assertContentRoots(contentRoots,
listOf(
ContentRootTestData(
expectedPath = "/root",
expectedMainSourceFolders = listOf("/root/src"),
expectedMainGeneratedFolders = listOf("/root/generated"),
expectedExcludes = listOf()))
)
}
@Test
fun `test exclude and prevent nested folders`() {
val root = "/home"
val excludeWithSource = "/home/exclude-with-source"
val sourcesUnderExcluded = "/home/exclude-with-source/src"
val excludeWithGenerated = "/home/exclude-with-generated"
val generatedUnderExcluded = "/home/exclude-with-generated/generated"
val excludeWithTestGenerated = "/home/exclude-with-test-generated"
val testGeneratedUnderExcluded = "/home/exclude-with-test-generated/test-generated"
val excludeWithAnnotation = "/home/exclude-with-annotation"
val annotationUnderExcluded = "/home/exclude-with-annotation/annotation"
val excludeWithTestAnnotation = "/home/exclude-with-test-annotation"
val testAnnotationUnderExcluded = "/home/exclude-with-test-annotation/test-annotation"
val contentRoots = collect(projectRoots = listOf(root),
mainSourceFolders = listOf(sourcesUnderExcluded),
mainGeneratedSourceFolders = listOf(generatedUnderExcluded),
testGeneratedSourceFolders = listOf(testGeneratedUnderExcluded),
mainAnnotationSourceFolders = listOf(annotationUnderExcluded),
testAnnotationSourceFolders = listOf(testAnnotationUnderExcluded),
excludeAndPreventSubfoldersFolders = listOf(excludeWithSource,
excludeWithGenerated,
excludeWithTestGenerated,
excludeWithAnnotation,
excludeWithTestAnnotation))
assertContentRoots(contentRoots,
listOf(ContentRootTestData(
expectedPath = root,
expectedMainSourceFolders = listOf(),
expectedTestSourceFolders = listOf(),
expectedMainGeneratedFolders = listOf(),
expectedTestGeneratedFolders = listOf(),
expectedExcludes = listOf(excludeWithSource,
excludeWithGenerated,
excludeWithAnnotation,
excludeWithTestGenerated,
excludeWithTestAnnotation)))
)
}
@Test
fun `test multiple content roots and empty exclude root and generated sources`() {
val baseContentRoot = "/home/src/main"
val sourceMain = "/home/src/main/java"
val sourceMain2 = "/home/java2"
val target = "/home/target"
val generatedSourceFolder = "/home/target/generated-sources/java"
val testGeneratedSourceFolder = "/home/target/test-generated-sources/java"
val annotationSourceFolder = "/home/target/annotation-sources/java"
val testAnnotationSourceFolder = "/home/target/test-annotation-sources/java"
val contentRoots = collect(projectRoots = listOf(baseContentRoot),
mainSourceFolders = listOf(sourceMain, sourceMain2),
mainGeneratedSourceFolders = listOf(generatedSourceFolder),
testGeneratedSourceFolders = listOf(testGeneratedSourceFolder),
mainAnnotationSourceFolders = listOf(annotationSourceFolder),
testAnnotationSourceFolders = listOf(testAnnotationSourceFolder),
excludeFolders = listOf(target),
excludeAndPreventSubfoldersFolders = emptyList())
assertContentRoots(
contentRoots,
listOf(
ContentRootTestData(expectedPath = baseContentRoot, expectedMainSourceFolders = listOf(sourceMain)),
ContentRootTestData(expectedPath = sourceMain2, expectedMainSourceFolders = listOf(sourceMain2)),
ContentRootTestData(expectedPath = generatedSourceFolder, expectedMainGeneratedFolders = listOf(generatedSourceFolder)),
ContentRootTestData(expectedPath = testGeneratedSourceFolder, expectedTestGeneratedFolders = listOf(testGeneratedSourceFolder)),
ContentRootTestData(expectedPath = annotationSourceFolder,
expectedMainGeneratedFolders = listOf(annotationSourceFolder)),
ContentRootTestData(expectedPath = testAnnotationSourceFolder,
expectedTestGeneratedFolders = listOf(testAnnotationSourceFolder)))
)
}
@Test
fun `test multiple source and resources content roots and annotation processor sources`() {
val baseContentRoot = "/home/a/b/c/maven/src/main"
val sourceMain = "/home/a/b/c/maven/src/main/java"
val sourceMain2 = "/home/a/b/c/maven/java2"
val sourceMain3 = "/home/a/b/c/maven/main/java3"
val sourceMain4 = "/home/a/b/c/other/java4"
val resourceMain = "/home/a/b/c/maven/src/main/resource"
val resourceMain2 = "/home/a/b/c/maven/resource2"
val resourceMain3 = "/home/a/b/c/maven/main/resource3"
val resourceMain4 = "/home/a/b/c/other/resource4"
val annotationProcessorDirectory = "/home/a/b/c/maven/target/annotation-processor/java"
val annotationProcessorTestDirectory = "/home/a/b/c/maven/target/annotation-processor-test/java"
val contentRoots = collect(projectRoots = listOf(baseContentRoot),
mainSourceFolders = listOf(
sourceMain4,
sourceMain3,
sourceMain2,
sourceMain),
mainResourceFolders = listOf(
resourceMain4,
resourceMain3,
resourceMain2,
resourceMain,
),
mainAnnotationSourceFolders = listOf(annotationProcessorDirectory),
testAnnotationSourceFolders = listOf(annotationProcessorTestDirectory))
assertContentRoots(contentRoots, listOf(
ContentRootTestData(expectedPath = baseContentRoot,
expectedMainSourceFolders = listOf(sourceMain),
expectedMainResourcesFolders = listOf(resourceMain)),
ContentRootTestData(expectedPath = sourceMain2, expectedMainSourceFolders = listOf(sourceMain2)),
ContentRootTestData(expectedPath = sourceMain3, expectedMainSourceFolders = listOf(sourceMain3)),
ContentRootTestData(expectedPath = sourceMain4, expectedMainSourceFolders = listOf(sourceMain4)),
ContentRootTestData(expectedPath = resourceMain2, expectedMainResourcesFolders = listOf(resourceMain2)),
ContentRootTestData(expectedPath = resourceMain3, expectedMainResourcesFolders = listOf(resourceMain3)),
ContentRootTestData(expectedPath = resourceMain4, expectedMainResourcesFolders = listOf(resourceMain4)),
ContentRootTestData(expectedPath = annotationProcessorDirectory,
expectedMainGeneratedFolders = listOf(annotationProcessorDirectory)),
ContentRootTestData(expectedPath = annotationProcessorTestDirectory,
expectedTestGeneratedFolders = listOf(annotationProcessorTestDirectory)))
)
}
private fun collect(projectRoots: List<String> = emptyList(),
mainSourceFolders: List<String> = emptyList(),
mainResourceFolders: List<String> = emptyList(),
testSourceFolders: List<String> = emptyList(),
testResourceFolders: List<String> = emptyList(),
mainGeneratedSourceFolders: List<String> = emptyList(),
testGeneratedSourceFolders: List<String> = emptyList(),
mainAnnotationSourceFolders: List<String> = emptyList(),
testAnnotationSourceFolders: List<String> = emptyList(),
excludeFolders: List<String> = emptyList(),
excludeAndPreventSubfoldersFolders: List<String> = emptyList()): Collection<ContentRootCollector.ContentRootResult> {
val folders = mutableListOf<ContentRootCollector.ImportedFolder>()
projectRoots.forEach { folders.add(ContentRootCollector.ProjectRootFolder(it)) }
mainSourceFolders.forEach { folders.add(ContentRootCollector.SourceFolder(it, JavaSourceRootType.SOURCE)) }
mainResourceFolders.forEach { folders.add(ContentRootCollector.SourceFolder(it, JavaResourceRootType.RESOURCE)) }
mainGeneratedSourceFolders.forEach {
folders.add(ContentRootCollector.GeneratedSourceFolder(it, JavaSourceRootType.SOURCE))
}
mainAnnotationSourceFolders.forEach {
folders.add(ContentRootCollector.AnnotationSourceFolder(it, JavaSourceRootType.SOURCE))
}
testSourceFolders.forEach { folders.add(ContentRootCollector.SourceFolder(it, JavaSourceRootType.TEST_SOURCE)) }
testResourceFolders.forEach { folders.add(ContentRootCollector.SourceFolder(it, JavaResourceRootType.TEST_RESOURCE)) }
testGeneratedSourceFolders.forEach {
folders.add(ContentRootCollector.GeneratedSourceFolder(it, JavaSourceRootType.TEST_SOURCE))
}
testAnnotationSourceFolders.forEach {
folders.add(ContentRootCollector.AnnotationSourceFolder(it, JavaSourceRootType.TEST_SOURCE))
}
excludeFolders.forEach { folders.add(ContentRootCollector.ExcludedFolder(it)) }
excludeAndPreventSubfoldersFolders.forEach { folders.add(ContentRootCollector.ExcludedFolderAndPreventSubfolders(it)) }
return collect(folders)
}
private fun assertContentRoots(actualRoots: Collection<ContentRootCollector.ContentRootResult>,
expectedRoots: Collection<ContentRootTestData>) {
fun mapPaths(result: ContentRootCollector.ContentRootResult,
type: JpsModuleSourceRootType<*>,
isGenerated: Boolean) =
result.sourceFolders.filter { it.type == type && it.isGenerated == isGenerated }.map { it.path }.sorted()
val actualSorted = actualRoots.map {
ContentRootTestData(
it.path,
expectedMainSourceFolders = mapPaths(it, JavaSourceRootType.SOURCE, isGenerated = false),
expectedMainResourcesFolders = mapPaths(it, JavaResourceRootType.RESOURCE, isGenerated = false),
expectedMainGeneratedFolders = mapPaths(it, JavaSourceRootType.SOURCE, isGenerated = true),
expectedTestSourceFolders = mapPaths(it, JavaSourceRootType.TEST_SOURCE, isGenerated = false),
expectedTestResourcesFolders = mapPaths(it, JavaResourceRootType.TEST_RESOURCE, isGenerated = false),
expectedTestGeneratedFolders = mapPaths(it, JavaSourceRootType.TEST_SOURCE, isGenerated = true),
expectedExcludes = it.excludeFolders.map { it.path }.sorted(),
)
}.sortedBy { it.expectedPath }
val expectedSorted = expectedRoots.map {
it.copy(
expectedMainSourceFolders = it.expectedMainSourceFolders.sorted(),
expectedMainResourcesFolders = it.expectedMainResourcesFolders.sorted(),
expectedMainGeneratedFolders = it.expectedMainGeneratedFolders.sorted(),
expectedTestSourceFolders = it.expectedTestSourceFolders.sorted(),
expectedTestResourcesFolders = it.expectedTestResourcesFolders.sorted(),
expectedTestGeneratedFolders = it.expectedTestGeneratedFolders.sorted(),
expectedExcludes = it.expectedExcludes.sorted()
)
}.sortedBy { it.expectedPath }
TestCase.assertEquals(expectedSorted, actualSorted)
}
private data class ContentRootTestData(val expectedPath: String,
val expectedMainSourceFolders: List<String> = emptyList(),
val expectedTestSourceFolders: List<String> = emptyList(),
val expectedMainResourcesFolders: List<String> = emptyList(),
val expectedTestResourcesFolders: List<String> = emptyList(),
val expectedMainGeneratedFolders: List<String> = emptyList(),
val expectedTestGeneratedFolders: List<String> = emptyList(),
val expectedExcludes: List<String> = emptyList()) {
override fun toString(): String {
val result = StringBuilder()
result.appendLine("{")
result.append("Root: ").appendLine(expectedPath)
fun appendIfNotEmpty(list: List<String>, type: String) {
if (list.isNotEmpty()) {
list.joinTo(result, prefix = " $type:\n ", separator = "\n ", postfix = "\n")
}
}
appendIfNotEmpty(expectedMainSourceFolders, "Main Sources")
appendIfNotEmpty(expectedMainResourcesFolders, "Main Resources")
appendIfNotEmpty(expectedMainGeneratedFolders, "Main Generated")
appendIfNotEmpty(expectedTestSourceFolders, "Test Sources")
appendIfNotEmpty(expectedTestResourcesFolders, "Test Resources")
appendIfNotEmpty(expectedTestGeneratedFolders, "Test Generated")
appendIfNotEmpty(expectedExcludes, "Excludes")
result.appendLine("}")
return result.toString()
}
}
} | apache-2.0 | 6e29334761f7e39fefc46426c75e63f5 | 52.607744 | 139 | 0.589976 | 6.039833 | false | true | false | false |
mdaniel/intellij-community | plugins/kotlin/gradle/gradle-tooling/tests/test/createKotlinMPPGradleModel.kt | 1 | 5581 | // 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.gradle
import org.gradle.internal.impldep.org.apache.commons.lang.math.RandomUtils
import org.jetbrains.kotlin.idea.gradleTooling.*
import org.jetbrains.kotlin.idea.gradleTooling.arguments.*
import org.jetbrains.kotlin.idea.projectModel.*
internal fun createKotlinMPPGradleModel(
dependencyMap: Map<KotlinDependencyId, KotlinDependency> = emptyMap(),
sourceSets: Set<KotlinSourceSet> = emptySet(),
targets: Iterable<KotlinTarget> = emptyList(),
extraFeatures: ExtraFeatures = createExtraFeatures(),
kotlinNativeHome: String = ""
): KotlinMPPGradleModelImpl {
return KotlinMPPGradleModelImpl(
dependencyMap = dependencyMap,
sourceSetsByName = sourceSets.associateBy { it.name },
targets = targets.toList(),
extraFeatures = extraFeatures,
kotlinNativeHome = kotlinNativeHome,
cacheAware = CompilerArgumentsCacheAwareImpl()
)
}
internal fun createExtraFeatures(
coroutinesState: String? = null,
isHmppEnabled: Boolean = false,
): ExtraFeaturesImpl {
return ExtraFeaturesImpl(
coroutinesState = coroutinesState,
isHMPPEnabled = isHmppEnabled,
)
}
internal fun createKotlinSourceSet(
name: String,
declaredDependsOnSourceSets: Set<String> = emptySet(),
allDependsOnSourceSets: Set<String> = declaredDependsOnSourceSets,
platforms: Set<KotlinPlatform> = emptySet(),
): KotlinSourceSetImpl = KotlinSourceSetImpl(
name = name,
languageSettings = KotlinLanguageSettingsImpl(
languageVersion = null,
apiVersion = null,
isProgressiveMode = false,
enabledLanguageFeatures = emptySet(),
optInAnnotationsInUse = emptySet(),
compilerPluginArguments = emptyArray(),
compilerPluginClasspath = emptySet(),
freeCompilerArgs = emptyArray()
),
sourceDirs = emptySet(),
resourceDirs = emptySet(),
regularDependencies = emptyArray(),
intransitiveDependencies = emptyArray(),
declaredDependsOnSourceSets = declaredDependsOnSourceSets,
allDependsOnSourceSets = allDependsOnSourceSets,
additionalVisibleSourceSets = emptySet(),
actualPlatforms = KotlinPlatformContainerImpl().apply { pushPlatforms(platforms) },
)
@Suppress("DEPRECATION_ERROR")
internal fun createKotlinCompilation(
name: String = "main",
defaultSourceSets: Set<KotlinSourceSet> = emptySet(),
allSourceSets: Set<KotlinSourceSet> = emptySet(),
dependencies: Iterable<KotlinDependencyId> = emptyList(),
output: KotlinCompilationOutput = createKotlinCompilationOutput(),
arguments: KotlinCompilationArguments = createKotlinCompilationArguments(),
dependencyClasspath: Iterable<String> = emptyList(),
cachedArgsInfo: CachedArgsInfo<*> = createCachedArgsInfo(),
kotlinTaskProperties: KotlinTaskProperties = createKotlinTaskProperties(),
nativeExtensions: KotlinNativeCompilationExtensions? = null,
associateCompilations: Set<KotlinCompilationCoordinates> = emptySet()
): KotlinCompilationImpl {
return KotlinCompilationImpl(
name = name,
declaredSourceSets = defaultSourceSets,
allSourceSets = allSourceSets,
dependencies = dependencies.toList().toTypedArray(),
output = output,
arguments = arguments,
dependencyClasspath = dependencyClasspath.toList().toTypedArray(),
cachedArgsInfo = cachedArgsInfo,
kotlinTaskProperties = kotlinTaskProperties,
nativeExtensions = nativeExtensions,
associateCompilations = associateCompilations
)
}
internal fun createKotlinCompilationOutput(): KotlinCompilationOutputImpl {
return KotlinCompilationOutputImpl(
classesDirs = emptySet(),
effectiveClassesDir = null,
resourcesDir = null
)
}
@Suppress("DEPRECATION_ERROR")
internal fun createKotlinCompilationArguments(): KotlinCompilationArgumentsImpl {
return KotlinCompilationArgumentsImpl(
defaultArguments = emptyArray(),
currentArguments = emptyArray()
)
}
internal fun createCachedArgsBucket(): CachedCompilerArgumentsBucket = CachedCompilerArgumentsBucket(
compilerArgumentsClassName = KotlinCachedRegularCompilerArgument(0),
singleArguments = emptyMap(),
classpathParts = KotlinCachedMultipleCompilerArgument(emptyList()),
multipleArguments = emptyMap(),
flagArguments = emptyMap(),
internalArguments = emptyList(),
freeArgs = emptyList()
)
internal fun createCachedArgsInfo(): CachedArgsInfo<*> = CachedExtractedArgsInfo(
cacheOriginIdentifier = RandomUtils.nextLong(),
currentCompilerArguments = createCachedArgsBucket(),
defaultCompilerArguments = createCachedArgsBucket(),
dependencyClasspath = emptyList()
)
internal fun createKotlinTaskProperties(): KotlinTaskPropertiesImpl {
return KotlinTaskPropertiesImpl(
null, null, null, null
)
}
internal fun createKotlinTarget(
name: String,
platform: KotlinPlatform = KotlinPlatform.COMMON,
compilations: Iterable<KotlinCompilation> = emptyList()
): KotlinTargetImpl {
return KotlinTargetImpl(
name = name,
presetName = null,
disambiguationClassifier = null,
platform = platform,
compilations = compilations.toList(),
testRunTasks = emptyList(),
nativeMainRunTasks = emptyList(),
jar = null,
konanArtifacts = emptyList()
)
}
| apache-2.0 | 697b460af6237028ef364a9d8af8c819 | 36.709459 | 158 | 0.734456 | 5.918346 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/pisa/PisaUltralightTransitData.kt | 1 | 2515 | /*
* PisaTransitData.kt
*
* Copyright 2018-2019 Google
*
* 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 au.id.micolous.metrodroid.transit.pisa
import au.id.micolous.metrodroid.card.ultralight.UltralightCard
import au.id.micolous.metrodroid.card.ultralight.UltralightCardTransitFactory
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.transit.TransactionTrip
import au.id.micolous.metrodroid.transit.TransactionTripAbstract
import au.id.micolous.metrodroid.transit.TransitData
import au.id.micolous.metrodroid.transit.TransitIdentity
import au.id.micolous.metrodroid.ui.ListItem
private const val NAME = "Pisa Ultralight"
@Parcelize
data class PisaUltralightTransitData(override val trips: List<TransactionTripAbstract>,
private val mA: Int,
private val mB: Long) : TransitData() {
override val serialNumber: String? get() = null
override val cardName get() = NAME
override fun getRawFields(level: TransitData.RawLevel) = listOf(ListItem("A", mA.toString()),
ListItem("B", mB.toString(16)))
}
private fun parse(card: UltralightCard): PisaUltralightTransitData {
val trips = listOf(8, 12).mapNotNull { offset ->
PisaTransaction.parseUltralight(card.readPages(offset, 4))
}
return PisaUltralightTransitData(
mA = card.getPage(4).data[3].toInt() and 0xff,
mB = card.readPages(6, 2).byteArrayToLong(),
trips = TransactionTrip.merge(trips))
}
class PisaUltralightTransitFactory : UltralightCardTransitFactory {
override fun check(card: UltralightCard) =
card.getPage(4).data.byteArrayToInt(0, 3) == PisaTransitData.PISA_NETWORK_ID
override fun parseTransitData(card: UltralightCard) = parse(card)
override fun parseTransitIdentity(card: UltralightCard) = TransitIdentity(NAME, null)
}
| gpl-3.0 | e0ed790e80f333268c54b41d48264b7a | 39.564516 | 97 | 0.730815 | 4.234007 | false | false | false | false |
Mystery00/JanYoShare | app/src/main/java/com/janyo/janyoshare/util/SocketUtil.kt | 1 | 6720 | package com.janyo.janyoshare.util
import android.content.Context
import android.net.Uri
import com.janyo.janyoshare.classes.TransferFile
import vip.mystery0.tools.logs.Logs
import java.io.*
import java.net.ConnectException
import java.net.ServerSocket
import java.net.Socket
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
class SocketUtil
{
private val TAG = "SocketUtil"
lateinit var socket: Socket
private lateinit var serverSocket: ServerSocket
lateinit var ip: String
fun tryCreateSocketConnection(host: String, port: Int): Boolean
{
return try
{
val socket = Socket(host, port)
if (socket.isConnected)
{
socket.keepAlive = true
ip = host
this.socket = socket
}
socket.isConnected
}
catch (e: ConnectException)
{
e.printStackTrace()
false
}
}
fun createSocketConnection(host: String, port: Int): Boolean
{
while (true)
{
try
{
val socket = Socket(host, port)
if (socket.isConnected)
{
this.socket = socket
break
}
}
catch (e: Exception)
{
Thread.sleep(100)
continue
}
}
socket.keepAlive = true
ip = host
return socket.isConnected
}
fun createServerConnection(port: Int): Boolean
{
try
{
val singleThreadPool = Executors.newSingleThreadExecutor()
val task = singleThreadPool.submit {
serverSocket = ServerSocket(port)
socket = serverSocket.accept()
}
try
{
task.get(20, TimeUnit.SECONDS)
}
catch (e: TimeoutException)
{
serverDisconnect()
Logs.wtf(TAG, "createServerConnection: 超时", e)
return false
}
finally
{
task.cancel(true)
}
socket.keepAlive = true
this.socket = socket
}
catch (e: Exception)
{
serverDisconnect()
Logs.wtf(TAG, "createServerConnection", e)
return false
}
return socket.isConnected
}
fun receiveMessage(): String
{
var response = "null"
val executorService = Executors.newSingleThreadExecutor()
val task = executorService.submit {
val inputStream = socket.getInputStream()
response = BufferedReader(InputStreamReader(inputStream)).readLine()
}
try
{
task.get(20, TimeUnit.SECONDS)
}
catch (e: TimeoutException)
{
Logs.wtf(TAG, "receiveMessage: 超时", e)
}
finally
{
task.cancel(true)
}
return response
}
fun sendMessage(message: String)
{
try
{
val outputStream = socket.getOutputStream()
outputStream.write((message + "\n").toByteArray())
outputStream.flush()
}
catch (e: Exception)
{
Logs.wtf(TAG, "sendMessage", e)
}
}
fun receiveFile(fileSize: Long, path: String, fileTransferListener: FileTransferListener): File?
{
createSocketConnection(FileTransferHelper.getInstance().ip, FileTransferHelper.getInstance().transferPort)
val file = File(path)
if (file.exists())
{
clientDisconnect()
fileTransferListener.onError(1, RuntimeException("file is exists!"))
return null
}
try
{
Logs.i(TAG, "receiveFile: 文件大小" + fileSize)
val dataInputStream: DataInputStream? = DataInputStream(BufferedInputStream(socket.getInputStream()))
val bytes = ByteArray(1024 * 1024)
var transferredSize = 0L
val dataOutputStream = DataOutputStream(BufferedOutputStream(FileOutputStream(file)))
fileTransferListener.onStart()
while (true)
{
val read = dataInputStream!!.read(bytes)
transferredSize += read
Logs.i(TAG, "receiveFile: " + read)
if (read <= 0)
{
Logs.i(TAG, "receiveFile: 退出循环")
break
}
fileTransferListener.onProgress((transferredSize * 100 / fileSize).toInt())
dataOutputStream.write(bytes, 0, read)
Logs.i(TAG, "receiveFile: 写入" + read + "个数据")
if (fileSize == transferredSize)
{
Logs.i(TAG, "receiveFile: 退出循环")
break
}
Thread.sleep(100)
if (socket.isClosed)
{
fileTransferListener.onError(3, Exception("连接关闭"))
}
}
}
catch (e: Exception)
{
fileTransferListener.onError(2, e)
}
Logs.i(TAG, "receiveFile: 文件完成")
clientDisconnect()
fileTransferListener.onFinish()
return file
}
fun sendFile(context: Context, transferFile: TransferFile,
fileTransferListener: FileTransferListener)
{
createServerConnection(FileTransferHelper.getInstance().transferPort)
try
{
Logs.i(TAG, "sendFile: fileSize" + transferFile.fileSize)
val dataOutputStream = DataOutputStream(socket.getOutputStream())
val parcelFileDescriptor = context.contentResolver.openFileDescriptor(Uri.parse(transferFile.fileUri), "r")
val fileDescriptor = parcelFileDescriptor.fileDescriptor
val dataInputStream = DataInputStream(BufferedInputStream(FileInputStream(fileDescriptor)))
var transferredSize = 0L
val bytes = ByteArray(1024 * 1024)
fileTransferListener.onStart()
while (true)
{
val read = dataInputStream.read(bytes)
Logs.i(TAG, "sendFile: " + read)
transferredSize += read
fileTransferListener.onProgress((transferredSize * 100 / transferFile.fileSize).toInt())
if (read <= 0)
{
Logs.i(TAG, "sendFile: 退出循环")
break
}
dataOutputStream.write(bytes, 0, read)
if (socket.isClosed)
{
fileTransferListener.onError(3, Exception("连接关闭"))
}
}
dataOutputStream.flush()
Logs.i(TAG, "sendFile: 推流")
fileTransferListener.onFinish()
}
catch (e: Exception)
{
fileTransferListener.onError(2, e)
}
serverDisconnect()
}
fun receiveObject(): Any?
{
var obj: Any? = null
try
{
val objectInputStream = ObjectInputStream(BufferedInputStream(socket.getInputStream()))
obj = objectInputStream.readObject()
}
catch (e: Exception)
{
Logs.wtf(TAG, "receiveObject", e)
}
clientDisconnect()
return obj
}
fun sendObject(obj: Any?): Boolean
{
if (obj == null)
{
return false
}
try
{
val objectOutputStream = ObjectOutputStream(socket.getOutputStream())
objectOutputStream.writeObject(obj)
objectOutputStream.flush()
}
catch (e: Exception)
{
Logs.wtf(TAG, "sendObject", e)
return false
}
serverDisconnect()
return true
}
fun clientDisconnect()
{
Logs.i(TAG, "clientDisconnect: 客户端终止连接")
try
{
socket.close()
}
catch (e: Exception)
{
Logs.wtf(TAG, "clientDisconnect: ", e)
}
}
fun serverDisconnect()
{
Logs.i(TAG, "serverDisconnect: 服务端终止连接")
try
{
serverSocket.close()
}
catch (e: Exception)
{
Logs.wtf(TAG, "serverDisconnect: ", e)
}
}
interface FileTransferListener
{
fun onStart()
fun onProgress(progress: Int)
fun onFinish()
fun onError(code: Int, e: Exception)
}
} | gpl-3.0 | 227651c4d4ed6fa96e424163dd490056 | 20.831683 | 110 | 0.684911 | 3.372769 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/FlatMapTransformation.kt | 3 | 4062 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions.loopToCallChain.sequence
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.*
import org.jetbrains.kotlin.idea.project.builtIns
import org.jetbrains.kotlin.idea.util.FuzzyType
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class FlatMapTransformation(
override val loop: KtForExpression,
val inputVariable: KtCallableDeclaration,
val transform: KtExpression
) : SequenceTransformation {
override val affectsIndex: Boolean
get() = true
override val presentation: String
get() = "flatMap{}"
override fun generateCode(chainedCallGenerator: ChainedCallGenerator): KtExpression {
val lambda = generateLambda(inputVariable, transform, chainedCallGenerator.reformat)
return chainedCallGenerator.generate("flatMap$0:'{}'", lambda)
}
/**
* Matches:
* for (...) {
* ...
* for (...) {
* ...
* }
* }
*/
object Matcher : TransformationMatcher {
override val indexVariableAllowed: Boolean
get() = true
override fun match(state: MatchingState): TransformationMatch.Sequence? {
val nestedLoop = state.statements.singleOrNull() as? KtForExpression ?: return null
val transform = nestedLoop.loopRange ?: return null
// check that we iterate over Iterable
val nestedSequenceType = transform.analyze(BodyResolveMode.PARTIAL).getType(transform) ?: return null
val builtIns = transform.builtIns
val iterableType = FuzzyType(builtIns.iterableType, builtIns.iterable.declaredTypeParameters)
if (iterableType.checkIsSuperTypeOf(nestedSequenceType) == null) return null
val nestedLoopBody = nestedLoop.body ?: return null
val newInputVariable = nestedLoop.loopParameter ?: return null
if (state.indexVariable != null && state.indexVariable.hasUsages(transform)) {
// if nested loop range uses index, convert to "mapIndexed {...}.flatMap { it }"
val mapIndexedTransformation =
MapTransformation(state.outerLoop, state.inputVariable, state.indexVariable, transform, mapNotNull = false)
val inputVarExpression = KtPsiFactory(nestedLoop).createExpressionByPattern(
"$0", state.inputVariable.nameAsSafeName,
reformat = state.reformat
)
val transformToUse = if (state.lazySequence) inputVarExpression.asSequence(state.reformat) else inputVarExpression
val flatMapTransformation = FlatMapTransformation(state.outerLoop, state.inputVariable, transformToUse)
val newState = state.copy(
innerLoop = nestedLoop,
statements = listOf(nestedLoopBody),
inputVariable = newInputVariable
)
return TransformationMatch.Sequence(listOf(mapIndexedTransformation, flatMapTransformation), newState)
}
val transformToUse = if (state.lazySequence) transform.asSequence(state.reformat) else transform
val transformation = FlatMapTransformation(state.outerLoop, state.inputVariable, transformToUse)
val newState = state.copy(
innerLoop = nestedLoop,
statements = listOf(nestedLoopBody),
inputVariable = newInputVariable
)
return TransformationMatch.Sequence(transformation, newState)
}
private fun KtExpression.asSequence(reformat: Boolean): KtExpression = KtPsiFactory(this).createExpressionByPattern(
"$0.asSequence()", this,
reformat = reformat
)
}
} | apache-2.0 | 97f9fe56d6831419d341dbaaded87b50 | 45.170455 | 158 | 0.660758 | 5.504065 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/highlighter/deprecated/Invalid.kt | 2 | 494 | @Deprecated<error descr="[NO_VALUE_FOR_PARAMETER] No value passed for parameter 'message'">()</error>
fun foo() {}
@Deprecated(<error descr="[CONSTANT_EXPECTED_TYPE_MISMATCH] The boolean literal does not conform to the expected type String">false</error>)
fun boo() {}
fun far() = <warning descr="[DEPRECATION] 'foo(): Unit' is deprecated. ">foo</warning>()
fun bar() = <warning descr="[DEPRECATION] 'boo(): Unit' is deprecated. ">boo</warning>()
// NO_CHECK_INFOS
// NO_CHECK_WEAK_WARNINGS
| apache-2.0 | 4ce67fa1e2b813b084dd2de4175a57f9 | 43.909091 | 140 | 0.702429 | 3.686567 | false | false | false | false |
shogo4405/HaishinKit.java | haishinkit/src/main/java/com/haishinkit/iso/AvcFormatUtils.kt | 1 | 1555 | package com.haishinkit.iso
import java.nio.ByteBuffer
object AvcFormatUtils {
val START_CODE = byteArrayOf(0, 0, 0, 1)
private const val ZERO: Byte = 0
private const val ONE: Byte = 1
private val TAG = AvcFormatUtils::class.java.simpleName
fun toNALFile(input: ByteBuffer, output: ByteBuffer) {
var length = 0
var position = -1
val offset = output.position()
val remaining = input.remaining() - 3 + offset
output.put(input)
for (i in offset until remaining) {
if (output.get(i) == ZERO && output.get(i + 1) == ZERO && output.get(i + 2) == ZERO && output.get(
i + 3
) == ONE
) {
if (0 <= position) {
output.putInt(position, length - 3)
}
position = i
length = 0
} else {
++length
}
}
output.putInt(position, length)
}
fun toByteStream(buffer: ByteBuffer, offset: Int) {
val position = buffer.position()
if (0 < offset) {
buffer.position(position + offset)
}
while (buffer.hasRemaining()) {
val index = buffer.position()
val length = buffer.int
buffer.put(index, ZERO)
buffer.put(index + 1, ZERO)
buffer.put(index + 2, ZERO)
buffer.put(index + 3, ONE)
buffer.position(buffer.position() + length)
}
buffer.position(position)
}
}
| bsd-3-clause | 57550d70393bf1d547d7c1d18d473a5b | 29.490196 | 110 | 0.509325 | 4.248634 | false | false | false | false |
GunoH/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/style/GrUnnecessarySemicolonInspection.kt | 5 | 3496 | // 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.groovy.codeInspection.style
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.plugins.groovy.GroovyBundle
import org.jetbrains.plugins.groovy.codeInspection.fixes.RemoveElementWithoutFormatterFix
import org.jetbrains.plugins.groovy.lang.lexer.TokenSets.WHITE_SPACES_OR_COMMENTS
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes.*
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock
import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrTraditionalForClause
import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameterList
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrEnumConstantList
import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement
import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.packaging.GrPackageDefinition
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.skipSet
import org.jetbrains.plugins.groovy.util.TokenSet
import org.jetbrains.plugins.groovy.util.minus
import org.jetbrains.plugins.groovy.util.plus
class GrUnnecessarySemicolonInspection : LocalInspectionTool(), CleanupLocalInspectionTool {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = object : PsiElementVisitor() {
override fun visitElement(element: PsiElement) {
if (element.node.elementType !== T_SEMI || Holder.isSemicolonNecessary(element)) return
holder.registerProblem(
element,
GroovyBundle.message("unnecessary.semicolon.description"),
Holder.fix
)
}
}
private object Holder {
val fix: LocalQuickFix = RemoveElementWithoutFormatterFix(GroovyBundle.message("unnecessary.semicolon.fix"))
private val nlSet = TokenSet(NL)
private val forwardSet = WHITE_SPACES_OR_COMMENTS + TokenSet(T_SEMI) - nlSet
private val backwardSet = WHITE_SPACES_OR_COMMENTS - nlSet
private val separators = TokenSet(NL, T_SEMI)
private val previousSet = TokenSet(T_LBRACE, T_ARROW)
fun isSemicolonNecessary(semicolon: PsiElement): Boolean {
if (semicolon.parent is GrTraditionalForClause) return true
val prevSibling = skipSet(semicolon, false, backwardSet) ?: return false
val nextSibling = skipSet(semicolon, true, forwardSet) ?: return false
val prevType = prevSibling.node.elementType
return when {
prevType in separators -> {
prevSibling.prevSibling is GrEnumConstantList
}
prevType in previousSet -> {
false
}
prevSibling is GrStatement -> {
nextSibling is GrStatement || nextSibling.nextSibling is GrClosableBlock
}
prevSibling is GrPackageDefinition || prevSibling is GrImportStatement -> {
nextSibling.node.elementType !in separators
}
prevSibling is GrParameterList && prevSibling.parent is GrClosableBlock -> {
false // beginning of a closure
}
else -> true
}
}
}
}
| apache-2.0 | b4d101674e5611c6b2e7900c80d601db | 45 | 124 | 0.76659 | 4.612137 | false | false | false | false |
yongce/AndroidLib | baseLib/src/main/java/me/ycdev/android/lib/common/net/NetworkUtils.kt | 1 | 8312 | package me.ycdev.android.lib.common.net
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.os.Build
import android.telephony.TelephonyManager
import android.text.TextUtils
import androidx.annotation.IntDef
import androidx.annotation.RequiresPermission
import androidx.annotation.VisibleForTesting
import me.ycdev.android.lib.common.utils.LibLogger
import java.io.IOException
import java.net.HttpURLConnection
import java.net.MalformedURLException
import java.net.URL
@Suppress("unused")
object NetworkUtils {
private const val TAG = "NetworkUtils"
const val WEAR_OS_COMPANION_PROXY = 16
const val NETWORK_TYPE_NONE = -1
const val NETWORK_TYPE_WIFI = 1
const val NETWORK_TYPE_MOBILE = 2
const val NETWORK_TYPE_2G = 10
const val NETWORK_TYPE_3G = 11
const val NETWORK_TYPE_4G = 12
const val NETWORK_TYPE_5G = 13
const val NETWORK_TYPE_COMPANION_PROXY = 20
@Retention(AnnotationRetention.SOURCE)
@IntDef(
NETWORK_TYPE_NONE,
NETWORK_TYPE_WIFI,
NETWORK_TYPE_MOBILE,
NETWORK_TYPE_2G,
NETWORK_TYPE_3G,
NETWORK_TYPE_4G,
NETWORK_TYPE_5G,
NETWORK_TYPE_COMPANION_PROXY
)
annotation class NetworkType
@RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
fun dumpActiveNetworkInfo(cxt: Context): String {
val capabilities = getActiveNetworkCapabilities(cxt) ?: return "No active network"
return capabilities.toString()
}
@RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
fun getActiveNetwork(cxt: Context): Network? {
val cm = cxt.getSystemService(ConnectivityManager::class.java)
if (cm == null) {
LibLogger.w(TAG, "failed to get connectivity service")
return null
}
try {
return cm.activeNetwork
} catch (e: Exception) {
LibLogger.w(TAG, "failed to get active network", e)
}
return null
}
@RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
fun getActiveNetworkCapabilities(cxt: Context): NetworkCapabilities? {
val cm = cxt.getSystemService(ConnectivityManager::class.java)
if (cm == null) {
LibLogger.w(TAG, "failed to get connectivity service")
return null
}
try {
val network = cm.activeNetwork ?: return null
return cm.getNetworkCapabilities(network)
} catch (e: Exception) {
LibLogger.w(TAG, "failed to get active network", e)
}
return null
}
/**
* @return One of the values [NETWORK_TYPE_NONE],
* [NETWORK_TYPE_WIFI] or [NETWORK_TYPE_MOBILE]
*/
@RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
@NetworkType
fun getNetworkType(cxt: Context): Int {
val capabilities = getActiveNetworkCapabilities(cxt) ?: return NETWORK_TYPE_NONE
return getNetworkType(capabilities)
}
@NetworkType
@VisibleForTesting
internal fun getNetworkType(capabilities: NetworkCapabilities): Int {
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)
) {
return NETWORK_TYPE_WIFI
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
return NETWORK_TYPE_MOBILE
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH)) {
// Wear OS
return NETWORK_TYPE_COMPANION_PROXY
}
return NETWORK_TYPE_NONE // Take unknown networks as none
}
/**
* @return One of values [NETWORK_TYPE_2G], [NETWORK_TYPE_3G],
* [NETWORK_TYPE_4G], [NETWORK_TYPE_5G] or [NETWORK_TYPE_NONE]
*/
@NetworkType
@RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
fun getMobileNetworkType(cxt: Context): Int {
// #1 Code from android-5.1.1_r4:
// frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java
// in NetworkControllerImpl#mapIconSets()
// #2 Code from master (Android R):
// frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java
// in MobileSignalController#mapIconSets()
val tm = cxt.getSystemService(TelephonyManager::class.java)
if (tm == null) {
LibLogger.w(TAG, "failed to get telephony service")
return NETWORK_TYPE_NONE
}
val tmType: Int
try {
@Suppress("DEPRECATION")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
tmType = tm.dataNetworkType
} else {
tmType = tm.networkType
}
} catch (e: Exception) {
LibLogger.w(TAG, "failed to get telephony network type", e)
return NETWORK_TYPE_NONE
}
return when (tmType) {
TelephonyManager.NETWORK_TYPE_UNKNOWN -> NETWORK_TYPE_NONE
TelephonyManager.NETWORK_TYPE_LTE -> NETWORK_TYPE_4G
TelephonyManager.NETWORK_TYPE_NR -> NETWORK_TYPE_5G
TelephonyManager.NETWORK_TYPE_EVDO_0,
TelephonyManager.NETWORK_TYPE_EVDO_A,
TelephonyManager.NETWORK_TYPE_EVDO_B,
TelephonyManager.NETWORK_TYPE_EHRPD,
TelephonyManager.NETWORK_TYPE_TD_SCDMA,
TelephonyManager.NETWORK_TYPE_UMTS -> NETWORK_TYPE_3G
TelephonyManager.NETWORK_TYPE_HSDPA,
TelephonyManager.NETWORK_TYPE_HSUPA,
TelephonyManager.NETWORK_TYPE_HSPA,
TelephonyManager.NETWORK_TYPE_HSPAP -> NETWORK_TYPE_3G // H
TelephonyManager.NETWORK_TYPE_GPRS,
TelephonyManager.NETWORK_TYPE_EDGE,
TelephonyManager.NETWORK_TYPE_CDMA,
TelephonyManager.NETWORK_TYPE_GSM,
TelephonyManager.NETWORK_TYPE_1xRTT -> NETWORK_TYPE_2G
else -> NETWORK_TYPE_2G
}
}
/**
* @return One of values [NETWORK_TYPE_WIFI], [NETWORK_TYPE_2G],
* [NETWORK_TYPE_3G], [NETWORK_TYPE_4G], [NETWORK_TYPE_5G] or [NETWORK_TYPE_NONE]
*/
@RequiresPermission(
allOf = [
android.Manifest.permission.ACCESS_NETWORK_STATE,
android.Manifest.permission.READ_PHONE_STATE
]
)
@NetworkType
fun getMixedNetworkType(cxt: Context): Int {
var type = getNetworkType(cxt)
if (type == NETWORK_TYPE_MOBILE) {
type = getMobileNetworkType(cxt)
}
return type
}
/**
* Check if there is an active network connection
*/
@RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
fun isNetworkAvailable(cxt: Context): Boolean {
val capabilities = getActiveNetworkCapabilities(cxt) ?: return false
return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
}
/**
* Check if the current active network may cause monetary cost
* @see ConnectivityManager.isActiveNetworkMetered
*/
@RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
fun isActiveNetworkMetered(cxt: Context): Boolean {
val cm = cxt.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
if (cm == null) {
LibLogger.w(TAG, "failed to get connectivity service")
return true
}
return cm.isActiveNetworkMetered
}
/**
* Open a HTTP connection to the specified URL. Use proxy automatically if needed.
*/
@Throws(IOException::class)
fun openHttpURLConnection(url: String): HttpURLConnection {
// check if url can be parsed successfully to prevent host == null crash
// https://code.google.com/p/android/issues/detail?id=16895
val linkUrl = URL(url)
val host = linkUrl.host
if (TextUtils.isEmpty(host)) {
throw MalformedURLException("Malformed URL: $url")
}
// TODO if needed to support proxy
return linkUrl.openConnection() as HttpURLConnection
}
}
| apache-2.0 | 6b9aefaa13f0afc21e29b4c9b60feb3d | 35.296943 | 117 | 0.653152 | 4.400212 | false | false | false | false |
pdvrieze/kotlinsql | util/src/main/kotlin/io/github/pdvrieze/jdbc/recorder/util.kt | 1 | 2080 | /*
* Copyright (c) 2020.
*
* This file is part of kotlinsql.
*
* This file is licenced to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You should have received a copy of the license with the source distribution.
* Alternatively, 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.github.pdvrieze.jdbc.recorder
internal fun Any?.stringify(): String {
return when (this) {
null -> "null"
is ByteArray -> joinToString(prefix = "[", postfix = "]")
is ShortArray -> joinToString(prefix = "[", postfix = "]")
is CharArray -> joinToString(prefix = "[", postfix = "]")
is IntArray -> joinToString(prefix = "[", postfix = "]")
is LongArray -> joinToString(prefix = "[", postfix = "]")
is FloatArray -> joinToString(prefix = "[", postfix = "]")
is DoubleArray -> joinToString(prefix = "[", postfix = "]")
is Array<*> -> joinToString<Any?>(prefix = "[", postfix = "]") { it.stringify() }
is Iterable<*> -> joinToString<Any?>(prefix = "[", postfix = "]") { it.stringify() }
is CharSequence -> "\"${escape()}\""
else -> toString()
}
}
internal fun CharSequence.escape(): String = buildString {
for (ch in this@escape) {
when (ch) {
'\\' -> append("\\\\")
'"' -> append("\\\"")
'\'' -> append("\\'")
else -> append(ch)
}
}
}
private fun Array<String>.dataArray(vararg data: Pair<String, Any?>): Array<Any?> {
return Array(size) { idx ->
val colName = get(idx)
data.firstOrNull { it.first == colName }?.second
}
}
| apache-2.0 | 8fc369d7bca66ececfd4f3adbeacb8e1 | 34.862069 | 98 | 0.597596 | 4.369748 | false | false | false | false |
airbnb/lottie-android | sample/src/main/kotlin/com/airbnb/lottie/samples/PreviewItemView.kt | 1 | 1146 | package com.airbnb.lottie.samples
import android.content.Context
import android.util.AttributeSet
import android.widget.LinearLayout
import androidx.annotation.DrawableRes
import com.airbnb.epoxy.CallbackProp
import com.airbnb.epoxy.ModelProp
import com.airbnb.epoxy.ModelView
import com.airbnb.epoxy.TextProp
import com.airbnb.lottie.samples.databinding.ListItemPreviewBinding
import com.airbnb.lottie.samples.utils.viewBinding
@ModelView(autoLayout = ModelView.Size.MATCH_WIDTH_WRAP_HEIGHT)
class PreviewItemView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
private val binding: ListItemPreviewBinding by viewBinding()
init {
orientation = VERTICAL
}
@TextProp
fun setTitle(title: CharSequence) {
binding.titleView.text = title
}
@ModelProp
fun setIcon(@DrawableRes icon: Int) {
binding.iconView.setImageResource(icon)
}
@CallbackProp
fun setClickListener(clickListener: OnClickListener?) {
binding.container.setOnClickListener(clickListener)
}
} | apache-2.0 | 6e9a5b26c586b9da8a904a5df8467a44 | 27.675 | 67 | 0.759162 | 4.476563 | false | false | false | false |
rlac/tealeaf | library/src/main/kotlin/au/id/rlac/tealeaf/properties/ViewDelegates.kt | 1 | 2361 | package au.id.rlac.tealeaf.properties
import android.app.Activity
import android.view.View
import android.view.ViewGroup
import kotlin.properties.ReadOnlyProperty
/**
* Delegate property for views on Activity classes.
*
* class MyActivity : Activity() {
* val myTextView: TextView by viewById(R.id.my_text_view)
* }
*
* @param id The id of the view to find.
* @return a delegate property that finds the view in the Activity by id when first accessed.
*/
public fun Activity.viewById<T : View>(id: Int): ReadOnlyProperty<Any, T> = ViewDelegates.ViewVal(id)
/**
* Delegate property for views with the [ViewHolder] trait.
*
* class MyViewHolder(val view: View) : ViewHolder {
* val myTextView: TextView by viewById(R.id.my_text_view)
* }
*
* @param id The id of the view to find.
* @return a delegate property that finds a child of the view property by id when first accessed.
*/
public fun ViewDelegates.ViewHolder.viewById<T : View>(id: Int): ReadOnlyProperty<Any, T> = ViewDelegates.ViewVal(id)
/**
* Delegate property for views within a ViewGroup.
*
* class MyCustomViewGroup(c: Context, a: AttributeSet?) : FrameLayout(c, a, 0) {
* val myTextView: TextView by viewById(R.id.my_text_view)
* }
*
* @param id The id of the view to find.
* @return a delegate property that finds a view under the ViewGroup by id when first accessed
*/
public fun ViewGroup.viewById<T : View>(id: Int): ReadOnlyProperty<Any, T> = ViewDelegates.ViewVal(id)
public object ViewDelegates {
public trait ViewHolder {
val view: View
}
public fun viewById<T : View>(v: View, id: Int): ReadOnlyProperty<Any, T> = ViewVal(id, v)
internal class ViewVal<T : View>(val id: Int, val v: View? = null) : ReadOnlyProperty<Any, T> {
var foundView: T? = null
override fun get(thisRef: Any, desc: PropertyMetadata): T {
[suppress("UNCHECKED_CAST")]
if (foundView == null) {
foundView =
if (v != null) v.findViewById(id) as T
else when (thisRef) {
is Activity -> thisRef.findViewById(id)
is ViewHolder -> thisRef.view.findViewById(id)
is ViewGroup -> thisRef.findViewById(id)
else -> throw UnsupportedClassException("Class containing view delegate is not a supported type.")
} as T
}
return foundView!!
}
}
}
| apache-2.0 | 5db647c673750e46d6afc9471010a795 | 32.728571 | 117 | 0.677255 | 3.74168 | false | false | false | false |
google/android-fhir | datacapture/src/main/java/com/google/android/fhir/datacapture/views/MarginItemDecoration.kt | 1 | 1357 | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.fhir.datacapture.views
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView
/**
* ItemDecoration that applies a specified margin to the items. Use this instead of manually adding
* a margin to the item's layout.
* @param margin Int value for the desired margin used as item offset
*/
class MarginItemDecoration(private val margin: Int) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(
outRect: Rect,
view: View,
parent: RecyclerView,
state: RecyclerView.State
) {
outRect.apply {
if (parent.getChildAdapterPosition(view) == 0) {
top = margin
}
left = margin
right = margin
bottom = margin
}
}
}
| apache-2.0 | 54955b578d694757c41f90ae28df8931 | 29.840909 | 99 | 0.717023 | 4.294304 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/inspections/trailingCommaOn/ParameterList.kt | 26 | 5738 | class A1 {
val x: String
val y: String
constructor(
x: String,
y: String,
) {
this.x = x
this.y = y
}
}
class B1 {
val x: String
val y: String
constructor(
x: String,
y: String
) {
this.x = x
this.y = y
}
}
class C1 {
val x: String
val y: String
constructor(
x: String,
y: String,) {
this.x = x
this.y = y
}
}
class D1 {
val x: String
val y: String
constructor(
x: String,
y: String
,) {
this.x = x
this.y = y
}
}
class A2 {
val x: String
val y: String
val z: String
constructor(
x: String,
y: String,
z: String,
) {
this.x = x
this.y = y
this.z = z
}
}
class B2 {
val x: String
val y: String
val z: String
constructor(
x: String,
y: String,
z: String
) {
this.x = x
this.y = y
this.z = z
}
}
class C2 {
val x: String
val y: String
val z: String
constructor(
x: String,
y: String,
z: String,) {
this.x = x
this.y = y
this.z = z
}
}
class D2 {
val x: String
val y: String
val z: String
constructor(
x: String,
y: String,
z: String
,) {
this.x = x
this.y = y
this.z = z
}
}
class A3 {
val x: String
constructor(x: String,) {
this.x = x
}
}
class B3 {
val x: String
constructor(x: String) {
this.x = x
}
}
class C3 {
val x: String
constructor(
x: String,) {
this.x = x
}
}
class D3 {
val x: String
constructor(
x: String
,) {
this.x = x
}
}
class E1 {
val x: String
val y: String
val z: String
constructor(
x: String,
y: String, z: String,) {
this.x = x
this.y = y
this.z = z
}
}
class E2 {
val x: String
val y: String
val z: String
constructor(
x: String,
y: String, z: String) {
this.x = x
this.y = y
this.z = z
}
}
class A1(
val x: String,
y: String,
)
class B1(
val x: String,
val y: String
)
class C1(
val x: String,
val y: String,)
class D1(
val x: String,
val y: String
,)
class A2(
val x: String,
val y: String,
val z: String,
)
class B2(
val x: String,
val y: String,
val z: String
)
class C2(
val x: String,
val y: String,
val z: String,)
class D2(
val x: String,
val y: String,
val z: String
,)
class A3(
val x: String,
)
class B3(
val x: String
)
class C3(
val x: String,)
class D3(
val x: String
,)
class A4(
val x: String ,
val y: String,
val z: String ,
)
class B4(
val x: String,
val y: String,
val z: String
)
class C4(
val x: String,
val y: String,
val z: String ,)
class D4(
val x: String,
val y: String,
val z: String
, )
class E1(
val x: String, val y: String,
val z: String
, )
class E2(
val x: String, val y: String, val z: String
)
class C(
z: String, val v: Int, val x: Int =
42, val y: Int =
42
)
val foo1: (Int, Int) -> Int = fun(
x,
y,
): Int = 42
val foo2: (Int, Int) -> Int = fun(
x,
y
): Int {
return x + y
}
val foo3: (Int, Int) -> Int = fun(
x, y,
): Int {
return x + y
}
val foo4: (Int) -> Int = fun(
x,
): Int = 42
val foo5: (Int) -> Int = fun(
x
): Int = 42
val foo6: (Int) -> Int = fun(x,): Int = 42
val foo7: (Int) -> Int = fun(x): Int = 42
val foo8: (Int, Int, Int) -> Int = fun (x, y: Int, z,): Int {
return x + y
}
val foo9: (Int, Int, Int) -> Int = fun (
x,
y: Int,
z,
): Int = 42
val foo10: (Int, Int, Int) -> Int = fun (
x,
y: Int,
z: Int
): Int = 43
val foo10 = fun (
x: Int,
y: Int,
z: Int
): Int = 43
val foo11 = fun (
x: Int,
y: Int,
z: Int,
): Int = 43
val foo12 = fun (
x: Int, y: Int, z: Int,
): Int = 43
val foo13 = fun (x: Int, y: Int, z: Int,
): Int = 43
val foo14 = fun (x: Int, y: Int, z: Int
,): Int = 43
fun a1(
x: String,
y: String,
) = Unit
fun b1(
x: String,
y: String
) = Unit
fun c1(
x: String,
y: String,) = Unit
fun d1(
x: String,
y: String
,) = Unit
fun a2(
x: String,
y: String,
z: String,
) = Unit
fun b2(
x: String,
y: String,
z: String
) = Unit
fun c2(
x: String,
y: String,
z: String,) = Unit
fun d2(
x: String,
y: String,
z: String
,) = Unit
fun a3(
x: String,
) = Unit
fun b3(
x: String
) = Unit
fun c3(
x: String,) = Unit
fun d3(
x: String
,) = Unit
fun a4(
x: String
,
y: String,
z: String ,
) = Unit
fun b4(
x: String,
y: String,
z: String
) = Unit
fun c4(x: String,
y: String,
z: String ,) = Unit
fun d4(
x: String,
y: String,
z: String
, ) = Unit
fun foo(
x: Int =
42
) {
}
class C(
val x: Int =
42
)
class G(
val x: String, val y: String
= "", /* */ val z: String
)
class G(
val x: String, val y: String
= "" /* */, /* */ val z: String
)
class H(
val x: String, /*
*/ val y: String,
val z: String ,)
class J(
val x: String, val y: String , val z: String /*
*/
, )
class K(
val x: String, val y: String,
val z: String
, )
class L(
val x: String, val y: String, val z: String // adwd
)
| apache-2.0 | f6ca2a1fd5057719f39cfcf52735ed8b | 11.528384 | 61 | 0.4519 | 2.843409 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveTopLevelDeclarations/misc/singletonsAndStatics/before/source/Foo.kt | 13 | 550 | package source
import library.*
class <caret>Foo {
val jv1 = JavaClass.foo()
val jv2 = JavaClass().foo()
val jv3 = JavaClass.Inner.foo()
val jv4 = JavaClass.Inner().foo()
val kt1 = KtClass.foo()
val kt2 = KtObject.foo()
val kt3 = KtClass.Inner.foo()
val kt4 = KtObject.Inner.foo()
val kt5 = KtClass.Companion.foo()
val kt6 = KtClass.Companion
val kt7 = KtClass
val kt8 = Bar
val kt9 = Bar.Companion
val kt10 = Bar.Companion.c
}
class Bar {
companion object {
val c : Int
}
} | apache-2.0 | cbad3e24551f53bf0a885b426f6b8423 | 19.407407 | 37 | 0.607273 | 3.313253 | false | false | false | false |
dahlstrom-g/intellij-community | python/src/com/jetbrains/python/packaging/toolwindow/uiComponents.kt | 6 | 9095 | // 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.jetbrains.python.packaging.toolwindow
import com.intellij.icons.AllIcons
import com.intellij.openapi.util.NlsSafe
import com.intellij.ui.DoubleClickListener
import com.intellij.ui.SideBorder
import com.intellij.ui.table.JBTable
import com.intellij.util.ui.ListTableModel
import com.intellij.util.ui.UIUtil
import com.jetbrains.python.PyBundle.message
import com.jetbrains.python.packaging.repository.PyPackageRepository
import java.awt.BorderLayout
import java.awt.Component
import java.awt.Dimension
import java.awt.event.ActionEvent
import java.awt.event.KeyEvent
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.*
import javax.swing.border.EmptyBorder
import javax.swing.table.DefaultTableCellRenderer
import javax.swing.table.TableCellRenderer
internal class PyPackagesTable<T : DisplayablePackage>(model: ListTableModel<T>, service: PyPackagingToolWindowService, tablesView: PyPackagingTablesView) : JBTable(model) {
private var lastSelectedRow = -1
init {
setShowGrid(false)
setSelectionMode(ListSelectionModel.SINGLE_SELECTION)
val column = columnModel.getColumn(1)
column.maxWidth = 100
column.resizable = false
border = SideBorder(UIUtil.getBoundsColor(), SideBorder.BOTTOM)
rowHeight = 20
initCrossNavigation(service, tablesView)
selectionModel.addListSelectionListener {
if (selectedRow != -1 && selectedRow != lastSelectedRow) {
lastSelectedRow = selectedRow
tablesView.requestSelection(this)
val pkg = model.items[selectedRow]
if (pkg !is ExpandResultNode) service.packageSelected(pkg)
}
}
object : DoubleClickListener() {
override fun onDoubleClick(event: MouseEvent): Boolean {
val pkg = model.items[selectedRow]
if (pkg is ExpandResultNode) loadMoreItems(service, pkg)
return true
}
}.installOn(this)
}
private fun initCrossNavigation(service: PyPackagingToolWindowService, tablesView: PyPackagingTablesView) {
getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), ENTER_ACTION)
actionMap.put(ENTER_ACTION, object : AbstractAction() {
override fun actionPerformed(e: ActionEvent?) {
if (selectedRow == -1) return
val index = selectedRow
val selectedItem = items[selectedRow]
if (selectedItem is ExpandResultNode) {
loadMoreItems(service, selectedItem)
}
setRowSelectionInterval(index, index)
}
})
val nextRowAction = actionMap[NEXT_ROW_ACTION]
actionMap.put(NEXT_ROW_ACTION, object : AbstractAction() {
override fun actionPerformed(e: ActionEvent?) {
if (selectedRow == -1) return
if (selectedRow + 1 == items.size) {
tablesView.selectNextFrom(this@PyPackagesTable)
}
else {
nextRowAction.actionPerformed(e)
}
}
})
val prevRowAction = actionMap[PREVIOUS_ROW_ACTION]
actionMap.put(PREVIOUS_ROW_ACTION, object : AbstractAction() {
override fun actionPerformed(e: ActionEvent?) {
if (selectedRow == -1) return
if (selectedRow == 0) {
tablesView.selectPreviousOf(this@PyPackagesTable)
}
else {
prevRowAction.actionPerformed(e)
}
}
})
}
@Suppress("UNCHECKED_CAST")
private fun loadMoreItems(service: PyPackagingToolWindowService, node: ExpandResultNode) {
val result = service.getMoreResultsForRepo(node.repository, items.size - 1)
items = items.dropLast(1) + (result.packages as List<T>)
if (result.moreItems > 0) {
node.more = result.moreItems
items = items + listOf(node) as List<T>
}
[email protected]()
[email protected]()
}
override fun getCellRenderer(row: Int, column: Int): TableCellRenderer {
return PyPaginationAwareRenderer()
}
override fun clearSelection() {
lastSelectedRow = -1
super.clearSelection()
}
internal fun addRows(rows: List<T>) = listModel.addRows(rows)
internal fun removeRow(index: Int) = listModel.removeRow(index)
internal fun insertRow(index: Int, pkg: T) = listModel.insertRow(index, pkg)
@Suppress("UNCHECKED_CAST")
private val listModel: ListTableModel<T>
get() = model as ListTableModel<T>
var items: List<T>
get() = listModel.items
set(value) { listModel.items = value.toMutableList() }
companion object {
private const val NEXT_ROW_ACTION = "selectNextRow"
private const val PREVIOUS_ROW_ACTION = "selectPreviousRow"
private const val ENTER_ACTION = "ENTER"
}
}
internal class PyPackagesTableModel<T : DisplayablePackage> : ListTableModel<T>() {
override fun isCellEditable(rowIndex: Int, columnIndex: Int): Boolean = false
override fun getColumnCount(): Int = 2
override fun getColumnName(column: Int): String = column.toString()
override fun getColumnClass(columnIndex: Int): Class<*> {
if (columnIndex == 0) return String::class.java
if (columnIndex == 1) return Number::class.java
return Any::class.java
}
override fun getValueAt(rowIndex: Int, columnIndex: Int): Any? {
val item = items[rowIndex]
if (columnIndex == 0) {
if (item is ExpandResultNode) {
return message("python.toolwindow.packages.load.more", item.more)
}
return item.name
}
if (columnIndex == 1 && item is InstalledPackage) return item.instance.version
return null
}
}
fun boxPanel(init: JPanel.() -> Unit) = object : JPanel() {
init {
layout = BoxLayout(this, BoxLayout.X_AXIS)
alignmentX = LEFT_ALIGNMENT
init()
}
}
fun borderPanel(init: JPanel.() -> Unit) = object : JPanel() {
init {
layout = BorderLayout(0, 0)
init()
}
}
fun headerPanel(label: JLabel, component: JComponent?) = object : JPanel() {
init {
background = UIUtil.getControlColor()
layout = BorderLayout()
border = BorderFactory.createCompoundBorder(SideBorder(UIUtil.getBoundsColor(), SideBorder.BOTTOM), EmptyBorder(0, 5, 0, 5))
preferredSize = Dimension(preferredSize.width, 25)
minimumSize = Dimension(minimumSize.width, 25)
maximumSize = Dimension(maximumSize.width, 25)
add(label, BorderLayout.WEST)
if (component != null) {
addMouseListener(object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent?) {
component.isVisible = !component.isVisible
label.icon = if (component.isVisible) AllIcons.General.ArrowDown else AllIcons.General.ArrowRight
}
})
}
}
}
private class PyPaginationAwareRenderer : DefaultTableCellRenderer() {
private val emptyBorder = BorderFactory.createEmptyBorder()
private val expanderMarker = message("python.toolwindow.packages.load.more.start")
override fun getTableCellRendererComponent(table: JTable?,
value: Any?,
isSelected: Boolean,
hasFocus: Boolean,
row: Int,
column: Int): Component {
val component = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column)
(component as DefaultTableCellRenderer).border = emptyBorder
if (value is String && value.startsWith(expanderMarker)) {
return component.apply {
foreground = UIUtil.getContextHelpForeground()
}
}
return component
}
}
internal class PyPackagingTableGroup<T: DisplayablePackage>(val repository: PyPackageRepository, val table: PyPackagesTable<T>) {
@NlsSafe val name: String = repository.name!!
val repoUrl = repository.repositoryUrl ?: ""
private var expanded = false
private val label = JLabel(name).apply { icon = AllIcons.General.ArrowDown }
private val header: JPanel = headerPanel(label, table)
internal var itemsCount: Int? = null
internal var items: List<T>
get() = table.items
set(value) {
table.items = value
}
fun collapse() {
expanded = false
table.isVisible = false
label.icon = if (table.isVisible) AllIcons.General.ArrowDown else AllIcons.General.ArrowRight
}
fun expand() {
expanded = true
table.isVisible = true
label.icon = if (table.isVisible) AllIcons.General.ArrowDown else AllIcons.General.ArrowRight
}
fun updateHeaderText(newItemCount: Int?) {
itemsCount = newItemCount
label.text = if (itemsCount == null) name else message("python.toolwindow.packages.custom.repo.searched", name, itemsCount)
}
fun addTo(panel: JPanel) {
panel.add(header)
panel.add(table)
}
fun replace(row: Int, pkg: T) {
table.removeRow(row)
table.insertRow(row, pkg)
}
fun removeFrom(panel: JPanel) {
panel.remove(header)
panel.remove(table)
}
fun repaint() {
table.invalidate()
table.repaint()
}
} | apache-2.0 | 1f8cded6401010a3e655f03c87a9a47a | 32.318681 | 173 | 0.686971 | 4.364203 | false | false | false | false |
cdietze/klay | klay-jvm/src/main/kotlin/klay/jvm/GLFWInput.kt | 1 | 13453 | package klay.jvm
import euklid.f.Point
import klay.core.Key
import klay.core.Keyboard.TextType
import klay.core.Mouse.ButtonEvent
import org.lwjgl.BufferUtils
import org.lwjgl.glfw.*
import org.lwjgl.glfw.GLFW.*
import react.RFuture
import javax.swing.JOptionPane
class GLFWInput(override val plat: LWJGLPlatform, private val window: Long) : JavaInput(plat) {
private var lastMouseX = -1f
private var lastMouseY = -1f
// we have to keep strong references to GLFW callbacks
private val charCallback = object : GLFWCharCallback() {
override fun invoke(window: Long, codepoint: Int) {
emitKeyTyped(System.currentTimeMillis().toDouble(), codepoint.toChar())
}
}
private val keyCallback = object : GLFWKeyCallback() {
override fun invoke(window: Long, keyCode: Int, scancode: Int, action: Int, mods: Int) {
val time = System.currentTimeMillis().toDouble()
val key = translateKey(keyCode)
val pressed = action == GLFW_PRESS || action == GLFW_REPEAT
if (key != null)
emitKeyPress(time, key, pressed, toModifierFlags(mods))
else
plat.log().warn("Unknown keyCode:" + keyCode)
}
}
private val mouseBtnCallback = object : GLFWMouseButtonCallback() {
override fun invoke(handle: Long, btnIdx: Int, action: Int, mods: Int) {
val time = System.currentTimeMillis().toDouble()
val m = queryCursorPosition()
val btn = getButton(btnIdx) ?: return
emitMouseButton(time, m.x, m.y, btn, action == GLFW_PRESS, toModifierFlags(mods))
}
}
private val cursorPosCallback = object : GLFWCursorPosCallback() {
override fun invoke(handle: Long, xpos: Double, ypos: Double) {
val time = System.currentTimeMillis().toDouble()
val x = xpos.toFloat()
val y = ypos.toFloat()
if (lastMouseX == -1f) {
lastMouseX = x
lastMouseY = y
}
val dx = x - lastMouseX
val dy = y - lastMouseY
emitMouseMotion(time, x, y, dx, dy, pollModifierFlags())
lastMouseX = x
lastMouseY = y
}
}
private val scrollCallback = object : GLFWScrollCallback() {
override fun invoke(handle: Long, xoffset: Double, yoffset: Double) {
val m = queryCursorPosition()
val time = System.currentTimeMillis().toDouble()
//TODO: is it correct that just simply sets the flag as 0?
if (GLFW_CURSOR_DISABLED == glfwGetInputMode(window, GLFW_CURSOR))
emitMouseMotion(time, m.x, m.y, xoffset.toFloat(), -yoffset.toFloat(), 0)
else
emitMouseWheel(time, m.x, m.y, if (yoffset > 0) -1 else 1, 0)
}
}
init {
glfwSetCharCallback(window, charCallback)
glfwSetKeyCallback(window, keyCallback)
glfwSetMouseButtonCallback(window, mouseBtnCallback)
glfwSetCursorPosCallback(window, cursorPosCallback)
glfwSetScrollCallback(window, scrollCallback)
}
override fun update() {
glfwPollEvents()
super.update()
}
internal fun shutdown() {
charCallback.close()
keyCallback.close()
mouseBtnCallback.close()
cursorPosCallback.close()
scrollCallback.close()
}
override fun getText(textType: TextType, label: String, initVal: String): RFuture<String> {
if (plat.needsHeadless()) throw UnsupportedOperationException(NO_UI_ERROR)
val result = JOptionPane.showInputDialog(null, label, "", JOptionPane.QUESTION_MESSAGE, null, null, initVal)
return RFuture.success(result as String)
}
override fun sysDialog(title: String, text: String,
ok: String, cancel: String?): RFuture<Boolean> {
if (plat.needsHeadless()) throw UnsupportedOperationException(NO_UI_ERROR)
val optType = JOptionPane.OK_CANCEL_OPTION
val msgType = if (cancel == null) JOptionPane.INFORMATION_MESSAGE else JOptionPane.QUESTION_MESSAGE
val options = if (cancel == null) arrayOf<Any>(ok) else arrayOf<Any>(ok, cancel)
val defOption = cancel ?: ok
val result = JOptionPane.showOptionDialog(null, text, title, optType, msgType, null, options, defOption)
return RFuture.success(result == 0)
}
override val hasMouseLock: Boolean = true
override var isMouseLocked: Boolean
get() = glfwGetInputMode(window, GLFW_CURSOR) == GLFW_CURSOR_DISABLED
set(locked) = glfwSetInputMode(window, GLFW_CURSOR, if (locked) GLFW_CURSOR_DISABLED else GLFW_CURSOR_NORMAL)
private val xpos = BufferUtils.createByteBuffer(8).asDoubleBuffer()
private val ypos = BufferUtils.createByteBuffer(8).asDoubleBuffer()
private val cpos = Point()
private fun queryCursorPosition(): Point {
xpos.rewind()
ypos.rewind()
glfwGetCursorPos(window, xpos, ypos)
cpos.set(xpos.get().toFloat(), ypos.get().toFloat())
return cpos
}
/** Returns the current state of the modifier keys. Note: the code assumes the current state of
* the modifier keys is "correct" for all events that have arrived since the last call to
* update; since that happens pretty frequently, 60fps, that's probably good enough. */
private fun pollModifierFlags(): Int {
return modifierFlags(
isKeyDown(GLFW_KEY_LEFT_ALT) || isKeyDown(GLFW_KEY_LEFT_ALT),
isKeyDown(GLFW_KEY_LEFT_CONTROL) || isKeyDown(GLFW_KEY_RIGHT_CONTROL),
isKeyDown(GLFW_KEY_LEFT_SUPER) || isKeyDown(GLFW_KEY_RIGHT_SUPER),
isKeyDown(GLFW_KEY_LEFT_SHIFT) || isKeyDown(GLFW_KEY_RIGHT_SHIFT))
}
/** Converts GLFW modifier key flags into Klay modifier key flags. */
private fun toModifierFlags(mods: Int): Int {
return modifierFlags(mods and GLFW_MOD_ALT != 0,
mods and GLFW_MOD_CONTROL != 0,
mods and GLFW_MOD_SUPER != 0,
mods and GLFW_MOD_SHIFT != 0)
}
private fun isKeyDown(key: Int): Boolean {
return glfwGetKey(window, key) == GLFW_PRESS
}
private fun translateKey(keyCode: Int): Key? {
when (keyCode) {
GLFW_KEY_ESCAPE -> return Key.ESCAPE
GLFW_KEY_1 -> return Key.K1
GLFW_KEY_2 -> return Key.K2
GLFW_KEY_3 -> return Key.K3
GLFW_KEY_4 -> return Key.K4
GLFW_KEY_5 -> return Key.K5
GLFW_KEY_6 -> return Key.K6
GLFW_KEY_7 -> return Key.K7
GLFW_KEY_8 -> return Key.K8
GLFW_KEY_9 -> return Key.K9
GLFW_KEY_0 -> return Key.K0
GLFW_KEY_MINUS -> return Key.MINUS
GLFW_KEY_EQUAL -> return Key.EQUALS
GLFW_KEY_BACKSPACE -> return Key.BACK
GLFW_KEY_TAB -> return Key.TAB
GLFW_KEY_Q -> return Key.Q
GLFW_KEY_W -> return Key.W
GLFW_KEY_E -> return Key.E
GLFW_KEY_R -> return Key.R
GLFW_KEY_T -> return Key.T
GLFW_KEY_Y -> return Key.Y
GLFW_KEY_U -> return Key.U
GLFW_KEY_I -> return Key.I
GLFW_KEY_O -> return Key.O
GLFW_KEY_P -> return Key.P
GLFW_KEY_LEFT_BRACKET -> return Key.LEFT_BRACKET
GLFW_KEY_RIGHT_BRACKET -> return Key.RIGHT_BRACKET
GLFW_KEY_ENTER -> return Key.ENTER
GLFW_KEY_RIGHT_CONTROL -> return Key.CONTROL
GLFW_KEY_LEFT_CONTROL -> return Key.CONTROL
GLFW_KEY_A -> return Key.A
GLFW_KEY_S -> return Key.S
GLFW_KEY_D -> return Key.D
GLFW_KEY_F -> return Key.F
GLFW_KEY_G -> return Key.G
GLFW_KEY_H -> return Key.H
GLFW_KEY_J -> return Key.J
GLFW_KEY_K -> return Key.K
GLFW_KEY_L -> return Key.L
GLFW_KEY_SEMICOLON -> return Key.SEMICOLON
GLFW_KEY_APOSTROPHE -> return Key.QUOTE
GLFW_KEY_GRAVE_ACCENT -> return Key.BACKQUOTE
GLFW_KEY_LEFT_SHIFT -> return Key.SHIFT // Klay doesn't know left v. right
GLFW_KEY_BACKSLASH -> return Key.BACKSLASH
GLFW_KEY_Z -> return Key.Z
GLFW_KEY_X -> return Key.X
GLFW_KEY_C -> return Key.C
GLFW_KEY_V -> return Key.V
GLFW_KEY_B -> return Key.B
GLFW_KEY_N -> return Key.N
GLFW_KEY_M -> return Key.M
GLFW_KEY_COMMA -> return Key.COMMA
GLFW_KEY_PERIOD -> return Key.PERIOD
GLFW_KEY_SLASH -> return Key.SLASH
GLFW_KEY_RIGHT_SHIFT -> return Key.SHIFT // Klay doesn't know left v. right
GLFW_KEY_KP_MULTIPLY -> return Key.MULTIPLY
GLFW_KEY_SPACE -> return Key.SPACE
GLFW_KEY_CAPS_LOCK -> return Key.CAPS_LOCK
GLFW_KEY_F1 -> return Key.F1
GLFW_KEY_F2 -> return Key.F2
GLFW_KEY_F3 -> return Key.F3
GLFW_KEY_F4 -> return Key.F4
GLFW_KEY_F5 -> return Key.F5
GLFW_KEY_F6 -> return Key.F6
GLFW_KEY_F7 -> return Key.F7
GLFW_KEY_F8 -> return Key.F8
GLFW_KEY_F9 -> return Key.F9
GLFW_KEY_F10 -> return Key.F10
GLFW_KEY_NUM_LOCK -> return Key.NP_NUM_LOCK
GLFW_KEY_SCROLL_LOCK -> return Key.SCROLL_LOCK
GLFW_KEY_KP_7 -> return Key.NP7
GLFW_KEY_KP_8 -> return Key.NP8
GLFW_KEY_KP_9 -> return Key.NP9
GLFW_KEY_KP_SUBTRACT -> return Key.NP_SUBTRACT
GLFW_KEY_KP_4 -> return Key.NP4
GLFW_KEY_KP_5 -> return Key.NP5
GLFW_KEY_KP_6 -> return Key.NP6
GLFW_KEY_KP_ADD -> return Key.NP_ADD
GLFW_KEY_KP_1 -> return Key.NP1
GLFW_KEY_KP_2 -> return Key.NP2
GLFW_KEY_KP_3 -> return Key.NP3
GLFW_KEY_KP_0 -> return Key.NP0
GLFW_KEY_KP_DECIMAL -> return Key.NP_DECIMAL
GLFW_KEY_F11 -> return Key.F11
GLFW_KEY_F12 -> return Key.F12
//case GLFW_KEY_F13 : return Key.F13;
//case GLFW_KEY_F14 : return Key.F14;
//case GLFW_KEY_F15 : return Key.F15;
//case GLFW_KEY_F16 : return Key.F16;
//case GLFW_KEY_F17 : return Key.F17;
//case GLFW_KEY_F18 : return Key.F18;
//case GLFW_KEY_KANA : return Key.
//case GLFW_KEY_F19 : return Key.F19;
//case GLFW_KEY_CONVERT : return Key.
//case GLFW_KEY_NOCONVERT : return Key.
//case GLFW_KEY_YEN : return Key.
//case GLFW_KEY_NUMPADEQUALS : return Key.
//TODO: case GLFW_KEY_CIRCUMFLEX : return Key.CIRCUMFLEX;
//TODO: case GLFW_KEY_AT : return Key.AT;
//TODO: case GLFW_KEY_COLON : return Key.COLON;
//TODO: case GLFW_KEY_UNDERLINE : return Key.UNDERSCORE;
//case GLFW_KEY_KANJI : return Key.
//case GLFW_KEY_STOP : return Key.
//case GLFW_KEY_AX : return Key.
//case GLFW_KEY_UNLABELED : return Key.
//case GLFW_KEY_NUMPADENTER : return Key.
//case GLFW_KEY_SECTION : return Key.
//case GLFW_KEY_NUMPADCOMMA : return Key.
//case GLFW_KEY_DIVIDE :
//TODO: case GLFW_KEY_SYSRQ : return Key.SYSRQ;
GLFW_KEY_RIGHT_ALT -> return Key.ALT // Klay doesn't know left v. right
GLFW_KEY_LEFT_ALT -> return Key.ALT // Klay doesn't know left v. right
GLFW_KEY_MENU -> return Key.FUNCTION
GLFW_KEY_PAUSE -> return Key.PAUSE
GLFW_KEY_HOME -> return Key.HOME
GLFW_KEY_UP -> return Key.UP
GLFW_KEY_PAGE_UP -> return Key.PAGE_UP
GLFW_KEY_LEFT -> return Key.LEFT
GLFW_KEY_RIGHT -> return Key.RIGHT
GLFW_KEY_END -> return Key.END
GLFW_KEY_DOWN -> return Key.DOWN
GLFW_KEY_PAGE_DOWN -> return Key.PAGE_DOWN
GLFW_KEY_INSERT -> return Key.INSERT
GLFW_KEY_DELETE -> return Key.DELETE
//TODO: case GLFW_KEY_CLEAR : return Key.CLEAR;
GLFW_KEY_RIGHT_SUPER -> return Key.META // Klay doesn't know left v. right
GLFW_KEY_LEFT_SUPER -> return Key.META // Klay doesn't know left v. right
//case GLFW_KEY_LWIN : return Key.WINDOWS; // Duplicate with KEY_LMETA
//case GLFW_KEY_RWIN : return Key.WINDOWS; // Duplicate with KEY_RMETA
//case GLFW_KEY_APPS : return Key.
//TODO: case GLFW_KEY_POWER : return Key.POWER;
//case Keyboard.KEY_SLEEP : return Key.
else -> return null
}
}
companion object {
private val NO_UI_ERROR = "The java-lwjgl backend does not allow interop with AWT on Mac OS X. " + "Use the java-swt backend if you need native dialogs."
private fun getButton(lwjglButton: Int): ButtonEvent.Id? {
when (lwjglButton) {
GLFW_MOUSE_BUTTON_LEFT -> return ButtonEvent.Id.LEFT
GLFW_MOUSE_BUTTON_MIDDLE -> return ButtonEvent.Id.MIDDLE
GLFW_MOUSE_BUTTON_RIGHT -> return ButtonEvent.Id.RIGHT
else -> return null
}
}
}
}
| apache-2.0 | 26bc6f20484443fc5fdef1ea061e9fb0 | 43.694352 | 161 | 0.581357 | 3.937079 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedSymbolInspection.kt | 1 | 33773 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInsight.daemon.QuickFixBundle
import com.intellij.codeInsight.daemon.impl.analysis.HighlightUtil
import com.intellij.codeInsight.daemon.impl.analysis.JavaHighlightUtil
import com.intellij.codeInspection.*
import com.intellij.codeInspection.deadCode.UnusedDeclarationInspection
import com.intellij.codeInspection.ex.EntryPointsManager
import com.intellij.codeInspection.ex.EntryPointsManagerBase
import com.intellij.codeInspection.ex.EntryPointsManagerImpl
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiReference
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.PsiSearchHelper
import com.intellij.psi.search.PsiSearchHelper.SearchCostResult
import com.intellij.psi.search.PsiSearchHelper.SearchCostResult.*
import com.intellij.psi.search.SearchScope
import com.intellij.psi.search.searches.DefinitionsScopedSearch
import com.intellij.psi.search.searches.MethodReferencesSearch
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.safeDelete.SafeDeleteHandler
import com.intellij.util.Processor
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.asJava.LightClassUtil
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.asJava.toLightMethods
import org.jetbrains.kotlin.config.AnalysisFlags
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.base.projectStructure.matches
import org.jetbrains.kotlin.idea.base.projectStructure.scope.KotlinSourceFilterScope
import org.jetbrains.kotlin.idea.base.util.projectScope
import org.jetbrains.kotlin.idea.caches.project.implementingDescriptors
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.completion.KotlinIdeaCompletionBundle
import org.jetbrains.kotlin.idea.core.isInheritable
import org.jetbrains.kotlin.idea.core.script.configuration.DefaultScriptingSupport
import org.jetbrains.kotlin.idea.core.toDescriptor
import org.jetbrains.kotlin.idea.findUsages.KotlinFindUsagesHandlerFactory
import org.jetbrains.kotlin.idea.findUsages.handlers.KotlinFindClassUsagesHandler
import org.jetbrains.kotlin.idea.intentions.isFinalizeMethod
import org.jetbrains.kotlin.idea.intentions.isReferenceToBuiltInEnumFunction
import org.jetbrains.kotlin.idea.isMainFunction
import org.jetbrains.kotlin.idea.quickfix.RemoveUnusedFunctionParameterFix
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors
import org.jetbrains.kotlin.idea.search.findScriptsWithUsages
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchParameters
import org.jetbrains.kotlin.idea.search.isCheapEnoughToSearchConsideringOperators
import org.jetbrains.kotlin.idea.search.usagesSearch.getClassNameForCompanionObject
import org.jetbrains.kotlin.idea.search.usagesSearch.isDataClassProperty
import org.jetbrains.kotlin.idea.util.hasActualsFor
import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.checkers.explicitApiEnabled
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.descriptorUtil.isEffectivelyPublicApi
import org.jetbrains.kotlin.resolve.isInlineClass
import org.jetbrains.kotlin.resolve.isInlineClassType
import org.jetbrains.kotlin.util.findCallableMemberBySignature
import java.awt.GridBagConstraints
import java.awt.GridBagLayout
import java.awt.Insets
import javax.swing.JComponent
import javax.swing.JPanel
class UnusedSymbolInspection : AbstractKotlinInspection() {
companion object {
private val javaInspection = UnusedDeclarationInspection()
private val KOTLIN_ADDITIONAL_ANNOTATIONS = listOf("kotlin.test.*", "kotlin.js.JsExport")
private fun KtDeclaration.hasKotlinAdditionalAnnotation() =
this is KtNamedDeclaration && checkAnnotatedUsingPatterns(this, KOTLIN_ADDITIONAL_ANNOTATIONS)
fun isEntryPoint(declaration: KtNamedDeclaration): Boolean =
isEntryPoint(declaration, lazy(LazyThreadSafetyMode.NONE) { isCheapEnoughToSearchUsages(declaration) })
private fun isEntryPoint(declaration: KtNamedDeclaration, isCheapEnough: Lazy<SearchCostResult>): Boolean {
if (declaration.hasKotlinAdditionalAnnotation()) return true
if (declaration is KtClass && declaration.declarations.any { it.hasKotlinAdditionalAnnotation() }) return true
// Some of the main-function-cases are covered by 'javaInspection.isEntryPoint(lightElement)' call
// but not all of them: light method for parameterless main still points to parameterless name
// that is not an actual entry point from Java language point of view
if (declaration.isMainFunction()) return true
val lightElement: PsiElement = when (declaration) {
is KtClassOrObject -> declaration.toLightClass()
is KtNamedFunction, is KtSecondaryConstructor -> LightClassUtil.getLightClassMethod(declaration as KtFunction)
is KtProperty, is KtParameter -> {
if (declaration is KtParameter && !declaration.hasValOrVar()) return false
// we may handle only annotation parameters so far
if (declaration is KtParameter && isAnnotationParameter(declaration)) {
val lightAnnotationMethods = LightClassUtil.getLightClassPropertyMethods(declaration).toList()
for (javaParameterPsi in lightAnnotationMethods) {
if (javaInspection.isEntryPoint(javaParameterPsi)) {
return true
}
}
}
// can't rely on light element, check annotation ourselves
val entryPointsManager = EntryPointsManager.getInstance(declaration.project) as EntryPointsManagerBase
return checkAnnotatedUsingPatterns(
declaration,
entryPointsManager.additionalAnnotations + entryPointsManager.ADDITIONAL_ANNOTATIONS
)
}
else -> return false
} ?: return false
if (isCheapEnough.value == TOO_MANY_OCCURRENCES) return false
return javaInspection.isEntryPoint(lightElement)
}
private fun isAnnotationParameter(parameter: KtParameter): Boolean {
val constructor = parameter.ownerFunction as? KtConstructor<*> ?: return false
return constructor.containingClassOrObject?.isAnnotation() ?: false
}
private fun isCheapEnoughToSearchUsages(declaration: KtNamedDeclaration): SearchCostResult {
val project = declaration.project
val psiSearchHelper = PsiSearchHelper.getInstance(project)
if (!findScriptsWithUsages(declaration) { DefaultScriptingSupport.getInstance(project).isLoadedFromCache(it) }) {
// Not all script configuration are loaded; behave like it is used
return TOO_MANY_OCCURRENCES
}
val useScope = psiSearchHelper.getUseScope(declaration)
if (useScope is GlobalSearchScope) {
var zeroOccurrences = true
val list = listOf(declaration.name) + declarationAccessorNames(declaration) +
listOfNotNull(declaration.getClassNameForCompanionObject())
for (name in list) {
if (name == null) continue
when (psiSearchHelper.isCheapEnoughToSearchConsideringOperators(name, useScope, null, null)) {
ZERO_OCCURRENCES -> {
} // go on, check other names
FEW_OCCURRENCES -> zeroOccurrences = false
TOO_MANY_OCCURRENCES -> return TOO_MANY_OCCURRENCES // searching usages is too expensive; behave like it is used
}
}
if (zeroOccurrences) return ZERO_OCCURRENCES
}
return FEW_OCCURRENCES
}
/**
* returns list of declaration accessor names e.g. pair of getter/setter for property declaration
*
* note: could be more than declaration.getAccessorNames()
* as declaration.getAccessorNames() relies on LightClasses and therefore some of them could be not available
* (as not accessible outside of class)
*
* e.g.: private setter w/o body is not visible outside of class and could not be used
*/
private fun declarationAccessorNames(declaration: KtNamedDeclaration): List<String> =
when (declaration) {
is KtProperty -> listOfPropertyAccessorNames(declaration)
is KtParameter -> listOfParameterAccessorNames(declaration)
else -> emptyList()
}
fun listOfParameterAccessorNames(parameter: KtParameter): List<String> {
val accessors = mutableListOf<String>()
if (parameter.hasValOrVar()) {
parameter.name?.let {
accessors.add(JvmAbi.getterName(it))
if (parameter.isVarArg)
accessors.add(JvmAbi.setterName(it))
}
}
return accessors
}
fun listOfPropertyAccessorNames(property: KtProperty): List<String> {
val accessors = mutableListOf<String>()
val propertyName = property.name ?: return accessors
accessors.add(property.getter?.let { getCustomAccessorName(it) } ?: JvmAbi.getterName(propertyName))
if (property.isVar)
accessors.add(property.setter?.let { getCustomAccessorName(it) } ?: JvmAbi.setterName(propertyName))
return accessors
}
/*
If the property has 'JvmName' annotation at accessor it should be used instead
*/
private fun getCustomAccessorName(method: KtPropertyAccessor?): String? {
val customJvmNameAnnotation =
method?.annotationEntries?.firstOrNull { it.shortName?.asString() == "JvmName" } ?: return null
return customJvmNameAnnotation.findDescendantOfType<KtStringTemplateEntry>()?.text
}
private fun KtProperty.isSerializationImplicitlyUsedField(): Boolean {
val ownerObject = getNonStrictParentOfType<KtClassOrObject>()
if (ownerObject is KtObjectDeclaration && ownerObject.isCompanion()) {
val lightClass = ownerObject.getNonStrictParentOfType<KtClass>()?.toLightClass() ?: return false
return lightClass.fields.any { it.name == name && HighlightUtil.isSerializationImplicitlyUsedField(it) }
}
return false
}
private fun KtNamedFunction.isSerializationImplicitlyUsedMethod(): Boolean =
toLightMethods().any { JavaHighlightUtil.isSerializationRelatedMethod(it, it.containingClass) }
// variation of IDEA's AnnotationUtil.checkAnnotatedUsingPatterns()
fun checkAnnotatedUsingPatterns(
declaration: KtNamedDeclaration,
annotationPatterns: Collection<String>
): Boolean {
if (declaration.annotationEntries.isEmpty()) return false
val context = declaration.analyze()
val annotationsPresent = declaration.annotationEntries.mapNotNull {
context[BindingContext.ANNOTATION, it]?.fqName?.asString()
}
if (annotationsPresent.isEmpty()) return false
for (pattern in annotationPatterns) {
val hasAnnotation = if (pattern.endsWith(".*")) {
annotationsPresent.any { it.startsWith(pattern.dropLast(1)) }
} else {
pattern in annotationsPresent
}
if (hasAnnotation) return true
}
return false
}
}
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor {
return namedDeclarationVisitor(fun(declaration) {
ProgressManager.checkCanceled()
val message = declaration.describe()?.let { KotlinIdeaCompletionBundle.message("inspection.message.never.used", it) } ?: return
if (!RootKindFilter.projectSources.matches(declaration)) return
// Simple PSI-based checks
if (declaration is KtObjectDeclaration && declaration.isCompanion()) return // never mark companion object as unused (there are too many reasons it can be needed for)
if (declaration is KtSecondaryConstructor && declaration.containingClass()?.isEnum() == true) return
if (declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return
if (declaration is KtProperty && declaration.isLocal) return
if (declaration is KtParameter &&
(declaration.getParent().parent !is KtPrimaryConstructor || !declaration.hasValOrVar())
) return
// More expensive, resolve-based checks
val descriptor = declaration.resolveToDescriptorIfAny() ?: return
if (declaration.languageVersionSettings.explicitApiEnabled
&& (descriptor as? DeclarationDescriptorWithVisibility)?.isEffectivelyPublicApi == true) {
return
}
if (descriptor is FunctionDescriptor && descriptor.isOperator) return
val isCheapEnough = lazy(LazyThreadSafetyMode.NONE) {
isCheapEnoughToSearchUsages(declaration)
}
if (isEntryPoint(declaration, isCheapEnough)) return
if (declaration.isFinalizeMethod(descriptor)) return
if (declaration is KtProperty && declaration.isSerializationImplicitlyUsedField()) return
if (declaration is KtNamedFunction && declaration.isSerializationImplicitlyUsedMethod()) return
// properties can be referred by component1/component2, which is too expensive to search, don't mark them as unused
if (declaration is KtParameter && (declaration.isDataClassProperty() || declaration.isInlineClassProperty())) return
// experimental annotations
if (descriptor is ClassDescriptor && descriptor.kind == ClassKind.ANNOTATION_CLASS) {
val fqName = descriptor.fqNameSafe.asString()
val languageVersionSettings = declaration.languageVersionSettings
if (fqName in languageVersionSettings.getFlag(AnalysisFlags.optIn)) return
}
// Main checks: finding reference usages && text usages
if (hasNonTrivialUsages(declaration, isCheapEnough, descriptor)) return
if (declaration is KtClassOrObject && classOrObjectHasTextUsages(declaration)) return
val psiElement = declaration.nameIdentifier ?: (declaration as? KtConstructor<*>)?.getConstructorKeyword() ?: return
val problemDescriptor = holder.manager.createProblemDescriptor(
psiElement,
null,
message,
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
true,
*createQuickFixes(declaration).toTypedArray()
)
holder.registerProblem(problemDescriptor)
})
}
private fun classOrObjectHasTextUsages(classOrObject: KtClassOrObject): Boolean {
var hasTextUsages = false
// Finding text usages
if (classOrObject.useScope is GlobalSearchScope) {
val findClassUsagesHandler = KotlinFindClassUsagesHandler(classOrObject, KotlinFindUsagesHandlerFactory(classOrObject.project))
findClassUsagesHandler.processUsagesInText(
classOrObject,
{ hasTextUsages = true; false },
GlobalSearchScope.projectScope(classOrObject.project)
)
}
return hasTextUsages
}
private fun hasNonTrivialUsages(declaration: KtNamedDeclaration, descriptor: DeclarationDescriptor? = null): Boolean {
val isCheapEnough = lazy(LazyThreadSafetyMode.NONE) { isCheapEnoughToSearchUsages(declaration) }
return hasNonTrivialUsages(declaration, isCheapEnough, descriptor)
}
private fun hasNonTrivialUsages(
declaration: KtNamedDeclaration,
enoughToSearchUsages: Lazy<SearchCostResult>,
descriptor: DeclarationDescriptor? = null
): Boolean {
val project = declaration.project
val psiSearchHelper = PsiSearchHelper.getInstance(project)
val useScope = psiSearchHelper.getUseScope(declaration)
val restrictedScope = if (useScope is GlobalSearchScope) {
val zeroOccurrences = when (enoughToSearchUsages.value) {
ZERO_OCCURRENCES -> true
FEW_OCCURRENCES -> false
TOO_MANY_OCCURRENCES -> return true // searching usages is too expensive; behave like it is used
}
if (zeroOccurrences && !declaration.hasActualModifier()) {
if (declaration is KtObjectDeclaration && declaration.isCompanion()) {
// go on: companion object can be used only in containing class
} else {
return false
}
}
if (declaration.hasActualModifier()) {
KotlinSourceFilterScope.projectSources(project.projectScope(), project)
} else {
KotlinSourceFilterScope.projectSources(useScope, project)
}
} else useScope
if (declaration is KtTypeParameter) {
val containingClass = declaration.containingClass()
if (containingClass != null) {
val isOpenClass = containingClass.isInterface()
|| containingClass.hasModifier(KtTokens.ABSTRACT_KEYWORD)
|| containingClass.hasModifier(KtTokens.SEALED_KEYWORD)
|| containingClass.hasModifier(KtTokens.OPEN_KEYWORD)
if (isOpenClass && hasOverrides(containingClass, restrictedScope)) return true
val containingClassSearchScope = GlobalSearchScope.projectScope(project)
val isRequiredToCallFunction =
ReferencesSearch.search(KotlinReferencesSearchParameters(containingClass, containingClassSearchScope)).any { ref ->
val userType = ref.element.parent as? KtUserType ?: return@any false
val typeArguments = userType.typeArguments
if (typeArguments.isEmpty()) return@any false
val parameter = userType.getStrictParentOfType<KtParameter>() ?: return@any false
val callableDeclaration = parameter.getStrictParentOfType<KtCallableDeclaration>()?.let {
if (it !is KtNamedFunction) it.containingClass() else it
} ?: return@any false
val typeParameters = callableDeclaration.typeParameters.map { it.name }
if (typeParameters.isEmpty()) return@any false
if (typeArguments.none { it.text in typeParameters }) return@any false
ReferencesSearch.search(KotlinReferencesSearchParameters(callableDeclaration, containingClassSearchScope)).any {
val callElement = it.element.parent as? KtCallElement
callElement != null && callElement.typeArgumentList == null
}
}
if (isRequiredToCallFunction) return true
}
}
return (declaration is KtObjectDeclaration && declaration.isCompanion() &&
declaration.body?.declarations?.isNotEmpty() == true) ||
hasReferences(declaration, descriptor, restrictedScope) ||
hasOverrides(declaration, restrictedScope) ||
hasFakeOverrides(declaration, restrictedScope) ||
hasPlatformImplementations(declaration, descriptor)
}
private fun checkDeclaration(declaration: KtNamedDeclaration, importedDeclaration: KtNamedDeclaration): Boolean =
declaration !in importedDeclaration.parentsWithSelf && !hasNonTrivialUsages(importedDeclaration)
private val KtNamedDeclaration.isObjectOrEnum: Boolean get() = this is KtObjectDeclaration || this is KtClass && isEnum()
private fun checkReference(ref: PsiReference, declaration: KtNamedDeclaration, descriptor: DeclarationDescriptor?): Boolean {
ProgressManager.checkCanceled()
if (declaration.isAncestor(ref.element)) return true // usages inside element's declaration are not counted
if (ref.element.parent is KtValueArgumentName) return true // usage of parameter in form of named argument is not counted
val import = ref.element.getParentOfType<KtImportDirective>(false)
if (import != null) {
if (import.aliasName != null && import.aliasName != declaration.name) {
return false
}
// check if we import member(s) from object / nested object / enum and search for their usages
val originalDeclaration = (descriptor as? TypeAliasDescriptor)?.classDescriptor?.findPsi() as? KtNamedDeclaration
if (declaration is KtClassOrObject || originalDeclaration is KtClassOrObject) {
if (import.isAllUnder) {
val importedFrom = import.importedReference?.getQualifiedElementSelector()?.mainReference?.resolve()
as? KtClassOrObject ?: return true
return importedFrom.declarations.none { it is KtNamedDeclaration && hasNonTrivialUsages(it) }
} else {
if (import.importedFqName != declaration.fqName) {
val importedDeclaration =
import.importedReference?.getQualifiedElementSelector()?.mainReference?.resolve() as? KtNamedDeclaration
?: return true
if (declaration.isObjectOrEnum || importedDeclaration.containingClassOrObject is KtObjectDeclaration) return checkDeclaration(
declaration,
importedDeclaration
)
if (originalDeclaration?.isObjectOrEnum == true) return checkDeclaration(
originalDeclaration,
importedDeclaration
)
// check type alias
if (importedDeclaration.fqName == declaration.fqName) return true
}
}
}
return true
}
return false
}
private fun hasReferences(
declaration: KtNamedDeclaration,
descriptor: DeclarationDescriptor?,
useScope: SearchScope
): Boolean {
fun checkReference(ref: PsiReference): Boolean = checkReference(ref, declaration, descriptor)
val searchOptions = KotlinReferencesSearchOptions(acceptCallableOverrides = declaration.hasActualModifier())
val searchParameters = KotlinReferencesSearchParameters(
declaration,
useScope,
kotlinOptions = searchOptions
)
val referenceUsed: Boolean by lazy { !ReferencesSearch.search(searchParameters).forEach(Processor { checkReference(it) }) }
if (descriptor is FunctionDescriptor && DescriptorUtils.findJvmNameAnnotation(descriptor) != null) {
if (referenceUsed) return true
}
if (declaration is KtSecondaryConstructor) {
val containingClass = declaration.containingClass()
if (containingClass != null && ReferencesSearch.search(KotlinReferencesSearchParameters(containingClass, useScope)).any {
it.element.getStrictParentOfType<KtTypeAlias>() != null
}) return true
}
if (declaration is KtCallableDeclaration && declaration.canBeHandledByLightMethods(descriptor)) {
val lightMethods = declaration.toLightMethods()
if (lightMethods.isNotEmpty()) {
val lightMethodsUsed = lightMethods.any { method ->
!MethodReferencesSearch.search(method).forEach(Processor { checkReference(it) })
}
if (lightMethodsUsed) return true
if (!declaration.hasActualModifier()) return false
}
}
if (declaration is KtEnumEntry) {
val enumClass = declaration.containingClass()?.takeIf { it.isEnum() }
if (hasBuiltInEnumFunctionReference(enumClass, useScope)) return true
}
return referenceUsed || checkPrivateDeclaration(declaration, descriptor)
}
private fun hasBuiltInEnumFunctionReference(enumClass: KtClass?, useScope: SearchScope): Boolean {
if (enumClass == null) return false
return enumClass.anyDescendantOfType(KtExpression::isReferenceToBuiltInEnumFunction) ||
ReferencesSearch.search(KotlinReferencesSearchParameters(enumClass, useScope)).any(::hasBuiltInEnumFunctionReference)
}
private fun hasBuiltInEnumFunctionReference(reference: PsiReference): Boolean {
val parent = reference.element.getParentOfTypes(
true,
KtTypeReference::class.java,
KtQualifiedExpression::class.java,
KtCallableReferenceExpression::class.java
) ?: return false
return parent.isReferenceToBuiltInEnumFunction()
}
private fun checkPrivateDeclaration(declaration: KtNamedDeclaration, descriptor: DeclarationDescriptor?): Boolean {
if (descriptor == null || !declaration.isPrivateNestedClassOrObject) return false
val set = hashSetOf<KtSimpleNameExpression>()
declaration.containingKtFile.importList?.acceptChildren(simpleNameExpressionRecursiveVisitor {
set += it
})
return set.mapNotNull { it.referenceExpression() }
.filter { descriptor in it.resolveMainReferenceToDescriptors() }
.any { !checkReference(it.mainReference, declaration, descriptor) }
}
private fun KtCallableDeclaration.canBeHandledByLightMethods(descriptor: DeclarationDescriptor?): Boolean {
return when {
descriptor is ConstructorDescriptor -> {
val classDescriptor = descriptor.constructedClass
!classDescriptor.isInlineClass() && classDescriptor.visibility != DescriptorVisibilities.LOCAL
}
hasModifier(KtTokens.INTERNAL_KEYWORD) -> false
descriptor !is FunctionDescriptor -> true
else -> !descriptor.hasInlineClassParameters()
}
}
private fun FunctionDescriptor.hasInlineClassParameters(): Boolean {
return when {
dispatchReceiverParameter?.type?.isInlineClassType() == true -> true
extensionReceiverParameter?.type?.isInlineClassType() == true -> true
else -> valueParameters.any { it.type.isInlineClassType() }
}
}
private fun hasOverrides(declaration: KtNamedDeclaration, useScope: SearchScope): Boolean =
DefinitionsScopedSearch.search(declaration, useScope).findFirst() != null
private fun hasFakeOverrides(declaration: KtNamedDeclaration, useScope: SearchScope): Boolean {
val ownerClass = declaration.containingClassOrObject as? KtClass ?: return false
if (!ownerClass.isInheritable()) return false
val descriptor = declaration.toDescriptor() as? CallableMemberDescriptor ?: return false
if (descriptor.modality == Modality.ABSTRACT) return false
val lightMethods = declaration.toLightMethods()
return DefinitionsScopedSearch.search(ownerClass, useScope).any { element: PsiElement ->
when (element) {
is KtLightClass -> {
val memberBySignature =
(element.kotlinOrigin?.toDescriptor() as? ClassDescriptor)?.findCallableMemberBySignature(descriptor)
memberBySignature != null &&
!memberBySignature.kind.isReal &&
memberBySignature.overriddenDescriptors.any { it != descriptor }
}
is PsiClass ->
lightMethods.any { lightMethod ->
val sameMethods = element.findMethodsBySignature(lightMethod, true)
sameMethods.all { it.containingClass != element } &&
sameMethods.any { it.containingClass != lightMethod.containingClass }
}
else ->
false
}
}
}
private fun hasPlatformImplementations(declaration: KtNamedDeclaration, descriptor: DeclarationDescriptor?): Boolean {
if (!declaration.hasExpectModifier()) return false
if (descriptor !is MemberDescriptor) return false
val commonModuleDescriptor = declaration.containingKtFile.findModuleDescriptor()
// TODO: Check if 'allImplementingDescriptors' should be used instead!
return commonModuleDescriptor.implementingDescriptors.any { it.hasActualsFor(descriptor) } ||
commonModuleDescriptor.hasActualsFor(descriptor)
}
override fun createOptionsPanel(): JComponent = JPanel(GridBagLayout()).apply {
add(
EntryPointsManagerImpl.createConfigureAnnotationsButton(),
GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, Insets(0, 0, 0, 0), 0, 0)
)
}
private fun createQuickFixes(declaration: KtNamedDeclaration): List<LocalQuickFix> {
val list = ArrayList<LocalQuickFix>()
list.add(SafeDeleteFix(declaration))
for (annotationEntry in declaration.annotationEntries) {
val resolvedName = annotationEntry.resolveToDescriptorIfAny() ?: continue
val fqName = resolvedName.fqName?.asString() ?: continue
// checks taken from com.intellij.codeInspection.util.SpecialAnnotationsUtilBase.createAddToSpecialAnnotationFixes
if (fqName.startsWith("kotlin.")
|| fqName.startsWith("java.")
|| fqName.startsWith("javax.")
|| fqName.startsWith("org.jetbrains.annotations.")
)
continue
val intentionAction = createAddToDependencyInjectionAnnotationsFix(declaration.project, fqName)
list.add(IntentionWrapper(intentionAction))
}
return list
}
private fun KtParameter.isInlineClassProperty(): Boolean {
if (!hasValOrVar()) return false
return containingClassOrObject?.hasModifier(KtTokens.INLINE_KEYWORD) == true ||
containingClassOrObject?.hasModifier(KtTokens.VALUE_KEYWORD) == true
}
}
class SafeDeleteFix(declaration: KtDeclaration) : LocalQuickFix {
@Nls
private val name: String =
if (declaration is KtConstructor<*>) KotlinBundle.message("safe.delete.constructor")
else QuickFixBundle.message("safe.delete.text", declaration.name)
override fun getName() = name
override fun getFamilyName() = QuickFixBundle.message("safe.delete.family")
override fun startInWriteAction(): Boolean = false
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val declaration = descriptor.psiElement.getStrictParentOfType<KtDeclaration>() ?: return
if (!FileModificationService.getInstance().prepareFileForWrite(declaration.containingFile)) return
if (declaration is KtParameter && declaration.parent is KtParameterList && declaration.parent?.parent is KtFunction) {
RemoveUnusedFunctionParameterFix(declaration).invoke(project, declaration.findExistingEditor(), declaration.containingKtFile)
} else {
val declarationPointer = declaration.createSmartPointer()
invokeLater {
declarationPointer.element?.let { safeDelete(project, it) }
}
}
}
}
private fun safeDelete(project: Project, declaration: PsiElement) {
SafeDeleteHandler.invoke(project, arrayOf(declaration), false)
}
| apache-2.0 | 2a2b7b48b1af2d0bacf858a312f712c2 | 50.404871 | 178 | 0.673289 | 6.076466 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/firehose/src/main/kotlin/com/kotlin/firehose/DeleteStream.kt | 1 | 1659 | // snippet-sourcedescription:[DeleteStream.kt demonstrates how to delete a delivery stream.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Amazon Kinesis Data Firehose]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.firehose
// snippet-start:[firehose.kotlin.delete_stream.import]
import aws.sdk.kotlin.services.firehose.FirehoseClient
import aws.sdk.kotlin.services.firehose.model.DeleteDeliveryStreamRequest
import kotlin.system.exitProcess
// snippet-end:[firehose.kotlin.delete_stream.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<streamName>
Where:
streamName - The name of the delivery stream.
"""
if (args.size != 1) {
println(usage)
exitProcess(0)
}
val streamName = args[0]
delStream(streamName)
}
// snippet-start:[firehose.kotlin.delete_stream.main]
suspend fun delStream(streamName: String) {
val request = DeleteDeliveryStreamRequest {
deliveryStreamName = streamName
}
FirehoseClient { region = "us-west-2" }.use { firehoseClient ->
firehoseClient.deleteDeliveryStream(request)
println("Delivery Stream $streamName is deleted")
}
}
// snippet-end:[firehose.kotlin.delete_stream.main]
| apache-2.0 | e56ce6092df43705981adba6d208280d | 26.603448 | 92 | 0.694997 | 3.95 | false | false | false | false |
orauyeu/SimYukkuri | subprojects/simyukkuri/src/main/kotlin/simyukkuri/gameobject/yukkuri/event/action/CalculatePosture.kt | 1 | 962 | package simyukkuri.gameobject.yukkuri.event.action
import simyukkuri.geometry.HasPosition3
internal fun <E> animation(pattern: Array<out E>, duration: Float, currentTime: Float): E {
return pattern[((currentTime % (pattern.size * duration)) / duration).toInt()]
}
internal fun postureByPosition(from: HasPosition3, to: HasPosition3): Posture {
val rad = Math.atan2(to.x - from.x, to.z - from.z)
return when {
-Math.PI / 4 <= rad && rad < Math.PI / 4 -> Posture.RIGHT
Math.PI / 4 <= rad && rad < Math.PI * 3 / 4 -> Posture.BACK
-Math.PI * 3 / 4 < rad && rad < -Math.PI / 4 -> Posture.FRONT
else -> Posture.LEFT
}
}
internal fun randomStandingPosture(): Posture {
val r = Math.random()
return when {
0 <= r && r < 1 / 4 -> Posture.RIGHT
1 / 4 <= r && r < 1 / 2 -> Posture.BACK
1 / 2 <= r && r < 3 / 4 -> Posture.LEFT
else -> Posture.FRONT
}
} | apache-2.0 | 0f81361f1cfebd3785aa6a147c88bf12 | 33.703704 | 91 | 0.573805 | 3.363636 | false | false | false | false |
google/intellij-community | platform/lang-impl/src/com/intellij/ui/AsyncImageIcon.kt | 1 | 4277 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ui
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.ScalableIcon
import com.intellij.ui.icons.CopyableIcon
import com.intellij.ui.scale.ScaleContext
import com.intellij.ui.scale.UserScaleContext
import com.intellij.util.IconUtil
import com.intellij.util.concurrency.EdtExecutorService
import com.intellij.util.ui.StartupUiUtil
import org.jetbrains.annotations.ApiStatus
import java.awt.Component
import java.awt.Graphics
import java.awt.Image
import java.awt.Rectangle
import java.util.concurrent.CompletableFuture
import javax.swing.Icon
/**
* Provide a way to show [Image] loaded in background as [Icon]
* Icon size will be taken from placeholder [defaultIcon] and should be loaded and scaled to size with [imageLoader]
* This implementation takes all scales into account
*
* @see [ScalingDeferredSquareImageIcon]
* if it is better for the case to use single thread shared with all [DeferredIconImpl] instances to load the [Image]
*
*/
@ApiStatus.Experimental
class AsyncImageIcon private constructor(
defaultIcon: Icon,
private val scale: Float = 1.0f,
private val imageLoader: (ScaleContext, Int, Int) -> CompletableFuture<Image?>,
// allows keeping cache after scale and copy functions
cache: UserScaleContext.Cache<CompletableFuture<Image?>, ScaleContext>?
) : Icon, ScalableIcon, CopyableIcon {
constructor(
defaultIcon: Icon,
scale: Float = 1.0f,
imageLoader: (ScaleContext, Int, Int) -> CompletableFuture<Image?>,
) : this(defaultIcon, scale, imageLoader, null)
private val defaultIcon = IconUtil.scale(defaultIcon, null, scale)
private val repaintScheduler = RepaintScheduler()
// Icon can be located on different monitors (with different ScaleContext),
// so it is better to cache image for each
private val imageRequestsCache: UserScaleContext.Cache<CompletableFuture<Image?>, ScaleContext> =
cache ?: ScaleContext.Cache { scaleCtx ->
imageLoader(scaleCtx, iconWidth, iconHeight).also {
it.thenRunAsync({ repaintScheduler.scheduleRepaint(iconWidth, iconHeight) }, EdtExecutorService.getInstance())
}
}
override fun getIconHeight() = defaultIcon.iconHeight
override fun getIconWidth() = defaultIcon.iconWidth
override fun paintIcon(c: Component?, g: Graphics, x: Int, y: Int) {
val imageRequest = imageRequestsCache.getOrProvide(ScaleContext.create(c))!!
if (!imageRequest.isDone && c != null) {
repaintScheduler.requestRepaint(c, x, y)
}
val image = try {
imageRequest.getNow(null)
}
catch (error: Throwable) {
LOG.debug("Image loading failed", error)
null
}
if (image == null) {
defaultIcon.paintIcon(c, g, x, y)
}
else {
val bounds = Rectangle(x, y, iconWidth, iconHeight)
StartupUiUtil.drawImage(g, image, bounds, c)
}
}
override fun copy(): Icon = AsyncImageIcon(defaultIcon, scale, imageLoader, imageRequestsCache)
override fun getScale(): Float = scale
override fun scale(scaleFactor: Float): Icon = AsyncImageIcon(defaultIcon, scaleFactor, imageLoader, imageRequestsCache)
companion object {
private val LOG = logger<AsyncImageIcon>()
}
}
private class RepaintScheduler {
// We collect repaintRequests for the icon to understand which Components should be repainted when icon is loaded
// We can receive paintIcon few times for the same component but with different x, y
// Only the last request should be scheduled
private val repaintRequests = mutableMapOf<Component, DeferredIconRepaintScheduler.RepaintRequest>()
fun requestRepaint(c: Component, x: Int, y: Int) {
repaintRequests[c] = repaintScheduler.createRepaintRequest(c, x, y)
}
fun scheduleRepaint(width: Int, height: Int) {
for ((_, repaintRequest) in repaintRequests) {
repaintScheduler.scheduleRepaint(repaintRequest, width, height, alwaysSchedule = false)
}
repaintRequests.clear()
}
companion object {
// Scheduler for all DelegatingIcon instances. It repaints components that contain these icons in a batch
private val repaintScheduler = DeferredIconRepaintScheduler()
}
} | apache-2.0 | f37eba4c4d8ace0484f737b1fc4afed4 | 36.2 | 122 | 0.74585 | 4.346545 | false | false | false | false |
RuneSuite/client | api/src/main/java/org/runestar/client/api/game/live/InterfaceParents.kt | 1 | 1057 | package org.runestar.client.api.game.live
import org.runestar.client.api.game.NodeHashTable
import org.runestar.client.api.game.Component
import org.runestar.client.api.game.ComponentId
import org.runestar.client.raw.CLIENT
import org.runestar.client.raw.access.XNodeHashTable
import org.runestar.client.raw.access.XInterfaceParent
object InterfaceParents : NodeHashTable<ComponentId, Int, XInterfaceParent>() {
override val accessor: XNodeHashTable get() = CLIENT.interfaceParents
override fun wrapKey(node: XInterfaceParent): ComponentId = ComponentId(node.key.toInt())
override fun unwrapKey(k: ComponentId): Long = k.packed.toLong()
override fun wrapValue(node: XInterfaceParent): Int = node.itf
fun parentId(itf: Int): Int {
val node = firstOrNull { it.itf == itf } ?: return -1
return node.key.toInt()
}
fun parent(group: Int): Component? {
val pid = parentId(group)
if (pid == -1) return null
return Components[ComponentId.getItf(pid), ComponentId.getComponent(pid)]
}
} | mit | 093941ee583dbcc2097fff25f15906e1 | 34.266667 | 93 | 0.730369 | 3.708772 | false | false | false | false |
Atsky/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/debugger/history/HistoryManager.kt | 1 | 12756 | package org.jetbrains.haskell.debugger.history
import org.jetbrains.haskell.debugger.actions.SwitchableAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.execution.ui.RunnerLayoutUi
import com.intellij.openapi.actionSystem.DefaultActionGroup
import org.jetbrains.haskell.debugger.highlighting.HsExecutionPointHighlighter
import com.intellij.ui.AppUIUtil
import org.jetbrains.haskell.debugger.frames.HsStackFrame
import java.util.ArrayList
import org.jetbrains.haskell.debugger.frames.HsHistoryFrame
import org.jetbrains.haskell.debugger.protocol.CommandCallback
import org.jetbrains.haskell.debugger.parser.MoveHistResult
import org.jetbrains.haskell.debugger.parser.HsStackFrameInfo
import org.jetbrains.haskell.debugger.parser.HsHistoryFrameInfo
import org.jetbrains.haskell.debugger.HaskellDebugProcess
import com.intellij.icons.AllIcons.Actions
import java.util.Deque
import java.util.ArrayDeque
import com.intellij.xdebugger.impl.ui.XDebuggerUIConstants
import org.jetbrains.haskell.debugger.utils.SyncObject
import com.intellij.xdebugger.impl.XDebugSessionImpl
import com.intellij.xdebugger.XDebugSession
/**
* Created by vlad on 8/5/14.
*/
class HistoryManager(private val debugSession : XDebugSession,
private val debugProcess: HaskellDebugProcess) {
val HISTORY_SIZE: Int = 20
class StackState(val historyIndex: Int,
val realHistIndex: Int,
val allFramesCollected: Boolean,
val historyFrames: List<HsHistoryFrame>,
val historyFramesLines: List<*>)
private val historyStack: HsHistoryStack = HsHistoryStack(debugProcess)
private var historyPanel: HistoryTab? = null
private val historyHighlighter = HsExecutionPointHighlighter(debugProcess.session!!.project,
HsExecutionPointHighlighter.HighlighterType.HISTORY)
private val backAction: SwitchableAction = object : SwitchableAction("back", "Move back along history", Actions.Back) {
override fun actionPerformed(e: AnActionEvent?) {
enabled = false
forwardAction.enabled = false
update(e)
forwardAction.update(e)
if (historyStack.historyIndex - 1 > HISTORY_SIZE) {
historyStack.moveTo(historyStack.historyIndex + 1)
} else {
historyPanel?.shiftBack()
}
}
}
private val forwardAction: SwitchableAction = object : SwitchableAction("forward", "Move forward along history",
Actions.Forward) {
override fun actionPerformed(e: AnActionEvent?) {
enabled = false
backAction.enabled = false
update(e)
backAction.update(e)
if (historyStack.historyIndex > HISTORY_SIZE) {
historyStack.moveTo(historyStack.historyIndex - 1)
} else {
historyPanel?.shiftForward()
}
}
}
fun initHistoryTab(debugSession : XDebugSessionImpl) {
historyPanel = HistoryTab(debugSession, debugProcess, this)
}
fun withRealFrameUpdate(finalCallback: ((MoveHistResult?) -> Unit)?): Unit =
historyStack.withRealFrameUpdate(finalCallback)
fun indexSelected(index: Int): Unit = historyStack.moveTo(index)
fun setHistoryFramesInfo(initial: HsHistoryFrameInfo, others: ArrayList<HsHistoryFrameInfo>, full: Boolean) {
AppUIUtil.invokeLaterIfProjectAlive(debugProcess.session!!.project, Runnable({ ->
historyPanel!!.addHistoryLine(initial.toString())
for (info in others) {
historyPanel!!.addHistoryLine(info.toString())
}
if (!full) {
historyPanel!!.addHistoryLine("...")
}
}))
}
fun registerContent(ui: RunnerLayoutUi) {
initHistoryTab(debugSession as XDebugSessionImpl)
val context = ui.createContent("history", historyPanel!!.getComponent(), "History", null, null)
context.isCloseable = false
ui.addContent(context)
ui.options.setToFocus(context, XDebuggerUIConstants.LAYOUT_VIEW_BREAKPOINT_CONDITION)
}
fun registerActions(topToolbar: DefaultActionGroup) {
topToolbar.addSeparator()
topToolbar.add(backAction)
topToolbar.add(forwardAction)
}
fun historyChanged(hasNext: Boolean, hasPrevious: Boolean, stackFrame: HsStackFrame?) {
AppUIUtil.invokeLaterIfProjectAlive(debugProcess.session!!.project, Runnable({ ->
backAction.enabled = hasPrevious
forwardAction.enabled = hasNext
historyPanel!!.stackChanged(stackFrame)
if (stackFrame != null) {
historyHighlighter.show(stackFrame, false, null)
} else {
historyHighlighter.hide()
}
}))
}
fun clean(): Unit = historyChanged(false, false, null)
fun historyFrameAppeared(frame: HsHistoryFrame): Unit = historyStack.addFrame(frame)
fun resetHistoryStack(): Unit = historyStack.clear()
fun markHistoryFramesAsObsolete(): Unit = historyStack.markFramesAsObsolete()
// save/load state managing
private val states: Deque<StackState> = ArrayDeque()
fun saveState(): Unit = states.addLast(historyStack.save())
fun loadState(): Unit = AppUIUtil.invokeLaterIfProjectAlive(debugProcess.session!!.project, {
historyStack.loadFrom(states.pollLast()!!)
})
fun hasSavedStates(): Boolean = !states.isEmpty()
private inner class HsHistoryStack(private val debugProcess: HaskellDebugProcess) {
var historyIndex: Int = 0
private set
private var realHistIndex: Int = 0
private var allFramesCollected = false
private val historyFrames: java.util.ArrayList<HsHistoryFrame> = ArrayList()
fun addFrame(frame: HsHistoryFrame) {
historyFrames.add(frame)
}
fun clear() {
historyIndex = 0
realHistIndex = 0
allFramesCollected = false
historyFrames.clear()
updateHistory()
}
fun hasNext(): Boolean = historyIndex > 0
fun hasPrevious(): Boolean = !allFramesCollected || historyIndex + 1 < historyFrames.size
fun currentFrame(): HsHistoryFrame? =
if (historyIndex < historyFrames.size) historyFrames.get(historyIndex) else null
fun moveTo(index: Int) {
if (index == -1 || index == historyIndex) {
} else if (index < historyIndex) {
val it = historyIndex - index
for (i in 1..it) {
moveForward()
}
} else {
val it = index - historyIndex
for (i in 1..it) {
moveBack()
}
}
updateHistory()
}
private fun moveForward() {
if (historyIndex > 0) {
if (historyFrames[historyIndex - 1].obsolete) {
val syncObject = SyncObject()
syncObject.lock()
withRealFrameUpdate {
debugProcess.debugger.forward(object : CommandCallback<MoveHistResult?>() {
override fun execAfterParsing(result: MoveHistResult?) {
syncObject.lock()
if (result != null) {
--historyIndex
--realHistIndex
}
syncObject.signal()
syncObject.unlock()
}
})
}
syncObject.await()
syncObject.unlock()
} else {
--historyIndex
}
}
}
private fun moveBack() {
if (historyIndex + 1 < historyFrames.size) {
if (historyFrames[historyIndex + 1].obsolete) {
val syncObject = SyncObject()
syncObject.lock()
withRealFrameUpdate {
debugProcess.debugger.back(object : CommandCallback<MoveHistResult?>() {
override fun execAfterParsing(result: MoveHistResult?) {
syncObject.lock()
if (result != null) {
++historyIndex
++realHistIndex
}
syncObject.signal()
syncObject.unlock()
}
})
}
syncObject.await()
syncObject.unlock()
} else {
++historyIndex
}
} else if (allFramesCollected) {
} else {
val syncObject = SyncObject()
syncObject.lock()
withRealFrameUpdate {
debugProcess.debugger.back(object : CommandCallback<MoveHistResult?>() {
override fun execAfterParsing(result: MoveHistResult?) {
syncObject.lock()
if (result != null) {
val frame = HsHistoryFrame(debugProcess.debugger, HsStackFrameInfo(result.filePosition, result.bindingList.list, null))
addFrame(frame)
++historyIndex
++realHistIndex
} else {
allFramesCollected = true
}
syncObject.signal()
syncObject.unlock()
}
})
}
syncObject.await()
syncObject.unlock()
}
}
private fun updateHistory() = historyChanged(hasNext(), hasPrevious(), currentFrame())
fun markFramesAsObsolete() {
for (frame in historyFrames) {
frame.obsolete = true
}
}
fun withRealFrameUpdate(finalCallback: ((MoveHistResult?) -> Unit)?) {
if (realHistIndex == historyIndex) {
finalCallback?.invoke(null)
return
}
if (realHistIndex < historyIndex) {
debugProcess.debugger.back(SequentialBackCallback(historyIndex - realHistIndex, finalCallback))
} else {
debugProcess.debugger.forward(SequentialForwardCallback(realHistIndex - historyIndex, finalCallback))
}
}
fun save(): StackState = StackState(historyIndex, realHistIndex, allFramesCollected, ArrayList(historyFrames),
historyPanel!!.getHistoryFramesModel().elements)
fun loadFrom(state: StackState) {
historyIndex = state.historyIndex
realHistIndex = state.realHistIndex
allFramesCollected = state.allFramesCollected
historyFrames.clear()
historyFrames.addAll(state.historyFrames)
historyPanel!!.getHistoryFramesModel().removeAllElements()
for (elem in state.historyFramesLines) {
historyPanel!!.addHistoryLine(elem.toString())
}
}
private inner class SequentialBackCallback(var toGo: Int,
val finalCallback: ((MoveHistResult?) -> Unit)?) : CommandCallback<MoveHistResult?>() {
override fun execAfterParsing(result: MoveHistResult?) {
--toGo
++realHistIndex
if (toGo == 0 || result == null) {
finalCallback?.invoke(null)
} else {
debugProcess.debugger.back(this)
}
}
}
private inner class SequentialForwardCallback(var toGo: Int,
val finalCallback: ((MoveHistResult?) -> Unit)?) : CommandCallback<MoveHistResult?>() {
override fun execAfterParsing(result: MoveHistResult?) {
--toGo
--realHistIndex
if (toGo == 0 || result == null) {
finalCallback?.invoke(null)
} else {
debugProcess.debugger.forward(this)
}
}
}
}
}
| apache-2.0 | 6d0de00e03e70fedf0c4f939dc0ba2c4 | 39.495238 | 151 | 0.557777 | 5.467638 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/kotlin.searching/base/src/org/jetbrains/kotlin/idea/base/searching/usages/handlers/KotlinFindUsagesHandler.kt | 1 | 5865 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.base.searching.usages.handlers
import com.intellij.find.findUsages.FindUsagesHandler
import com.intellij.find.findUsages.FindUsagesOptions
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.impl.light.LightMemberReference
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.SearchScope
import com.intellij.usageView.UsageInfo
import com.intellij.util.CommonProcessors
import com.intellij.util.Processor
import org.jetbrains.kotlin.idea.base.searching.usages.KotlinReferencePreservingUsageInfo
import org.jetbrains.kotlin.idea.base.searching.usages.KotlinReferenceUsageInfo
import org.jetbrains.kotlin.idea.base.util.runReadActionInSmartMode
import org.jetbrains.kotlin.idea.base.searching.usages.KotlinFindUsagesHandlerFactory
import java.util.*
abstract class KotlinFindUsagesHandler<T : PsiElement>(
psiElement: T,
private val elementsToSearch: Collection<PsiElement>,
val factory: KotlinFindUsagesHandlerFactory
) : FindUsagesHandler(psiElement) {
@Suppress("UNCHECKED_CAST")
fun getElement(): T {
return psiElement as T
}
constructor(psiElement: T, factory: KotlinFindUsagesHandlerFactory) : this(psiElement, emptyList(), factory)
override fun getPrimaryElements(): Array<PsiElement> {
return if (elementsToSearch.isEmpty())
arrayOf(psiElement)
else
elementsToSearch.toTypedArray()
}
private fun searchTextOccurrences(
element: PsiElement,
processor: Processor<in UsageInfo>,
options: FindUsagesOptions
): Boolean {
if (!options.isSearchForTextOccurrences) return true
val scope = options.searchScope
if (scope is GlobalSearchScope) {
if (options.fastTrack == null) {
return processUsagesInText(element, processor, scope)
}
options.fastTrack.searchCustom {
processUsagesInText(element, processor, scope)
}
}
return true
}
override fun processElementUsages(
element: PsiElement,
processor: Processor<in UsageInfo>,
options: FindUsagesOptions
): Boolean {
return searchReferences(element, processor, options, forHighlight = false) && searchTextOccurrences(element, processor, options)
}
private fun searchReferences(
element: PsiElement,
processor: Processor<in UsageInfo>,
options: FindUsagesOptions,
forHighlight: Boolean
): Boolean {
val searcher = createSearcher(element, processor, options)
if (!runReadAction { project }.runReadActionInSmartMode { searcher.buildTaskList(forHighlight) }) return false
return searcher.executeTasks()
}
protected abstract fun createSearcher(
element: PsiElement,
processor: Processor<in UsageInfo>,
options: FindUsagesOptions
): Searcher
override fun findReferencesToHighlight(target: PsiElement, searchScope: SearchScope): Collection<PsiReference> {
val results = Collections.synchronizedList(arrayListOf<PsiReference>())
val options = findUsagesOptions.clone()
options.searchScope = searchScope
searchReferences(target, Processor { info ->
val reference = info.reference
if (reference != null) {
results.add(reference)
}
true
}, options, forHighlight = true)
return results
}
protected abstract class Searcher(
val element: PsiElement,
val processor: Processor<in UsageInfo>,
val options: FindUsagesOptions
) {
private val tasks = ArrayList<() -> Boolean>()
/**
* Adds a time-consuming operation to be executed outside read-action
*/
protected fun addTask(task: () -> Boolean) {
tasks.add(task)
}
/**
* Invoked outside read-action
*/
fun executeTasks(): Boolean {
return tasks.all { it() }
}
/**
* Invoked under read-action, should use [addTask] for all time-consuming operations
*/
abstract fun buildTaskList(forHighlight: Boolean): Boolean
}
companion object {
val LOG = Logger.getInstance(KotlinFindUsagesHandler::class.java)
internal fun processUsage(processor: Processor<in UsageInfo>, ref: PsiReference): Boolean =
processor.processIfNotNull {
when {
ref is LightMemberReference -> KotlinReferencePreservingUsageInfo(ref)
ref.element.isValid -> KotlinReferenceUsageInfo(ref)
else -> null
}
}
internal fun processUsage(
processor: Processor<in UsageInfo>,
element: PsiElement
): Boolean =
processor.processIfNotNull { if (element.isValid) UsageInfo(element) else null }
private fun Processor<in UsageInfo>.processIfNotNull(callback: () -> UsageInfo?): Boolean {
ProgressManager.checkCanceled()
val usageInfo = runReadAction(callback)
return if (usageInfo != null) process(usageInfo) else true
}
internal fun createReferenceProcessor(usageInfoProcessor: Processor<in UsageInfo>): Processor<PsiReference> {
val uniqueProcessor = CommonProcessors.UniqueProcessor(usageInfoProcessor)
return Processor { processUsage(uniqueProcessor, it) }
}
}
}
| apache-2.0 | f35e7fa3732858e589a8c6763790b819 | 35.65625 | 136 | 0.674169 | 5.40553 | false | false | false | false |
vhromada/Catalog | core/src/main/kotlin/com/github/vhromada/catalog/facade/impl/AccountFacadeImpl.kt | 1 | 4539 | package com.github.vhromada.catalog.facade.impl
import com.github.vhromada.catalog.common.entity.Page
import com.github.vhromada.catalog.common.exception.InputException
import com.github.vhromada.catalog.domain.Role
import com.github.vhromada.catalog.entity.Account
import com.github.vhromada.catalog.entity.AccountStatistics
import com.github.vhromada.catalog.entity.ChangeRolesRequest
import com.github.vhromada.catalog.entity.Credentials
import com.github.vhromada.catalog.facade.AccountFacade
import com.github.vhromada.catalog.filter.AccountFilter
import com.github.vhromada.catalog.mapper.AccountMapper
import com.github.vhromada.catalog.service.AccountService
import com.github.vhromada.catalog.service.RoleService
import com.github.vhromada.catalog.validator.AccountValidator
import com.github.vhromada.catalog.validator.RoleValidator
import org.springframework.data.domain.Sort
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Component
/**
* A class represents implementation of facade for accounts.
*
* @author Vladimir Hromada
*/
@Component("accountFacade")
class AccountFacadeImpl(
/**
* Service for accounts
*/
private val accountService: AccountService,
/**
* Service for roles
*/
private val roleService: RoleService,
/**
* Mapper for accounts
*/
private val mapper: AccountMapper,
/**
* Validator for accounts
*/
private val accountValidator: AccountValidator,
/**
* Validator for roles
*/
private val roleValidator: RoleValidator,
/**
* Password encoder
*/
private val encoder: PasswordEncoder
) : AccountFacade {
override fun search(filter: AccountFilter): Page<Account> {
val accounts = accountService.search(filter = mapper.mapFilter(source = filter), pageable = filter.toPageable(sort = Sort.by("id")))
return Page(data = mapper.mapAccounts(source = accounts.content), page = accounts)
}
override fun get(uuid: String): Account {
return mapper.mapAccount(source = accountService.get(uuid = uuid))
}
override fun updateCredentials(uuid: String, credentials: Credentials): Account {
accountValidator.validateCredentials(credentials = credentials)
val account = accountService.get(uuid = uuid)
if (account.username != credentials.username) {
accountService.checkUsername(username = credentials.username!!)
}
account.merge(mapper.mapCredentials(source = credentials))
return mapper.mapAccount(source = accountService.store(account = account))
}
override fun updateRoles(uuid: String, request: ChangeRolesRequest): Account {
roleValidator.validateRequest(request = request)
val account = accountService.get(uuid = uuid)
account.changeRoles(roleList = getRoles(roles = request.roles))
return mapper.mapAccount(source = accountService.store(account = account))
}
override fun getStatistics(): AccountStatistics {
return AccountStatistics(count = accountService.getCount().toInt())
}
override fun addCredentials(credentials: Credentials): Account {
accountValidator.validateCredentials(credentials = credentials)
accountService.checkUsername(username = credentials.username!!)
val account = mapper.mapCredentials(source = credentials)
account.changeRoles(getRoles(roles = listOf("ROLE_USER")))
return mapper.mapAccount(source = accountService.store(account = account))
}
override fun checkCredentials(credentials: Credentials): Account {
accountValidator.validateCredentials(credentials = credentials)
val account = accountService.find(filter = com.github.vhromada.catalog.domain.filter.AccountFilter(username = credentials.username))
.orElseThrow { InputException(key = "INVALID_CREDENTIALS", message = "Credentials aren't valid.") }
val valid = encoder.matches(credentials.password, account.password)
if (!valid) {
throw InputException(key = "INVALID_CREDENTIALS", message = "Credentials aren't valid.")
}
return mapper.mapAccount(account)
}
/**
* Returns roles.
*
* @param roles role names
* @return roles
* @throws InputException if role doesn't exist in data storage
*/
private fun getRoles(roles: List<String?>?): List<Role> {
return roles!!.filterNotNull().map { roleService.get(name = it) }
}
}
| mit | d4b14abfd1234edca518867af5e0e379 | 38.815789 | 140 | 0.721304 | 4.655385 | false | false | false | false |
googlemaps/android-places-demos | demo-kotlin/app/src/gms/java/com/example/placesdemo/model/GeocodingResult.kt | 1 | 3896 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.example.placesdemo.model
import java.io.Serializable
import java.util.*
class GeocodingResult : Serializable {
/**
* The human-readable address of this location.
*
*
* Often this address is equivalent to the "postal address," which sometimes differs from
* country to country. (Note that some countries, such as the United Kingdom, do not allow
* distribution of true postal addresses due to licensing restrictions.) This address is generally
* composed of one or more address components. For example, the address "111 8th Avenue, New York,
* NY" contains separate address components for "111" (the street number, "8th Avenue" (the
* route), "New York" (the city) and "NY" (the US state). These address components contain
* additional information.
*/
var formattedAddress: String? = null
/**
* All the localities contained in a postal code. This is only present when the result is a postal
* code that contains multiple localities.
*/
var postcodeLocalities: Array<String>? = null
/** Location information for this result. */
var geometry: Geometry? = null
/**
* The types of the returned result. This array contains a set of zero or more tags identifying
* the type of feature returned in the result. For example, a geocode of "Chicago" returns
* "locality" which indicates that "Chicago" is a city, and also returns "political" which
* indicates it is a political entity.
*/
var types: Array<AddressType>? = null
/**
* Indicates that the geocoder did not return an exact match for the original request, though it
* was able to match part of the requested address. You may wish to examine the original request
* for misspellings and/or an incomplete address.
*
*
* Partial matches most often occur for street addresses that do not exist within the locality
* you pass in the request. Partial matches may also be returned when a request matches two or
* more locations in the same locality. For example, "21 Henr St, Bristol, UK" will return a
* partial match for both Henry Street and Henrietta Street. Note that if a request includes a
* misspelled address component, the geocoding service may suggest an alternate address.
* Suggestions triggered in this way will not be marked as a partial match.
*/
var partialMatch = false
/** A unique identifier for this place. */
var placeId: String? = null
/** The Plus Code identifier for this place. */
var plusCode: PlusCode? = null
override fun toString(): String {
val sb = StringBuilder("[GeocodingResult")
if (partialMatch) {
sb.append(" PARTIAL MATCH")
}
sb.append(" placeId=").append(placeId)
sb.append(" ").append(geometry)
sb.append(", formattedAddress=").append(formattedAddress)
sb.append(", types=").append(Arrays.toString(types))
if (postcodeLocalities != null && postcodeLocalities!!.size > 0) {
sb.append(", postcodeLocalities=").append(Arrays.toString(postcodeLocalities))
}
sb.append("]")
return sb.toString()
}
companion object {
private const val serialVersionUID = 1L
}
} | apache-2.0 | 2cae8333cfe904a9c13b574b174f293e | 41.824176 | 102 | 0.687115 | 4.452571 | false | false | false | false |
allotria/intellij-community | platform/platform-api/src/com/intellij/openapi/rd/DisposableEx.kt | 2 | 2247 | // 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.
@file:JvmName("DisposableEx")
package com.intellij.openapi.rd
import com.intellij.openapi.Disposable
import com.intellij.openapi.util.Disposer
import com.jetbrains.rd.util.lifetime.Lifetime
import com.jetbrains.rd.util.lifetime.LifetimeDefinition
import com.jetbrains.rd.util.lifetime.isAlive
import com.jetbrains.rd.util.lifetime.onTermination
import org.jetbrains.annotations.ApiStatus
@ApiStatus.ScheduledForRemoval(inVersion = "2020.2")
@Deprecated("Use version from `LifetimeDisposableEx`")
fun defineNestedLifetime(disposable: Disposable): LifetimeDefinition {
val lifetimeDefinition = Lifetime.Eternal.createNested()
if (Disposer.isDisposed(disposable)) {
lifetimeDefinition.terminate()
return lifetimeDefinition
}
disposable.attach { if (lifetimeDefinition.lifetime.isAlive) lifetimeDefinition.terminate() }
return lifetimeDefinition
}
@ApiStatus.ScheduledForRemoval(inVersion = "2020.2")
@Deprecated("Use version from `LifetimeDisposableEx`")
internal fun doIfAlive(disposable: Disposable, action: (Lifetime) -> Unit) {
val disposableLifetime: Lifetime?
if (Disposer.isDisposed(disposable)) {
return
}
try {
disposableLifetime = defineNestedLifetime(disposable).lifetime
}
catch (t: Throwable) {
//do nothing, there is no other way to handle disposables
return
}
action(disposableLifetime)
}
@ApiStatus.ScheduledForRemoval(inVersion = "2020.2")
@Deprecated("Use version from `LifetimeDisposableEx`")
internal fun Lifetime.createNestedDisposable(debugName: String = "lifetimeToDisposable"): Disposable {
val d = Disposer.newDisposable(debugName)
this.onTermination {
Disposer.dispose(d)
}
return d
}
@Suppress("ObjectLiteralToLambda")
/**
* Executes the given action when this disposable will be disposed
* @throws com.intellij.util.IncorrectOperationException if this disposable is being disposed or is already disposed
* @see Disposer.register
*/
inline fun Disposable.attach(crossinline disposable: () -> Unit) {
Disposer.register(this, object : Disposable {
override fun dispose() {
disposable()
}
})
} | apache-2.0 | dabb555afe0870ce56bc716bb4402303 | 32.552239 | 140 | 0.772586 | 4.423228 | false | false | false | false |
allotria/intellij-community | platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/sync/Context.kt | 2 | 7802 | // 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.intellij.build.images.sync
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.io.createDirectories
import org.jetbrains.intellij.build.images.ImageExtension
import java.io.File
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.function.Consumer
import kotlin.concurrent.thread
internal class Context(private val errorHandler: Consumer<String> = Consumer { error(it) },
private val devIconsVerifier: Consumer<Collection<Path>>? = null) {
companion object {
const val iconsCommitHashesToSyncArg = "sync.icons.commits"
private const val iconsRepoArg = "icons.repo"
}
var devRepoDir: Path
var iconRepoDir: Path
val iconsRepoName: String
val devRepoName: String
val skipDirsPattern: String?
val doSyncIconsRepo: Boolean
val doSyncDevRepo: Boolean
val doSyncRemovedIconsInDev: Boolean
private val failIfSyncDevIconsRequired: Boolean
val notifySlack: Boolean
val byDev = Changes()
val byCommit = mutableMapOf<String, Changes>()
val consistent: MutableCollection<String> = mutableListOf()
var icons: Map<String, GitObject> = emptyMap()
var devIcons: Map<String, GitObject> = emptyMap()
var devCommitsToSync: Map<Path, Collection<CommitInfo>> = emptyMap()
var iconsCommitsToSync: Map<Path, Collection<CommitInfo>> = emptyMap()
val iconsCommitHashesToSync: MutableSet<String>
val devIconsCommitHashesToSync: MutableSet<String>
val devIconsSyncAll: Boolean
init {
val devRepoArg = "dev.repo"
val iconsRepoNameArg = "icons.repo.name"
val iconsRepoPathArg = "icons.repo.path"
val devRepoNameArg = "dev.repo.name"
val patternArg = "skip.dirs.pattern"
val syncIconsArg = "sync.icons"
val syncDevIconsArg = "sync.dev.icons"
val syncRemovedIconsInDevArg = "sync.dev.icons.removed"
val failIfSyncDevIconsRequiredArg = "fail.if.sync.dev.icons.required"
val assignInvestigationArg = "assign.investigation"
val notifySlackArg = "notify.slack"
val devIconsSyncAllArg = "sync.dev.icons.all"
@Suppress("unused")
fun usage() = println("""
|Usage: -D$devRepoArg=<devRepoDir> -D$iconsRepoArg=<iconsRepoDir> [-Doption=...]
|Options:
|* `$iconsRepoArg` - designers' repo
|* `$devRepoArg` - developers' repo
|* `$iconsRepoPathArg` - path in designers' repo
|* `$iconsRepoNameArg` - designers' repo name (for report)
|* `$devRepoNameArg` - developers' repo name (for report)
|* `$patternArg` - regular expression for names of directories to skip
|* `$syncDevIconsArg` - sync icons in developers' repo. Switch off to run check only
|* `$syncIconsArg` - sync icons in designers' repo. Switch off to run check only
|* `$syncRemovedIconsInDevArg` - remove icons in developers' repo removed by designers
|* `$failIfSyncDevIconsRequiredArg` - do fail if icons sync in developers' repo is required
|* `$assignInvestigationArg` - assign investigation if required
|* `$notifySlackArg` - notify slack channel if required
|* `$iconsCommitHashesToSyncArg` - commit hashes in designers' repo to sync icons from, implies $syncDevIconsArg
|* `$devIconsSyncAllArg` - sync all changes from developers' repo to designers' repo, implies $syncIconsArg
""".trimMargin())
fun bool(arg: String) = System.getProperty(arg)?.toBoolean() ?: false
fun commits(arg: String): MutableSet<String> {
return System.getProperty(arg)
?.takeIf { it.trim() != "*" }
?.split(",", ";", " ")
?.filter { it.isNotBlank() }
?.mapTo(mutableSetOf(), String::trim) ?: mutableSetOf()
}
devRepoDir = findDirectoryIgnoringCase(System.getProperty(devRepoArg)) ?: {
warn("$devRepoArg not found")
Paths.get(System.getProperty("user.dir"))
}()
val iconsRepoRelativePath = System.getProperty(iconsRepoPathArg) ?: ""
val iconsRepoRootDir = findDirectoryIgnoringCase(System.getProperty(iconsRepoArg)) ?: cloneIconsRepoToTempDir()
iconRepoDir = iconsRepoRootDir.resolve(iconsRepoRelativePath)
iconRepoDir.createDirectories()
iconsRepoName = System.getProperty(iconsRepoNameArg) ?: "icons repo"
devRepoName = System.getProperty(devRepoNameArg) ?: "dev repo"
skipDirsPattern = System.getProperty(patternArg)
doSyncDevRepo = bool(syncDevIconsArg)
doSyncIconsRepo = bool(syncIconsArg)
failIfSyncDevIconsRequired = bool(failIfSyncDevIconsRequiredArg)
notifySlack = bool(notifySlackArg)
iconsCommitHashesToSync = commits(iconsCommitHashesToSyncArg)
doSyncRemovedIconsInDev = bool(syncRemovedIconsInDevArg) || iconsCommitHashesToSync.isNotEmpty()
// scheduled build is always full check
devIconsSyncAll = bool(devIconsSyncAllArg) || isScheduled()
// read TeamCity provided changes
devIconsCommitHashesToSync = System.getProperty("teamcity.build.changedFiles.file")
// if icons sync is required
?.takeIf { doSyncIconsRepo }
// or full check is not required
?.takeIf { !devIconsSyncAll }
?.let(::File)
?.takeIf(File::exists)
?.let(FileUtil::loadFile)
?.takeIf { !it.contains("<personal>") }
?.let(StringUtil::splitByLines)
?.mapNotNull {
val split = it.split(':')
if (split.size != 3) {
warn("malformed line in 'teamcity.build.changedFiles.file' : $it")
return@mapNotNull null
}
val (file, _, commit) = split
if (ImageExtension.fromName(file) != null) commit else null
}?.toMutableSet() ?: mutableSetOf()
}
val iconRepo: Path by lazy {
findGitRepoRoot(iconRepoDir)
}
val devRepoRoot: Path by lazy {
findGitRepoRoot(devRepoDir)
}
private fun cloneIconsRepoToTempDir(): Path {
val uri = "ssh://[email protected]/IntelliJIcons.git"
log("$iconsRepoArg not found. Have to perform full clone of $uri")
val tmp = Files.createTempDirectory("icons-sync")
Runtime.getRuntime().addShutdownHook(thread(start = false) {
tmp.toFile().deleteRecursively()
})
return callWithTimer("Cloning $uri into $tmp") { gitClone(uri, tmp) }
}
val byDesigners = Changes(includeRemoved = doSyncRemovedIconsInDev)
val devIconsFilter: (Path) -> Boolean by lazy {
val skipDirsRegex = skipDirsPattern?.toRegex()
val testRoots = searchTestRoots(devRepoRoot.toAbsolutePath().toString())
log("Found ${testRoots.size} test roots")
return@lazy { file: Path ->
filterDevIcon(file, testRoots, skipDirsRegex, this)
}
}
var iconFilter: (Path) -> Boolean = { Icon(it).isValid }
fun devChanges() = byDev.all()
fun iconsChanges() = byDesigners.all()
fun iconsSyncRequired() = devChanges().isNotEmpty()
fun devSyncRequired() = iconsChanges().isNotEmpty()
fun verifyDevIcons(repos: Collection<Path>) {
try {
devIconsVerifier?.accept(repos)
}
catch (e: Exception) {
doFail("Test failures detected")
}
}
fun doFail(report: String) {
log(report)
errorHandler.accept(report)
}
fun isFail() = notifySlack && failIfSyncDevIconsRequired && devSyncRequired()
private fun findDirectoryIgnoringCase(path: String?): Path? {
if (path == null) {
return null
}
val file = Paths.get(path)
if (Files.isDirectory(file)) {
return file
}
return file.parent?.toFile()?.listFiles()?.firstOrNull {
it.absolutePath.equals(FileUtil.toSystemDependentName(path), ignoreCase = true)
}?.toPath()
}
fun warn(message: String) = System.err.println(message)
} | apache-2.0 | e8a07fb12cd688f36ea53662f7aed62a | 39.015385 | 140 | 0.698667 | 4.029959 | false | false | false | false |
bitsydarel/DBWeather | dbweatherdata/src/main/java/com/dbeginc/dbweatherdata/implementations/datasources/local/news/RoomNewsDataSource.kt | 1 | 3870 | /*
* Copyright (C) 2017 Darel Bitsy
* 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.dbeginc.dbweatherdata.implementations.datasources.local.news
import android.content.Context
import android.support.annotation.RestrictTo
import com.dbeginc.dbweatherdata.implementations.datasources.local.LocalNewsDataSource
import com.dbeginc.dbweatherdata.proxies.mappers.toDomain
import com.dbeginc.dbweatherdata.proxies.mappers.toProxy
import com.dbeginc.dbweatherdomain.entities.news.Article
import com.dbeginc.dbweatherdomain.entities.news.NewsPaper
import com.dbeginc.dbweatherdomain.entities.requests.news.ArticleRequest
import com.dbeginc.dbweatherdomain.entities.requests.news.ArticlesRequest
import io.reactivex.Completable
import io.reactivex.Flowable
import io.reactivex.Maybe
/**
* Created by darel on 04.10.17.
*
* Local News Data NewsPaper Implementation
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
class RoomNewsDataSource private constructor(private val db: RoomNewsDatabase) : LocalNewsDataSource {
companion object {
@JvmStatic
fun create(context: Context): LocalNewsDataSource {
return RoomNewsDataSource(RoomNewsDatabase.createDb(context))
}
}
override fun getArticles(request: ArticlesRequest<String>): Flowable<List<Article>> {
return db.newsDao()
.getArticles(newsPaperId = request.newsPaperId, newsPaperName = request.arg)
.map { articles -> articles.map { article -> article.toDomain() } }
}
override fun getArticle(request: ArticleRequest<Unit>): Flowable<Article> {
return db.newsDao()
.getArticle(newsPaperId = request.newsPaperId, articleUrl = request.url)
.map { article -> article.toDomain() }
}
override fun putArticles(articles: List<Article>): Completable =
Completable.fromAction {
db.newsDao().putArticles(articles.map { article -> article.toProxy() })
}
override fun getNewsPapers(): Flowable<List<NewsPaper>> {
return db.newsDao().getNewsPapers()
.map { newsPapers -> newsPapers.map { it.toDomain() } }
}
override fun defineDefaultSubscribedNewsPapers(newsPapers: List<NewsPaper>): Completable {
return Completable.fromCallable {
db.newsDao().defineDefaultNewsPapers(newsPapers.map { it.toProxy() })
}
}
override fun getSubscribedNewsPapers(): Flowable<List<NewsPaper>> {
return db.newsDao().getSubscribedNewsPapers()
.map { newsPapers -> newsPapers.map { it.toDomain() } }
}
override fun getNewsPaper(name: String): Flowable<NewsPaper> =
db.newsDao().getNewsPaper(name).map { source -> source.toDomain() }
override fun findNewspaper(name: String): Maybe<List<NewsPaper>> =
db.newsDao().findNewsPaperByName(name).map { newsPapers -> newsPapers.map { it.toDomain() } }
override fun updateNewsPaper(newsPaper: NewsPaper): Completable =
Completable.fromAction { db.newsDao().updateNewsPaper(newsPaper.toProxy()) }
override fun putNewsPapers(newsPapers: List<NewsPaper>): Completable =
Completable.fromAction {
db.newsDao().putNewsPapers(
newsPapers.map { source -> source.toProxy() }
)
}
} | gpl-3.0 | bcd56d303ab388bf3de470f61d2cd137 | 39.747368 | 105 | 0.697933 | 4.248079 | false | false | false | false |
stefanosiano/PowerfulImageView | powerfulimageview_rs/src/main/java/com/stefanosiano/powerful_libraries/imageview/extensions/BitmapExtensions.kt | 2 | 365 | package com.stefanosiano.powerful_libraries.imageview.extensions
import android.graphics.Bitmap
internal class BitmapExtensions
internal fun Bitmap?.safeWidth(fallbackWidth: Int): Int = if (this == null || isRecycled) fallbackWidth else width
internal fun Bitmap?.safeHeight(fallbackHeight: Int): Int = if (this == null || isRecycled) fallbackHeight else height
| mit | 6374fd848fef712d7fcdc6b7fdafbbf1 | 44.625 | 118 | 0.8 | 4.195402 | false | false | false | false |
leafclick/intellij-community | platform/util-ex/src/com/intellij/diagnostic/startUpMeasurer.kt | 1 | 836 | // 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.diagnostic
inline fun <T> Activity?.runChild(name: String, task: () -> T): T {
val activity = this?.startChild(name)
val result = task()
activity?.end()
return result
}
inline fun <T> runActivity(name: String, category: ActivityCategory = ActivityCategory.APP_INIT, task: () -> T): T {
val activity = createActivity(name, category)
val result = task()
activity.end()
return result
}
@PublishedApi
internal fun createActivity(name: String, category: ActivityCategory): Activity {
return when (category) {
ActivityCategory.MAIN -> StartUpMeasurer.startMainActivity(name)
else -> StartUpMeasurer.startActivity(name, ActivityCategory.APP_INIT)
}
} | apache-2.0 | a89cf1008e7a4efd7afac6c487796efd | 33.875 | 140 | 0.732057 | 4.058252 | false | false | false | false |
peervalhoegen/SudoQ | sudoq-app/sudoqmodel/src/main/kotlin/de/sudoq/model/actionTree/Action.kt | 1 | 2436 | /*
* SudoQ is a Sudoku-App for Adroid Devices with Version 2.2 at least.
* Copyright (C) 2012 Heiko Klare, Julian Geppert, Jan-Bernhard Kordaß, Jonathan Kieling, Tim Zeitz, Timo Abele
* 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.sudoq.model.actionTree
import de.sudoq.model.sudoku.Cell
/**
* This class represents an action that can be applied and reversed on a [Cell].
* @constructor protected to prevent instantiation outside this package.
* @property diff the difference between old and new value. If a cells value is changed from 4 to 6
* then the diff is 2.
* @property cell the [Cell] that this action is associated with
*/
abstract class Action internal constructor(@JvmField var diff: Int, @JvmField val cell: Cell) {
//constuctor was originally package wide through protected
//but there is no kotlin equivalent so it is `internal` now
var XML_ATTRIBUTE_NAME = "Action"
protected set
/**
* Executes the action.
*/
abstract fun execute()
/**
* Reverses the action.
*/
abstract fun undo()
/**
* Returns the id of the cell.
*
* @return the [Cell.id] of the cell associated with this class.
*/
val cellId: Int
get() = cell.id
/**
* {@inheritDoc}
*/
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (javaClass != other.javaClass)
return false
other as Action //TODO make explicit equals for all subclasses instead of comparing javaClass
return diff == other.diff
&& cell == other.cell
}
/**
* Determines whether two actions are inverse to each other.
* @param a another action
* @return whether the passed action is inverse to this one.
*/
abstract fun inverse(a: Action): Boolean
} | gpl-3.0 | a6f1cd928abdfee690fab6f275e9321f | 36.476923 | 243 | 0.681725 | 4.459707 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/hierarchy/calls/callees/kotlinProperty/main0.kt | 13 | 569 | class KA {
val name = "A"
fun foo(s: String): String = "A: $s"
}
fun packageFun(s: String): String = s
val packageVal = ""
class KClient() {
val <caret>bar: String
get() {
fun localFun(s: String): String = packageFun(s)
val localVal = localFun("")
KA().foo(KA().name)
JA().foo(JA().name)
localFun(packageVal)
run {
KA().foo(KA().name)
JA().foo(JA().name)
packageFun(localVal)
}
return ""
}
} | apache-2.0 | 627cab10da3da781c8baf4606cfa51b0 | 19.357143 | 59 | 0.441125 | 3.670968 | false | false | false | false |
smmribeiro/intellij-community | platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/autolink/MockUnlinkedProjectAware.kt | 10 | 1886 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.autolink
import com.intellij.openapi.Disposable
import com.intellij.openapi.externalSystem.autoimport.ExternalSystemProjectId
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.containers.DisposableWrapperList
import java.util.concurrent.atomic.AtomicInteger
class MockUnlinkedProjectAware(
override val systemId: ProjectSystemId,
private val buildFileExtension: String
) : ExternalSystemUnlinkedProjectAware {
private val linkedProjects = HashSet<String>()
private val listeners = DisposableWrapperList<(String) -> Unit>()
val linkCounter = AtomicInteger()
fun getProjectId(projectDirectory: VirtualFile): ExternalSystemProjectId {
return ExternalSystemProjectId(systemId, projectDirectory.path)
}
override fun isBuildFile(project: Project, buildFile: VirtualFile) = isBuildFile(buildFile)
fun isBuildFile(buildFile: VirtualFile): Boolean {
return buildFile.extension == buildFileExtension
}
override fun isLinkedProject(project: Project, externalProjectPath: String): Boolean {
return externalProjectPath in linkedProjects
}
override fun linkAndLoadProject(project: Project, externalProjectPath: String) = linkProject(externalProjectPath)
fun linkProject(externalProjectPath: String) {
linkCounter.incrementAndGet()
linkedProjects.add(externalProjectPath)
listeners.forEach { it(externalProjectPath) }
}
override fun subscribe(project: Project, listener: ExternalSystemProjectLinkListener, parentDisposable: Disposable) {
listeners.add(listener::onProjectLinked, parentDisposable)
}
} | apache-2.0 | 5943549b04c4fe82fa133d206a67b162 | 41.886364 | 158 | 0.811771 | 5.069892 | false | false | false | false |
mdaniel/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/MainEntityListImpl.kt | 1 | 5533 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class MainEntityListImpl: MainEntityList, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
@JvmField var _x: String? = null
override val x: String
get() = _x!!
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: MainEntityListData?): ModifiableWorkspaceEntityBase<MainEntityList>(), MainEntityList.Builder {
constructor(): this(MainEntityListData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity MainEntityList is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isXInitialized()) {
error("Field MainEntityList#x should be initialized")
}
if (!getEntityData().isEntitySourceInitialized()) {
error("Field MainEntityList#entitySource should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var x: String
get() = getEntityData().x
set(value) {
checkModificationAllowed()
getEntityData().x = value
changedProperty.add("x")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override fun getEntityData(): MainEntityListData = result ?: super.getEntityData() as MainEntityListData
override fun getEntityClass(): Class<MainEntityList> = MainEntityList::class.java
}
}
class MainEntityListData : WorkspaceEntityData<MainEntityList>() {
lateinit var x: String
fun isXInitialized(): Boolean = ::x.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<MainEntityList> {
val modifiable = MainEntityListImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): MainEntityList {
val entity = MainEntityListImpl()
entity._x = x
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return MainEntityList::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as MainEntityListData
if (this.x != other.x) return false
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as MainEntityListData
if (this.x != other.x) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + x.hashCode()
return result
}
} | apache-2.0 | 2b8c589e46ae1415e1c3b5b0258c4d43 | 33.160494 | 125 | 0.638352 | 5.968716 | false | false | false | false |
VREMSoftwareDevelopment/WiFiAnalyzer | app/src/main/kotlin/com/vrem/wifianalyzer/wifi/filter/Filter.kt | 1 | 4126 | /*
* WiFiAnalyzer
* Copyright (C) 2015 - 2022 VREM Software Development <[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.vrem.wifianalyzer.wifi.filter
import android.app.AlertDialog
import android.content.DialogInterface
import com.vrem.wifianalyzer.MainContext
import com.vrem.wifianalyzer.R
import com.vrem.wifianalyzer.navigation.NavigationMenu
class Filter(val alertDialog: AlertDialog?) {
private var ssidFilter: SSIDFilter? = null
internal var wiFiBandFilter: WiFiBandFilter? = null
private set
internal var strengthFilter: StrengthFilter? = null
private set
internal var securityFilter: SecurityFilter? = null
private set
fun show() {
if (alertDialog != null && !alertDialog.isShowing) {
alertDialog.show()
wiFiBandFilter = addWiFiBandFilter(alertDialog)
ssidFilter = addSSIDFilter(alertDialog)
strengthFilter = addStrengthFilter(alertDialog)
securityFilter = addSecurityFilter(alertDialog)
}
}
private fun addSSIDFilter(alertDialog: AlertDialog): SSIDFilter =
SSIDFilter(MainContext.INSTANCE.filtersAdapter.ssidAdapter(), alertDialog)
private fun addWiFiBandFilter(alertDialog: AlertDialog): WiFiBandFilter? =
if (NavigationMenu.ACCESS_POINTS == MainContext.INSTANCE.mainActivity.currentNavigationMenu()) {
WiFiBandFilter(MainContext.INSTANCE.filtersAdapter.wiFiBandAdapter(), alertDialog)
} else null
private fun addStrengthFilter(alertDialog: AlertDialog): StrengthFilter =
StrengthFilter(MainContext.INSTANCE.filtersAdapter.strengthAdapter(), alertDialog)
private fun addSecurityFilter(alertDialog: AlertDialog): SecurityFilter =
SecurityFilter(MainContext.INSTANCE.filtersAdapter.securityAdapter(), alertDialog)
private class Close : DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface, which: Int) {
dialog.dismiss()
MainContext.INSTANCE.filtersAdapter.reload()
}
}
private class Apply : DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface, which: Int) {
dialog.dismiss()
MainContext.INSTANCE.filtersAdapter.save()
MainContext.INSTANCE.mainActivity.update()
}
}
private class Reset : DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface, which: Int) {
dialog.dismiss()
MainContext.INSTANCE.filtersAdapter.reset()
MainContext.INSTANCE.mainActivity.update()
}
}
companion object {
fun build(): Filter {
return Filter(buildAlertDialog())
}
private fun buildAlertDialog(): AlertDialog? {
if (MainContext.INSTANCE.mainActivity.isFinishing) {
return null
}
val view = MainContext.INSTANCE.layoutInflater.inflate(R.layout.filter_popup, null)
return AlertDialog.Builder(view.context)
.setView(view)
.setTitle(R.string.filter_title)
.setIcon(R.drawable.ic_filter_list)
.setNegativeButton(R.string.filter_reset, Reset())
.setNeutralButton(R.string.filter_close, Close())
.setPositiveButton(R.string.filter_apply, Apply())
.create()
}
}
} | gpl-3.0 | 482384353bdb60740236ef250cbbafea | 39.067961 | 108 | 0.677169 | 5.056373 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/jps/jps-plugin/src/org/jetbrains/kotlin/jps/targets/KotlinJvmModuleBuildTarget.kt | 1 | 15432 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.jps.targets
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.StandardFileSystems
import com.intellij.util.containers.FileCollectionFactory
import com.intellij.util.io.URLUtil
import org.jetbrains.jps.ModuleChunk
import org.jetbrains.jps.builders.java.JavaBuilderUtil
import org.jetbrains.jps.builders.storage.BuildDataPaths
import org.jetbrains.jps.incremental.*
import org.jetbrains.jps.model.java.JpsJavaExtensionService
import org.jetbrains.jps.model.module.JpsSdkDependency
import org.jetbrains.jps.service.JpsServiceManager
import org.jetbrains.kotlin.build.GeneratedFile
import org.jetbrains.kotlin.build.GeneratedJvmClass
import org.jetbrains.kotlin.build.JvmBuildMetaInfo
import org.jetbrains.kotlin.build.JvmSourceRoot
import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.compilerRunner.JpsCompilerEnvironment
import org.jetbrains.kotlin.compilerRunner.JpsKotlinCompilerRunner
import org.jetbrains.kotlin.config.IncrementalCompilation
import org.jetbrains.kotlin.config.Services
import org.jetbrains.kotlin.incremental.*
import org.jetbrains.kotlin.incremental.components.ExpectActualTracker
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.jps.build.KotlinBuilder
import org.jetbrains.kotlin.jps.build.KotlinCompileContext
import org.jetbrains.kotlin.jps.build.KotlinDirtySourceFilesHolder
import org.jetbrains.kotlin.jps.incremental.JpsIncrementalCache
import org.jetbrains.kotlin.jps.incremental.JpsIncrementalJvmCache
import org.jetbrains.kotlin.jps.model.k2JvmCompilerArguments
import org.jetbrains.kotlin.jps.model.kotlinCompilerSettings
import org.jetbrains.kotlin.load.kotlin.incremental.components.IncrementalCache
import org.jetbrains.kotlin.load.kotlin.incremental.components.IncrementalCompilationComponents
import org.jetbrains.kotlin.modules.KotlinModuleXmlBuilder
import org.jetbrains.kotlin.modules.TargetId
import org.jetbrains.kotlin.utils.keysToMap
import org.jetbrains.org.objectweb.asm.ClassReader
import java.io.File
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import kotlin.io.path.exists
import kotlin.io.path.extension
import kotlin.io.path.notExists
private const val JVM_BUILD_META_INFO_FILE_NAME = "jvm-build-meta-info.txt"
class KotlinJvmModuleBuildTarget(kotlinContext: KotlinCompileContext, jpsModuleBuildTarget: ModuleBuildTarget) :
KotlinModuleBuildTarget<JvmBuildMetaInfo>(kotlinContext, jpsModuleBuildTarget) {
override val isIncrementalCompilationEnabled: Boolean
get() = IncrementalCompilation.isEnabledForJvm()
override fun createCacheStorage(paths: BuildDataPaths) =
JpsIncrementalJvmCache(jpsModuleBuildTarget, paths, kotlinContext.fileToPathConverter)
override val buildMetaInfoFactory
get() = JvmBuildMetaInfo
override val buildMetaInfoFileName
get() = JVM_BUILD_META_INFO_FILE_NAME
override val targetId: TargetId
get() {
val moduleName = module.k2JvmCompilerArguments.moduleName
return if (moduleName != null) TargetId(moduleName, jpsModuleBuildTarget.targetType.typeId)
else super.targetId
}
override fun makeServices(
builder: Services.Builder,
incrementalCaches: Map<KotlinModuleBuildTarget<*>, JpsIncrementalCache>,
lookupTracker: LookupTracker,
exceptActualTracer: ExpectActualTracker
) {
super.makeServices(builder, incrementalCaches, lookupTracker, exceptActualTracer)
with(builder) {
register(
IncrementalCompilationComponents::class.java,
@Suppress("UNCHECKED_CAST")
IncrementalCompilationComponentsImpl(
incrementalCaches.mapKeys { it.key.targetId } as Map<TargetId, IncrementalCache>
)
)
}
}
override fun compileModuleChunk(
commonArguments: CommonCompilerArguments,
dirtyFilesHolder: KotlinDirtySourceFilesHolder,
environment: JpsCompilerEnvironment
): Boolean {
require(chunk.representativeTarget == this)
if (chunk.targets.size > 1) {
environment.messageCollector.report(
CompilerMessageSeverity.STRONG_WARNING,
"Circular dependencies are only partially supported. " +
"The following modules depend on each other: ${chunk.presentableShortName}. " +
"Kotlin will compile them, but some strange effect may happen"
)
}
val filesSet = dirtyFilesHolder.allDirtyFiles
val moduleFile = generateChunkModuleDescription(dirtyFilesHolder)
if (moduleFile == null) {
if (KotlinBuilder.LOG.isDebugEnabled) {
KotlinBuilder.LOG.debug(
"Not compiling, because no files affected: " + chunk.presentableShortName
)
}
// No Kotlin sources found
return false
}
val module = chunk.representativeTarget.module
if (KotlinBuilder.LOG.isDebugEnabled) {
val totalRemovedFiles = dirtyFilesHolder.allRemovedFilesFiles.size
KotlinBuilder.LOG.debug(
"Compiling to JVM ${filesSet.size} files"
+ (if (totalRemovedFiles == 0) "" else " ($totalRemovedFiles removed files)")
+ " in " + chunk.presentableShortName
)
}
try {
val compilerRunner = JpsKotlinCompilerRunner()
compilerRunner.runK2JvmCompiler(
commonArguments,
module.k2JvmCompilerArguments,
module.kotlinCompilerSettings,
environment,
moduleFile
)
} finally {
if (System.getProperty(DELETE_MODULE_FILE_PROPERTY) != "false") {
moduleFile.delete()
}
}
return true
}
override fun registerOutputItems(outputConsumer: ModuleLevelBuilder.OutputConsumer, outputItems: List<GeneratedFile>) {
if (kotlinContext.isInstrumentationEnabled) {
val (classFiles, nonClassFiles) = outputItems.partition { it is GeneratedJvmClass }
super.registerOutputItems(outputConsumer, nonClassFiles)
for (output in classFiles) {
val bytes = output.outputFile.readBytes()
val binaryContent = BinaryContent(bytes)
val compiledClass = CompiledClass(output.outputFile, output.sourceFiles, ClassReader(bytes).className, binaryContent)
outputConsumer.registerCompiledClass(jpsModuleBuildTarget, compiledClass)
}
} else {
super.registerOutputItems(outputConsumer, outputItems)
}
}
private fun generateChunkModuleDescription(dirtyFilesHolder: KotlinDirtySourceFilesHolder): File? {
val builder = KotlinModuleXmlBuilder()
var hasDirtySources = false
val targets = chunk.targets
val outputDirs = targets.map { it.outputDir }.toSet()
for (target in targets) {
target as KotlinJvmModuleBuildTarget
val outputDir = target.outputDir
val friendDirs = target.friendOutputDirs
val sources = target.collectSourcesToCompile(dirtyFilesHolder)
if (sources.logFiles()) {
hasDirtySources = true
}
val kotlinModuleId = target.targetId
val allFiles = sources.allFiles
val commonSourceFiles = sources.crossCompiledFiles
builder.addModule(
kotlinModuleId.name,
outputDir.absolutePath,
preprocessSources(allFiles),
target.findSourceRoots(dirtyFilesHolder.context),
target.findClassPathRoots(),
preprocessSources(commonSourceFiles),
target.findModularJdkRoot(),
kotlinModuleId.type,
isTests,
// this excludes the output directories from the class path, to be removed for true incremental compilation
outputDirs,
friendDirs
)
}
if (!hasDirtySources) return null
val scriptFile = createTempFileForChunkModuleDesc()
FileUtil.writeToFile(scriptFile, builder.asText().toString())
return scriptFile
}
/**
* Internal API for source level code preprocessors.
*
* Currently used in https://plugins.jetbrains.com/plugin/13355-spot-profiler-for-java
*/
interface SourcesPreprocessor {
/**
* Preprocess some sources and return path to the resulting file.
* This function should be pure and should return the same output for given input
* (required for incremental compilation).
*/
fun preprocessSources(srcFiles: List<File>): List<File>
}
fun preprocessSources(srcFiles: List<File>): List<File> {
var result = srcFiles
JpsServiceManager.getInstance().getExtensions(SourcesPreprocessor::class.java).forEach {
result = it.preprocessSources(result)
}
return result
}
private fun createTempFileForChunkModuleDesc(): File {
val readableSuffix = buildString {
append(StringUtil.sanitizeJavaIdentifier(chunk.representativeTarget.module.name))
if (chunk.containsTests) {
append("-test")
}
}
fun createTempFile(dir: Path?, prefix: String?, suffix: String?): Path =
if (dir != null) Files.createTempFile(dir, prefix, suffix) else Files.createTempFile(prefix, suffix)
val dir = System.getProperty("kotlin.jps.dir.for.module.files")?.let { Paths.get(it) }?.takeIf { Files.isDirectory(it) }
return try {
createTempFile(dir, "kjps", readableSuffix + ".script.xml")
} catch (e: IOException) {
// sometimes files cannot be created, because file name is too long (Windows, Mac OS)
// see https://bugs.openjdk.java.net/browse/JDK-8148023
try {
createTempFile(dir, "kjps", ".script.xml")
} catch (e: IOException) {
val message = buildString {
append("Could not create module file when building chunk $chunk")
if (dir != null) {
append(" in dir $dir")
}
}
throw RuntimeException(message, e)
}
}.toFile()
}
private fun findClassPathRoots(): Collection<File> = allDependencies.classes().roots.filter { file ->
val path = file.toPath()
if (path.notExists()) {
val extension = path.extension
// Don't filter out files, we want to report warnings about absence through the common place
if (extension != "class" && extension != "jar") {
return@filter false
}
}
true
}
private fun findModularJdkRoot(): File? {
// List of paths to JRE modules in the following format:
// jrt:///Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home!/java.base
val urls = JpsJavaExtensionService.dependencies(module)
.satisfying { dependency -> dependency is JpsSdkDependency }
.classes().urls
val url = urls.firstOrNull { it.startsWith(StandardFileSystems.JRT_PROTOCOL_PREFIX) } ?: return null
return File(url.substringAfter(StandardFileSystems.JRT_PROTOCOL_PREFIX).substringBeforeLast(URLUtil.JAR_SEPARATOR))
}
private fun findSourceRoots(context: CompileContext): List<JvmSourceRoot> {
val roots = context.projectDescriptor.buildRootIndex.getTargetRoots(jpsModuleBuildTarget, context)
val result = mutableListOf<JvmSourceRoot>()
for (root in roots) {
val file = root.rootFile
val prefix = root.packagePrefix
if (file.toPath().exists()) {
result.add(JvmSourceRoot(file, prefix.ifEmpty { null }))
}
}
return result
}
override fun updateCaches(
dirtyFilesHolder: KotlinDirtySourceFilesHolder,
jpsIncrementalCache: JpsIncrementalCache,
files: List<GeneratedFile>,
changesCollector: ChangesCollector,
environment: JpsCompilerEnvironment
) {
super.updateCaches(dirtyFilesHolder, jpsIncrementalCache, files, changesCollector, environment)
updateIncrementalCache(files, jpsIncrementalCache as IncrementalJvmCache, changesCollector, null)
}
override val globalLookupCacheId: String
get() = "jvm"
override fun updateChunkMappings(
localContext: CompileContext,
chunk: ModuleChunk,
dirtyFilesHolder: KotlinDirtySourceFilesHolder,
outputItems: Map<ModuleBuildTarget, Iterable<GeneratedFile>>,
incrementalCaches: Map<KotlinModuleBuildTarget<*>, JpsIncrementalCache>
) {
val previousMappings = localContext.projectDescriptor.dataManager.mappings
val callback = JavaBuilderUtil.getDependenciesRegistrar(localContext)
val targetDirtyFiles: Map<ModuleBuildTarget, Set<File>> = chunk.targets.keysToMap {
val files = HashSet<File>()
files.addAll(dirtyFilesHolder.getRemovedFiles(it))
files.addAll(dirtyFilesHolder.getDirtyFiles(it).keys)
files
}
fun getOldSourceFiles(target: ModuleBuildTarget, generatedClass: GeneratedJvmClass): Set<File> {
val cache = incrementalCaches[kotlinContext.targetsBinding[target]] ?: return emptySet()
cache as JpsIncrementalJvmCache
val className = generatedClass.outputClass.className
if (!cache.isMultifileFacade(className)) return emptySet()
val name = previousMappings.getName(className.internalName)
return previousMappings.getClassSources(name)?.toSet() ?: emptySet()
}
for ((target, outputs) in outputItems) {
for (output in outputs) {
if (output !is GeneratedJvmClass) continue
val sourceFiles = FileCollectionFactory.createCanonicalFileSet()
sourceFiles.addAll(getOldSourceFiles(target, output))
sourceFiles.removeAll(targetDirtyFiles[target] ?: emptySet())
sourceFiles.addAll(output.sourceFiles)
callback.associate(
FileUtil.toSystemIndependentName(output.outputFile.canonicalPath),
sourceFiles.map { FileUtil.toSystemIndependentName(it.canonicalPath) },
ClassReader(output.outputClass.fileContents)
)
}
}
val allCompiled = dirtyFilesHolder.allDirtyFiles
JavaBuilderUtil.registerFilesToCompile(localContext, allCompiled)
JavaBuilderUtil.registerSuccessfullyCompiled(localContext, allCompiled)
}
} | apache-2.0 | 495c313aeed7ee695d639046ef59f4c0 | 40.375335 | 158 | 0.671008 | 5.121806 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/internal/makeBackup/CreateIncrementalCompilationBackup.kt | 1 | 7450 | // 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.internal.makeBackup
import com.intellij.compiler.server.BuildManager
import com.intellij.history.core.RevisionsCollector
import com.intellij.history.integration.LocalHistoryImpl
import com.intellij.history.integration.patches.PatchCreator
import com.intellij.ide.actions.RevealFileAction
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vcs.changes.Change
import com.intellij.util.WaitForProgressToShow
import com.intellij.util.io.ZipUtil
import org.jetbrains.kotlin.idea.KotlinJvmBundle
import org.jetbrains.kotlin.idea.util.application.runReadAction
import java.io.File
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.*
import java.util.zip.ZipOutputStream
class CreateIncrementalCompilationBackup : AnAction(KotlinJvmBundle.message("create.backup.for.debugging.kotlin.incremental.compilation")) {
companion object {
const val BACKUP_DIR_NAME = ".backup"
const val PATCHES_TO_CREATE = 5
const val PATCHES_FRACTION = .25
const val LOGS_FRACTION = .05
const val PROJECT_SYSTEM_FRACTION = .05
const val ZIP_FRACTION = 1.0 - PATCHES_FRACTION - LOGS_FRACTION - PROJECT_SYSTEM_FRACTION
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val projectBaseDir = File(project.baseDir!!.path)
val backupDir = File(FileUtil.createTempDirectory("makeBackup", null), BACKUP_DIR_NAME)
ProgressManager.getInstance().run(
object : Task.Backgroundable(
project,
KotlinJvmBundle.message("creating.backup.for.debugging.kotlin.incremental.compilation"),
true
) {
override fun run(indicator: ProgressIndicator) {
createPatches(backupDir, project, indicator)
copyLogs(backupDir, indicator)
copyProjectSystemDir(backupDir, project, indicator)
zipProjectDir(backupDir, project, projectBaseDir, indicator)
}
}
)
}
private fun createPatches(backupDir: File, project: Project, indicator: ProgressIndicator) {
runReadAction {
val localHistoryImpl = LocalHistoryImpl.getInstanceImpl()!!
val gateway = localHistoryImpl.gateway!!
val localHistoryFacade = localHistoryImpl.facade
val revisionsCollector = RevisionsCollector(
localHistoryFacade,
gateway.createTransientRootEntry(),
project.baseDir!!.path,
project.locationHash,
null
)
var patchesCreated = 0
val patchesDir = File(backupDir, "patches")
patchesDir.mkdirs()
val revisions = revisionsCollector.result!!
for (rev in revisions) {
val label = rev.label
if (label != null && label.startsWith(HISTORY_LABEL_PREFIX)) {
val patchFile = File(patchesDir, label.removePrefix(HISTORY_LABEL_PREFIX) + ".patch")
indicator.text = KotlinJvmBundle.message("creating.patch.0", patchFile)
indicator.fraction = PATCHES_FRACTION * patchesCreated / PATCHES_TO_CREATE
val differences = revisions[0].getDifferencesWith(rev)!!
val changes = differences.map { d ->
Change(d.getLeftContentRevision(gateway), d.getRightContentRevision(gateway))
}
PatchCreator.create(project, changes, patchFile.toPath(), false, null)
if (++patchesCreated >= PATCHES_TO_CREATE) {
break
}
}
}
}
}
private fun copyLogs(backupDir: File, indicator: ProgressIndicator) {
indicator.text = KotlinJvmBundle.message("copying.logs")
indicator.fraction = PATCHES_FRACTION
val logsDir = File(backupDir, "logs")
FileUtil.copyDir(File(PathManager.getLogPath()), logsDir)
indicator.fraction = PATCHES_FRACTION + LOGS_FRACTION
}
private fun copyProjectSystemDir(backupDir: File, project: Project, indicator: ProgressIndicator) {
indicator.text = KotlinJvmBundle.message("copying.project.s.system.dir")
indicator.fraction = PATCHES_FRACTION
val projectSystemDir = File(backupDir, "project-system")
FileUtil.copyDir(BuildManager.getInstance().getProjectSystemDirectory(project)!!, projectSystemDir)
indicator.fraction = PATCHES_FRACTION + LOGS_FRACTION + PROJECT_SYSTEM_FRACTION
}
private fun zipProjectDir(backupDir: File, project: Project, projectDir: File, indicator: ProgressIndicator) {
// files and relative paths
val files = ArrayList<Pair<File, String>>() // files and relative paths
var totalBytes = 0L
for (dir in listOf(projectDir, backupDir.parentFile!!)) {
FileUtil.processFilesRecursively(
dir,
/*processor*/ {
if (it!!.isFile
&& !it.name.endsWith(".hprof")
&& !(it.name.startsWith("make_backup_") && it.name.endsWith(".zip"))
) {
indicator.text = KotlinJvmBundle.message("scanning.project.dir.0", it)
files.add(Pair(it, FileUtil.getRelativePath(dir, it)!!))
totalBytes += it.length()
}
true
},
/*directoryFilter*/ {
val name = it!!.name
name != ".git" && name != "out"
}
)
}
val backupFile = File(projectDir, "make_backup_" + SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(Date()) + ".zip")
val zos = ZipOutputStream(FileOutputStream(backupFile))
var processedBytes = 0L
zos.use {
for ((file, relativePath) in files) {
indicator.text = KotlinJvmBundle.message("adding.file.to.backup.0", relativePath)
indicator.fraction = PATCHES_FRACTION + LOGS_FRACTION + processedBytes.toDouble() / totalBytes * ZIP_FRACTION
ZipUtil.addFileToZip(zos, file, relativePath, null, null)
processedBytes += file.length()
}
}
FileUtil.delete(backupDir)
WaitForProgressToShow.runOrInvokeLaterAboveProgress(
{
RevealFileAction.showDialog(
project,
KotlinJvmBundle.message("successfully.created.backup.0", backupFile.absolutePath),
KotlinJvmBundle.message("created.backup"),
backupFile,
null
)
}, null, project
)
}
}
| apache-2.0 | 29becd9e6da66c22357b37552b6a8cb5 | 38.839572 | 158 | 0.620537 | 5.057705 | false | false | false | false |
dowenliu-xyz/ketcd | ketcd-core/src/main/kotlin/xyz/dowenliu/ketcd/client/EtcdKVService.kt | 1 | 8956 | package xyz.dowenliu.ketcd.client
import com.google.common.util.concurrent.ListenableFuture
import com.google.protobuf.ByteString
import xyz.dowenliu.ketcd.api.*
import xyz.dowenliu.ketcd.kv.Txn
import xyz.dowenliu.ketcd.option.CompactOption
import xyz.dowenliu.ketcd.option.DeleteOption
import xyz.dowenliu.ketcd.option.GetOption
import xyz.dowenliu.ketcd.option.PutOption
/**
* Interface of kv service talking to etcd.
*
* create at 2017/4/16
* @author liufl
* @since 0.1.0
*/
interface EtcdKVService : AutoCloseable {
/**
* The client which created this service.
*/
val client: EtcdClient
/**
* Puts the given key into the key-value store (blocking).
* A put request increments the revision of the key-value store and generates one event in the event history.
*
* @param key key of the key/value pair to store.
* @param value value of the key/value pair to store.
* @param options put request options.
* @return [PutResponse]
*/
fun put(key: ByteString, value: ByteString, options: PutOption = PutOption.DEFAULT): PutResponse
/**
* Puts the given key into the key-value store in future.
* A put request increments the revision of the key-value store and generates one event in the event history.
*
* @param key key of the key/value pair to store.
* @param value value of the key/value pair to store.
* @param options put request options.
* @return [ListenableFuture] of [PutResponse]
*/
fun putInFuture(key: ByteString, value: ByteString, options: PutOption = PutOption.DEFAULT): ListenableFuture<PutResponse>
/**
* Puts the given key into the key-value store (asynchronously).
* A put request increments the revision of the key-value store and generates one event in the event history.
*
* @param key key of the key/value pair to store.
* @param value value of the key/value pair to store.
* @param options put request options.
* @param callback A [ResponseCallback] to handle the response.
*/
fun putAsync(key: ByteString, value: ByteString, options: PutOption = PutOption.DEFAULT, callback: ResponseCallback<PutResponse>)
/**
* Gets the key/value pair of key or the key/value pairs in the range from the key-value store (blocking).
*
* @param key the key, or the range start, or the prefix.
* If it's '\u0000' and _endKey_ of the [options] is also '\u0000', all keys will be return
* (but limited by _limit_ option).
* @param options get request options
* @return [RangeResponse]
*/
fun get(key: ByteString, options: GetOption = GetOption.DEFAULT): RangeResponse
/**
* Gets the key/value pair of key or the key/value pairs in the range from the key-value store in future.
*
* @param key the key, or the range start, or the prefix.
* If it's '\u0000' and _endKey_ of the [options] is also '\u0000', all keys will be return
* (but limited by _limit_ option).
* @param options get request options
* @return [ListenableFuture] of [RangeResponse]
*/
fun getInFuture(key: ByteString, options: GetOption = GetOption.DEFAULT): ListenableFuture<RangeResponse>
/**
* Gets the key/value pair of key or the key/value pairs in the range from the key-value store (asynchronously).
*
* @param key the key, or the range start, or the prefix.
* If it's '\u0000' and _endKey_ of the [options] is also '\u0000', all keys will be return
* (but limited by _limit_ option).
* @param options get request options
* @param callback A [ResponseCallback] to handle the response.
*/
fun getAsync(key: ByteString, options: GetOption = GetOption.DEFAULT, callback: ResponseCallback<RangeResponse>)
/**
* Deletes one or the given range from the key-value store (blocking).
* A delete request increments the revision of the key-value store and
* generates a delete event in the event history for every deleted key.
*
* @param key the key, or the range start, or the prefix.
* If it's '\u0000' and _endKey_ of the [options] is also '\u0000', all keys will be deleted.
* @param options delete request options
* @return [DeleteRangeResponse]
*/
fun delete(key: ByteString, options: DeleteOption = DeleteOption.DEFAULT): DeleteRangeResponse
/**
* Deletes one or the given range from the key-value store in future.
* A delete request increments the revision of the key-value store and
* generates a delete event in the event history for every deleted key.
*
* @param key the key, or the range start, or the prefix.
* If it's '\u0000' and _endKey_ of the [options] is also '\u0000', all keys will be deleted.
* @param options delete request options
* @return [ListenableFuture] of [DeleteRangeResponse]
*/
fun deleteInFuture(key: ByteString, options: DeleteOption = DeleteOption.DEFAULT): ListenableFuture<DeleteRangeResponse>
/**
* Deletes one or the given range from the key-value store (asynchronously).
* A delete request increments the revision of the key-value store and
* generates a delete event in the event history for every deleted key.
*
* @param key the key, or the range start, or the prefix.
* If it's '\u0000' and _endKey_ of the [options] is also '\u0000', all keys will be deleted.
* @param options delete request options
* @param callback A [ResponseCallback] to handle the response.
*/
fun deleteAsync(key: ByteString, options: DeleteOption = DeleteOption.DEFAULT, callback: ResponseCallback<DeleteRangeResponse>)
/**
* Compacts the event history in the etcd key-value store (blocking).
* The key-value store should be periodically compacted or the event history will continue to grow indefinitely.
*
* Notes that: you CAN NOT compact at the same revision more tha once. Take care when you call this function
* without options, as it will always compact at revision 0.
*
* @param options compact request options.
* @return [CompactionResponse]
*/
fun compact(options: CompactOption = CompactOption.DEFAULT): CompactionResponse
/**
* Compacts the event history in the etcd key-value store in future.
* The key-value store should be periodically compacted or the event history will continue to grow indefinitely.
*
* Notes that: you CAN NOT compact at the same revision more tha once. Take care when you call this function
* without options, as it will always compact at revision 0.
*
* @param options compact request options.
* @return [ListenableFuture] of [CompactionResponse]
*/
fun compactInFuture(options: CompactOption = CompactOption.DEFAULT): ListenableFuture<CompactionResponse>
/**
* Compacts the event history in the etcd key-value store (asynchronously).
* The key-value store should be periodically compacted or the event history will continue to grow indefinitely.
*
* Notes that: you CAN NOT compact at the same revision more tha once. Take care when you call this function
* without options, as it will always compact at revision 0.
*
* @param options compact request options.
* @param callback A [ResponseCallback] to handle the response.
*/
fun compactAsync(options: CompactOption = CompactOption.DEFAULT, callback: ResponseCallback<CompactionResponse>)
/**
* Processes multiple requests in a single transaction (blocking).
* A txn request increments the revision of the key-value store and
* generates events with the same revision for every completed request.
* It is not allowed to modify the same key several times within one txn.
*
* @param txn Predicate that create a [TxnRequest]
* @return [TxnResponse]
*/
fun commit(txn: Txn): TxnResponse
/**
* Processes multiple requests in a single transaction in future.
* A txn request increments the revision of the key-value store and
* generates events with the same revision for every completed request.
* It is not allowed to modify the same key several times within one txn.
*
* @param txn Predicate that create a [TxnRequest]
* @return [ListenableFuture] of [TxnResponse]
*/
fun commitInFuture(txn: Txn): ListenableFuture<TxnResponse>
/**
* Processes multiple requests in a single transaction (asynchronously).
* A txn request increments the revision of the key-value store and
* generates events with the same revision for every completed request.
* It is not allowed to modify the same key several times within one txn.
*
* @param txn Predicate that create a [TxnRequest]
* @param callback A [ResponseCallback] to handle the response.
*/
fun commitAsync(txn: Txn, callback: ResponseCallback<TxnResponse>)
} | apache-2.0 | 66b2f1ae0b3b269914054242b911d24a | 45.409326 | 133 | 0.696963 | 4.314066 | false | true | false | false |
JetBrains/kotlin-native | performance/cinterop/src/main/kotlin-native/org/jetbrains/cinteropBenchmarks/structsBenchmark.kt | 4 | 2898 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.structsBenchmarks
import kotlinx.cinterop.*
import platform.posix.*
import kotlin.math.sqrt
const val benchmarkSize = 10000
actual fun structBenchmark() {
memScoped {
val containsFunction = staticCFunction<CPointer<ElementS>?, CPointer<ElementS>?, Int> { first, second ->
if (first == null || second == null) {
0
} else if (first.pointed.string.toKString().contains(second.pointed.string.toKString())) {
1
}
else {
0
}
}
val elementsList = mutableListOf<ElementS>()
// Fill list.
for (i in 1..benchmarkSize) {
val element = alloc<ElementS>()
element.floatValue = i + sqrt(i.toDouble()).toFloat()
element.integer = i.toLong()
sprintf(element.string, "%d", i)
element.contains = containsFunction
elementsList.add(element)
}
val summary = elementsList.map { multiplyElementS(it.readValue(), (0..10).random()) }
.reduce { acc, it -> sumElementSPtr(acc.ptr, it.ptr)!!.pointed.readValue() }
val intValue = summary.useContents { integer }
elementsList.last().contains!!(elementsList.last().ptr, elementsList.first().ptr)
}
}
actual fun unionBenchmark() {
memScoped {
val elementsList = mutableListOf<ElementU>()
// Fill list.
for (i in 1..benchmarkSize) {
val element = alloc<ElementU>()
element.integer = i.toLong()
elementsList.add(element)
}
elementsList.forEach {
it.floatValue = it.integer + sqrt(it.integer.toDouble()).toFloat()
}
val summary = elementsList.map { multiplyElementU(it.readValue(), (0..10).random()) }
.reduce { acc, it -> sumElementUPtr(acc.ptr, it.ptr)!!.pointed.readValue() }
summary.useContents { integer }
}
}
actual fun enumBenchmark() {
val days = arrayOf("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
val enumValues = mutableListOf<WeekDay>()
for (i in 1..benchmarkSize) {
enumValues.add(getWeekDay(days[(0..6).random()]))
}
enumValues.forEach {
isWeekEnd(it)
}
} | apache-2.0 | 2f10439fba86891b89f73b3e53de0276 | 34.790123 | 112 | 0.614217 | 4.206096 | false | false | false | false |
BijoySingh/Quick-Note-Android | base/src/main/java/com/maubis/scarlet/base/database/NotesProvider.kt | 1 | 2609 | package com.maubis.scarlet.base.database
import com.maubis.scarlet.base.config.ApplicationBase
import com.maubis.scarlet.base.core.note.INoteContainer
import com.maubis.scarlet.base.database.room.note.Note
import com.maubis.scarlet.base.database.room.note.NoteDao
import com.maubis.scarlet.base.note.applySanityChecks
import java.util.concurrent.ConcurrentHashMap
class NotesProvider {
val notes = ConcurrentHashMap<String, Note>()
fun notifyInsertNote(note: Note) {
maybeLoadFromDB()
notes[note.uuid] = note
}
fun notifyDelete(note: Note) {
maybeLoadFromDB()
notes.remove(note.uuid)
}
fun getCount(): Int {
maybeLoadFromDB()
return notes.size
}
fun getUUIDs(): List<String> {
maybeLoadFromDB()
return notes.values.map { it.uuid }
}
fun getAll(): List<Note> {
maybeLoadFromDB()
return notes.values.toList()
}
fun getByNoteState(states: Array<String>): List<Note> {
maybeLoadFromDB()
return notes.values.filter { states.contains(it.state) }
}
fun getNoteByLocked(locked: Boolean): List<Note> {
maybeLoadFromDB()
return notes.values.filter { it.locked == locked }
}
fun getNoteByTag(uuid: String): List<Note> {
maybeLoadFromDB()
return notes.values.filter { it.tags?.contains(uuid) ?: false }
}
fun getNoteCountByTag(uuid: String): Int {
maybeLoadFromDB()
return notes.values.count { it.tags?.contains(uuid) ?: false }
}
fun getNoteCountByFolder(uuid: String): Int {
maybeLoadFromDB()
return notes.values.count { it.folder == uuid }
}
fun getNotesByFolder(uuid: String): List<Note> {
maybeLoadFromDB()
return notes.values.filter { it.folder == uuid }
}
fun getByID(uid: Int): Note? {
maybeLoadFromDB()
return notes.values.firstOrNull { it.uid == uid }
}
fun getByUUID(uuid: String): Note? {
maybeLoadFromDB()
return notes[uuid]
}
fun getAllUUIDs(): List<String> {
maybeLoadFromDB()
return notes.keys.toList()
}
fun getLastTimestamp(): Long {
maybeLoadFromDB()
return notes.values.map { it.updateTimestamp }.max() ?: 0
}
fun unlockAll() {
maybeLoadFromDB()
}
fun existingMatch(noteContainer: INoteContainer): Note? {
maybeLoadFromDB()
return getByUUID(noteContainer.uuid())
}
@Synchronized
fun maybeLoadFromDB() {
if (notes.isNotEmpty()) {
return
}
database().all.forEach {
it.applySanityChecks()
notes[it.uuid] = it
}
}
fun clear() {
notes.clear()
}
fun database(): NoteDao {
return ApplicationBase.instance.database().notes()
}
} | gpl-3.0 | 90284129b8de82de5a39328d87480be0 | 21.5 | 67 | 0.675355 | 3.700709 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/jvm-debugger/core-fe10/src/org/jetbrains/kotlin/idea/debugger/stepping/smartStepInto/SmartStepTargetVisitor.kt | 1 | 15668 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.stepping.smartStepInto
import com.intellij.debugger.actions.MethodSmartStepTarget
import com.intellij.debugger.actions.SmartStepTarget
import com.intellij.openapi.application.runReadAction
import com.intellij.psi.PsiMethod
import com.intellij.util.Range
import com.intellij.util.containers.OrderedSet
import org.jetbrains.kotlin.builtins.functions.FunctionInvokeDescriptor
import org.jetbrains.kotlin.builtins.isBuiltinFunctionalType
import org.jetbrains.kotlin.builtins.isFunctionType
import org.jetbrains.kotlin.builtins.isSuspendFunctionType
import org.jetbrains.kotlin.codegen.intrinsics.IntrinsicMethods
import org.jetbrains.kotlin.config.JvmTarget
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.base.facet.platform.platform
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.debugger.core.breakpoints.isInlineOnly
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.load.java.isFromJava
import org.jetbrains.kotlin.platform.jvm.JdkPlatform
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.util.getParentCall
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.isInlineClassType
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.SimpleType
import org.jetbrains.kotlin.types.checker.isSingleClassifierType
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
// TODO support class initializers, local functions, delegated properties with specified type, setter for properties
class SmartStepTargetVisitor(
private val element: KtElement,
private val lines: Range<Int>,
private val consumer: OrderedSet<SmartStepTarget>
) : KtTreeVisitorVoid() {
private fun append(target: SmartStepTarget) {
consumer += target
}
private val intrinsicMethods = run {
val jvmTarget = element.platform.firstIsInstanceOrNull<JdkPlatform>()?.targetVersion ?: JvmTarget.DEFAULT
IntrinsicMethods(jvmTarget)
}
override fun visitLambdaExpression(lambdaExpression: KtLambdaExpression) {
recordFunction(lambdaExpression.functionLiteral)
}
override fun visitNamedFunction(function: KtNamedFunction) {
if (!recordFunction(function)) {
super.visitNamedFunction(function)
}
}
override fun visitCallableReferenceExpression(expression: KtCallableReferenceExpression) {
recordCallableReference(expression)
super.visitCallableReferenceExpression(expression)
}
private fun recordCallableReference(expression: KtCallableReferenceExpression) {
val bindingContext = expression.analyze(BodyResolveMode.PARTIAL)
val resolvedCall = expression.callableReference.getResolvedCall(bindingContext) ?: return
when (val descriptor = resolvedCall.resultingDescriptor) {
is FunctionDescriptor -> recordFunctionReference(expression, descriptor)
is PropertyDescriptor -> recordGetter(expression, descriptor, bindingContext)
}
}
private fun recordFunctionReference(expression: KtCallableReferenceExpression, descriptor: FunctionDescriptor) {
val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(element.project, descriptor)
if (descriptor.isFromJava && declaration is PsiMethod) {
append(MethodSmartStepTarget(declaration, null, expression, true, lines))
} else if (declaration is KtNamedFunction) {
val label = KotlinMethodSmartStepTarget.calcLabel(descriptor)
append(
KotlinMethodReferenceSmartStepTarget(
lines,
expression,
label,
declaration,
CallableMemberInfo(descriptor)
)
)
}
}
private fun recordGetter(expression: KtExpression, descriptor: PropertyDescriptor, bindingContext: BindingContext) {
val getterDescriptor = descriptor.getter
if (getterDescriptor == null || getterDescriptor.isDefault) return
val ktDeclaration = DescriptorToSourceUtilsIde.getAnyDeclaration(element.project, getterDescriptor) as? KtDeclaration ?: return
val delegatedResolvedCall = bindingContext[BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, getterDescriptor]
if (delegatedResolvedCall != null) {
val delegatedPropertyGetterDescriptor = delegatedResolvedCall.resultingDescriptor
val delegateDeclaration = DescriptorToSourceUtilsIde.getAnyDeclaration(
element.project, delegatedPropertyGetterDescriptor
) as? KtDeclarationWithBody ?: return
val label = "${descriptor.name}." + KotlinMethodSmartStepTarget.calcLabel(delegatedPropertyGetterDescriptor)
appendPropertyFilter(delegatedPropertyGetterDescriptor, delegateDeclaration, label, expression, lines)
} else {
if (ktDeclaration is KtPropertyAccessor && ktDeclaration.hasBody()) {
val label = KotlinMethodSmartStepTarget.calcLabel(getterDescriptor)
appendPropertyFilter(getterDescriptor, ktDeclaration, label, expression, lines)
}
}
}
private fun appendPropertyFilter(
descriptor: CallableMemberDescriptor,
declaration: KtDeclarationWithBody,
label: String,
expression: KtExpression,
lines: Range<Int>
) {
val methodInfo = CallableMemberInfo(descriptor)
when (expression) {
is KtCallableReferenceExpression ->
append(
KotlinMethodReferenceSmartStepTarget(
lines,
expression,
label,
declaration,
methodInfo
)
)
else -> {
val ordinal = countExistingMethodCalls(declaration)
append(
KotlinMethodSmartStepTarget(
lines,
expression,
label,
declaration,
ordinal,
methodInfo
)
)
}
}
}
private fun recordFunction(function: KtFunction): Boolean {
val (parameter, resultingDescriptor) = function.getParameterAndResolvedCallDescriptor() ?: return false
val target = createSmartStepTarget(function, parameter, resultingDescriptor)
if (target != null) {
append(target)
return true
}
return false
}
private fun createSmartStepTarget(
function: KtFunction,
parameter: ValueParameterDescriptor,
resultingDescriptor: CallableMemberDescriptor
): KotlinLambdaSmartStepTarget? {
val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(element.project, resultingDescriptor) as? KtDeclaration ?: return null
val callerMethodOrdinal = countExistingMethodCalls(declaration)
if (parameter.isSamLambdaParameterDescriptor()) {
val methodDescriptor = parameter.type.getFirstAbstractMethodDescriptor() ?: return null
return KotlinLambdaSmartStepTarget(
function,
declaration,
lines,
KotlinLambdaInfo(
resultingDescriptor,
parameter,
callerMethodOrdinal,
methodDescriptor.containsInlineClassInValueArguments(),
methodDescriptor.name.asString(),
(methodDescriptor as? FunctionDescriptor)?.isSuspend ?: false
)
)
}
return KotlinLambdaSmartStepTarget(
function,
declaration,
lines,
KotlinLambdaInfo(
resultingDescriptor,
parameter,
callerMethodOrdinal,
parameter.type.arguments.any { it.type.isInlineClassType() }
)
)
}
private fun countExistingMethodCalls(declaration: KtDeclaration): Int {
return consumer
.filterIsInstance<KotlinMethodSmartStepTarget>()
.count {
val targetDeclaration = it.getDeclaration()
targetDeclaration != null && targetDeclaration === declaration
}
}
override fun visitObjectLiteralExpression(expression: KtObjectLiteralExpression) {
// Skip calls in object declarations
}
override fun visitIfExpression(expression: KtIfExpression) {
expression.condition?.accept(this)
}
override fun visitWhileExpression(expression: KtWhileExpression) {
expression.condition?.accept(this)
}
override fun visitDoWhileExpression(expression: KtDoWhileExpression) {
expression.condition?.accept(this)
}
override fun visitForExpression(expression: KtForExpression) {
expression.loopRange?.accept(this)
}
override fun visitWhenExpression(expression: KtWhenExpression) {
expression.subjectExpression?.accept(this)
}
override fun visitArrayAccessExpression(expression: KtArrayAccessExpression) {
super.visitArrayAccessExpression(expression)
recordFunctionCall(expression)
}
override fun visitUnaryExpression(expression: KtUnaryExpression) {
super.visitUnaryExpression(expression)
recordFunctionCall(expression.operationReference)
}
override fun visitBinaryExpression(expression: KtBinaryExpression) {
super.visitBinaryExpression(expression)
recordFunctionCall(expression.operationReference)
}
override fun visitCallExpression(expression: KtCallExpression) {
val calleeExpression = expression.calleeExpression
if (calleeExpression != null) {
recordFunctionCall(calleeExpression)
}
super.visitCallExpression(expression)
}
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
val bindingContext = expression.analyze(BodyResolveMode.PARTIAL)
val resolvedCall = expression.getResolvedCall(bindingContext) ?: return
val propertyDescriptor = resolvedCall.resultingDescriptor as? PropertyDescriptor ?: return
recordGetter(expression, propertyDescriptor, bindingContext)
super.visitSimpleNameExpression(expression)
}
private fun recordFunctionCall(expression: KtExpression) {
val resolvedCall = expression.resolveToCall() ?: return
val descriptor = resolvedCall.resultingDescriptor
if (descriptor !is FunctionDescriptor || isIntrinsic(descriptor)) return
val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(element.project, descriptor)
if (descriptor.isFromJava) {
if (declaration is PsiMethod) {
append(MethodSmartStepTarget(declaration, null, expression, false, lines))
}
} else {
if (declaration == null && !isInvokeInBuiltinFunction(descriptor)) {
return
}
if (declaration !is KtDeclaration?) return
if (descriptor is ConstructorDescriptor && descriptor.isPrimary) {
if (declaration is KtClass && declaration.getAnonymousInitializers().isEmpty()) {
// There is no constructor or init block, so do not show it in smart step into
return
}
}
// We can't step into @InlineOnly callables as there is no LVT, so skip them
if (declaration is KtCallableDeclaration && declaration.isInlineOnly()) {
return
}
val callLabel = KotlinMethodSmartStepTarget.calcLabel(descriptor)
val label = when (descriptor) {
is FunctionInvokeDescriptor -> {
when (expression) {
is KtSimpleNameExpression -> "${runReadAction { expression.text }}.$callLabel"
else -> callLabel
}
}
else -> callLabel
}
val ordinal = if (declaration == null) 0 else countExistingMethodCalls(declaration)
append(
KotlinMethodSmartStepTarget(
lines,
expression,
label,
declaration,
ordinal,
CallableMemberInfo(descriptor)
)
)
}
}
private fun isIntrinsic(descriptor: CallableMemberDescriptor): Boolean {
return intrinsicMethods.getIntrinsic(descriptor) != null
}
}
private fun PropertyAccessorDescriptor.getJvmMethodName(): String {
return DescriptorUtils.getJvmName(this) ?: JvmAbi.getterName(correspondingProperty.name.asString())
}
fun DeclarationDescriptor.getMethodName() =
when (this) {
is ClassDescriptor, is ConstructorDescriptor -> "<init>"
is PropertyAccessorDescriptor -> getJvmMethodName()
else -> name.asString()
}
fun KtFunction.isSamLambda(): Boolean {
val (parameter, _) = getParameterAndResolvedCallDescriptor() ?: return false
return parameter.isSamLambdaParameterDescriptor()
}
private fun ValueParameterDescriptor.isSamLambdaParameterDescriptor(): Boolean {
val type = type
return !type.isFunctionType && !type.isSuspendFunctionType && type is SimpleType && type.isSingleClassifierType
}
private fun KtFunction.getParameterAndResolvedCallDescriptor(): Pair<ValueParameterDescriptor, CallableMemberDescriptor>? {
val context = analyze()
val resolvedCall = getParentCall(context).getResolvedCall(context) ?: return null
val descriptor = resolvedCall.resultingDescriptor as? CallableMemberDescriptor ?: return null
val arguments = resolvedCall.valueArguments
for ((param, argument) in arguments) {
if (argument.arguments.any { getArgumentExpression(it) == this }) {
return Pair(param, descriptor)
}
}
return null
}
private fun getArgumentExpression(it: ValueArgument): KtExpression? {
return (it.getArgumentExpression() as? KtLambdaExpression)?.functionLiteral ?: it.getArgumentExpression()
}
private fun KotlinType.getFirstAbstractMethodDescriptor(): CallableMemberDescriptor? =
memberScope
.getDescriptorsFiltered(DescriptorKindFilter.FUNCTIONS)
.asSequence()
.filterIsInstance<CallableMemberDescriptor>()
.firstOrNull {
it.modality == Modality.ABSTRACT
}
private fun isInvokeInBuiltinFunction(descriptor: DeclarationDescriptor): Boolean {
if (descriptor !is FunctionInvokeDescriptor) return false
val classDescriptor = descriptor.containingDeclaration as? ClassDescriptor ?: return false
return classDescriptor.defaultType.isBuiltinFunctionalType
}
| apache-2.0 | 778ea0c23db7bcfbace6bf0ad609b6f1 | 40.781333 | 158 | 0.680751 | 6.163651 | false | false | false | false |
DSteve595/Put.io | app/src/main/java/com/stevenschoen/putionew/transfers/add/AddTransferActivity.kt | 1 | 11103 | package com.stevenschoen.putionew.transfers.add
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationCompat
import androidx.fragment.app.Fragment
import com.stevenschoen.putionew.NOTIFICATION_CHANNEL_ID_TRANSFERS
import com.stevenschoen.putionew.PutioActivity
import com.stevenschoen.putionew.PutioUtils
import com.stevenschoen.putionew.R
import com.stevenschoen.putionew.model.PutioUploadInterface
import com.stevenschoen.putionew.model.files.PutioFile
import com.stevenschoen.putionew.putioApp
import com.stevenschoen.putionew.transfers.TransfersActivity
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import org.apache.commons.io.FileUtils
import java.io.File
import java.io.IOException
class AddTransferActivity : AppCompatActivity() {
companion object {
const val ACTION_ADDTRANSFER_LINK = "com.stevenschoen.putionew.ADDTRANSFER_LINK"
const val ACTION_ADDTRANSFER_FILE = "com.stevenschoen.putionew.ADDTRANSFER_FILE"
const val EXTRA_PRECHOSEN_DESTINATION_FOLDER = "init_dest_folder"
private const val FRAGTAG_ADDTRANSFER_PICKTYPE = "add_type"
private const val FRAGTAG_ADDTRANSFER_FILE = "file"
private const val FRAGTAG_ADDTRANSFER_LINK = "link"
}
var prechosenDestinationFolder: PutioFile? = null
val hasPrechosenDestinationFolder: Boolean
get() = (intent.extras?.containsKey(EXTRA_PRECHOSEN_DESTINATION_FOLDER)) ?: false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (!putioApp.isLoggedIn) {
startActivity(Intent(this, PutioActivity::class.java))
finish()
return
}
if (intent.hasExtra(EXTRA_PRECHOSEN_DESTINATION_FOLDER)) {
prechosenDestinationFolder = intent.extras.getParcelable(EXTRA_PRECHOSEN_DESTINATION_FOLDER)
}
if (intent != null) {
when (intent.action) {
Intent.ACTION_VIEW -> when (intent.scheme) {
"http", "https", "magnet" -> {
showLinkFragmentIfNotShowing(intent.dataString)
}
"file", "content" -> {
showFileFragmentIfNotShowing(intent.data)
}
}
ACTION_ADDTRANSFER_LINK -> showLinkFragmentIfNotShowing()
ACTION_ADDTRANSFER_FILE -> showFileFragmentIfNotShowing()
else -> showPickTypeFragmentIfNotShowing()
}
} else {
showPickTypeFragmentIfNotShowing()
}
supportFragmentManager.addOnBackStackChangedListener {
if (supportFragmentManager.backStackEntryCount == 0) {
finish()
}
}
}
fun showPickTypeFragmentIfNotShowing() {
if (supportFragmentManager.findFragmentByTag(FRAGTAG_ADDTRANSFER_PICKTYPE) == null) {
val pickTypeFragment = Fragment.instantiate(this, PickTypeFragment::class.java.name) as PickTypeFragment
val transaction = supportFragmentManager.beginTransaction()
transaction.addToBackStack("pick")
pickTypeFragment.show(transaction, FRAGTAG_ADDTRANSFER_PICKTYPE)
}
}
fun showLinkFragmentIfNotShowing(link: String? = null) {
if (supportFragmentManager.findFragmentByTag(FRAGTAG_ADDTRANSFER_LINK) == null) {
val fileFragment = FromUrlFragment.newInstance(this@AddTransferActivity, link)
val transaction = supportFragmentManager.beginTransaction()
transaction.addToBackStack("url")
fileFragment.show(transaction, FRAGTAG_ADDTRANSFER_LINK)
}
}
fun showFileFragmentIfNotShowing(torrentUri: Uri? = null) {
if (supportFragmentManager.findFragmentByTag(FRAGTAG_ADDTRANSFER_FILE) == null) {
val fileFragment = FromFileFragment.newInstance(this@AddTransferActivity, torrentUri)
val transaction = supportFragmentManager.beginTransaction()
transaction.addToBackStack("file")
fileFragment.show(transaction, FRAGTAG_ADDTRANSFER_FILE)
}
}
private fun uploadTransferUrl(link: String, parentId: Long, extract: Boolean) {
val notif = UploadNotif()
notif.start();
val restInterface = putioApp.putioUtils!!.restInterface
restInterface.addTransferUrl(link, extract, parentId).subscribe(
{ response ->
notif.succeeded()
},
{ error ->
notif.failed()
error.printStackTrace()
if (!isDestroyed) {
runOnUiThread {
Toast.makeText(this, "Error: " + error.message, Toast.LENGTH_LONG).show()
}
}
})
}
private fun uploadTransferFile(torrentUri: Uri, parentId: Long) {
val notif = UploadNotif()
notif.start()
val uploadInterface = putioApp.putioUtils!!
.makePutioRestInterface(PutioUtils.uploadBaseUrl)
.create(PutioUploadInterface::class.java)
val file: File
if (torrentUri.scheme == ContentResolver.SCHEME_CONTENT) {
file = File(cacheDir, "upload.torrent")
val cr = contentResolver
try {
FileUtils.copyInputStreamToFile(cr.openInputStream(torrentUri)!!, file)
} catch (e: IOException) {
e.printStackTrace()
notif.failed()
return
}
} else {
file = File(torrentUri.path)
}
val requestBody = RequestBody.create(MediaType.parse("application/x-bittorrent"), file)
val filePart = MultipartBody.Part.createFormData("file", file.name, requestBody)
uploadInterface.uploadFile(filePart, parentId).subscribe({
notif.succeeded()
}, { error ->
notif.failed()
PutioUtils.getRxJavaThrowable(error).printStackTrace()
if (!isDestroyed) {
runOnUiThread {
Toast.makeText(this, "Error: " + error.message, Toast.LENGTH_LONG).show()
}
}
})
}
fun getDestinationFolder(fileOrUrlFragment: BaseFragment?): PutioFile {
prechosenDestinationFolder?.let { return it }
return fileOrUrlFragment!!.destinationPickerFragment!!.destination
}
inner class UploadNotif {
private val notifManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
fun start() {
val notifBuilder = NotificationCompat.Builder(this@AddTransferActivity, NOTIFICATION_CHANNEL_ID_TRANSFERS)
notifBuilder
.setOngoing(true)
.setCategory(NotificationCompat.CATEGORY_PROGRESS)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentTitle(getString(R.string.notification_title_uploading_torrent))
.setSmallIcon(R.drawable.ic_notificon_transfer)
.setTicker(getString(R.string.notification_ticker_uploading_torrent))
.setProgress(1, 0, true)
var notif = notifBuilder.build()
notif.ledARGB = Color.parseColor("#FFFFFF00")
try {
notifManager.notify(1, notif)
} catch (e: IllegalArgumentException) {
notifBuilder
.setContentIntent(
PendingIntent.getActivity(
this@AddTransferActivity, 0, Intent(this@AddTransferActivity, PutioActivity::class.java), 0
)
)
notif = notifBuilder.build()
notif.ledARGB = Color.parseColor("#FFFFFF00")
notifManager.notify(1, notif)
}
}
fun succeeded() {
val notifBuilder = NotificationCompat.Builder(this@AddTransferActivity, NOTIFICATION_CHANNEL_ID_TRANSFERS)
notifBuilder
.setOngoing(false)
.setAutoCancel(true)
.setCategory(NotificationCompat.CATEGORY_PROGRESS)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentTitle(getString(R.string.notification_title_uploaded_torrent))
.setContentText(getString(R.string.notification_body_uploaded_torrent))
.setSmallIcon(R.drawable.ic_notificon_transfer)
val viewTransfersIntent = Intent(this@AddTransferActivity, TransfersActivity::class.java)
viewTransfersIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
notifBuilder
.setContentIntent(
PendingIntent.getActivity(
this@AddTransferActivity, 0, viewTransfersIntent, PendingIntent.FLAG_CANCEL_CURRENT
)
)
// notifBuilder.addAction(R.drawable.ic_notif_watch, "Watch", null) TODO
notifBuilder
.setTicker(getString(R.string.notification_ticker_uploaded_torrent))
.setProgress(0, 0, false)
val notif = notifBuilder.build()
notif.ledARGB = Color.parseColor("#FFFFFF00")
notifManager.notify(1, notif)
}
fun failed() {
val notifBuilder = NotificationCompat.Builder(this@AddTransferActivity, NOTIFICATION_CHANNEL_ID_TRANSFERS)
notifBuilder
.setOngoing(false)
.setAutoCancel(true)
.setCategory(NotificationCompat.CATEGORY_ERROR)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentTitle(getString(R.string.notification_title_error))
.setContentText(getString(R.string.notification_body_error))
.setSmallIcon(R.drawable.ic_notificon_transfer)
val retryNotifIntent = PendingIntent.getActivity(
this@AddTransferActivity, 0, intent, PendingIntent.FLAG_ONE_SHOT
)
notifBuilder
.addAction(
R.drawable.ic_notif_retry,
getString(R.string.notification_button_retry),
retryNotifIntent
)
.setContentIntent(retryNotifIntent)
.setTicker(getString(R.string.notification_ticker_error))
val notif = notifBuilder.build()
notif.ledARGB = Color.parseColor("#FFFFFF00")
notifManager.notify(1, notif)
}
}
override fun onAttachFragment(fragment: Fragment) {
super.onAttachFragment(fragment)
when (fragment.tag) {
FRAGTAG_ADDTRANSFER_PICKTYPE -> {
fragment as PickTypeFragment
fragment.callbacks = object : PickTypeFragment.Callbacks {
override fun onLinkSelected() {
showLinkFragmentIfNotShowing()
}
override fun onFileSelected() {
showFileFragmentIfNotShowing()
}
}
}
FRAGTAG_ADDTRANSFER_LINK -> {
fragment as FromUrlFragment
fragment.callbacks = object : FromUrlFragment.Callbacks {
override fun onLinkSelected(link: String, extract: Boolean) {
uploadTransferUrl(link, getDestinationFolder(fragment).id, extract)
finish()
}
}
}
FRAGTAG_ADDTRANSFER_FILE -> {
fragment as FromFileFragment
fragment.callbacks = object : FromFileFragment.Callbacks {
override fun onFileSelected(torrentUri: Uri) {
uploadTransferFile(torrentUri, getDestinationFolder(fragment).id)
finish()
}
}
}
}
}
}
| mit | 2b19901c552280e7cbc893f7b72b3fb5 | 36.133779 | 112 | 0.689453 | 4.565378 | false | false | false | false |
rabbitmq/rabbitmq-tutorials | kotlin/src/main/kotlin/ReceiveLogs.kt | 1 | 972 | import com.rabbitmq.client.*
class ReceiveLogs {
companion object {
const val EXCHANGE_NAME = "logs"
}
}
fun main(argv: Array<String>) {
val factory = ConnectionFactory()
factory.host = "localhost"
val connection = factory.newConnection()
val channel = connection.createChannel()
channel.exchangeDeclare(ReceiveLogs.EXCHANGE_NAME, BuiltinExchangeType.FANOUT)
val queueName = channel.queueDeclare().queue
channel.queueBind(queueName, ReceiveLogs.EXCHANGE_NAME, "")
println(" [*] Waiting for messages. To exit press CTRL+C")
val consumer = object : DefaultConsumer(channel) {
override fun handleDelivery(consumerTag: String, envelope: Envelope,
properties: AMQP.BasicProperties, body: ByteArray) {
val message = String(body, charset("UTF-8"))
println(" [x] Received '$message'")
}
}
channel.basicConsume(queueName, true, consumer)
} | apache-2.0 | 896808dffa44c1952b897c9ae5e10569 | 31.433333 | 88 | 0.659465 | 4.39819 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/completion/tests-shared/test/org/jetbrains/kotlin/idea/completion/test/AbstractKeywordCompletionTest.kt | 4 | 1555 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.completion.test
import com.intellij.codeInsight.completion.CompletionType
import com.intellij.codeInsight.lookup.LookupElement
import org.jetbrains.kotlin.idea.completion.KeywordLookupObject
import org.jetbrains.kotlin.idea.test.KotlinLightProjectDescriptor
import org.jetbrains.kotlin.idea.test.KotlinProjectDescriptorWithFacet
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
abstract class AbstractKeywordCompletionTest : KotlinFixtureCompletionBaseTestCase() {
override fun getPlatform() = JvmPlatforms.unspecifiedJvmPlatform
override fun defaultCompletionType() = CompletionType.BASIC
override fun complete(completionType: CompletionType, invocationCount: Int): Array<LookupElement>? {
val items = myFixture.complete(completionType) ?: return null
return items.filter { it.`object` is KeywordLookupObject }.toTypedArray()
}
override fun getProjectDescriptor(): KotlinLightProjectDescriptor = when {
"LangLevel10" in fileName() -> KotlinProjectDescriptorWithFacet.KOTLIN_10.apply { replicateToFacetSettings() }
"LangLevel11" in fileName() -> KotlinProjectDescriptorWithFacet.KOTLIN_11.apply { replicateToFacetSettings() }
else -> KotlinProjectDescriptorWithFacet.KOTLIN_STABLE_WITH_MULTIPLATFORM.apply { replicateToFacetSettings() }
}
override fun defaultInvocationCount() = 1
} | apache-2.0 | 98e222e0bdd930048c3a5f7de5784899 | 52.655172 | 158 | 0.796141 | 5.23569 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/IsEnumEntryFactory.kt | 4 | 2442 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
object IsEnumEntryFactory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val element = diagnostic.psiElement.safeAs<KtTypeReference>()?.parent ?: return null
return when (element) {
is KtIsExpression -> if (element.typeReference == null) null else ReplaceWithComparisonFix(element)
is KtWhenConditionIsPattern -> if (element.typeReference == null || element.isNegated) null else RemoveIsFix(element)
else -> null
}
}
private class ReplaceWithComparisonFix(isExpression: KtIsExpression) : KotlinQuickFixAction<KtIsExpression>(isExpression) {
private val comparison = if (isExpression.isNegated) "!=" else "=="
override fun getText() = KotlinBundle.message("replace.with.0", comparison)
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val leftHandSide = element?.leftHandSide ?: return
val typeReference = element?.typeReference?.text ?: return
val binaryExpression = KtPsiFactory(project).createExpressionByPattern("$0 $comparison $1", leftHandSide, typeReference)
element?.replace(binaryExpression)
}
}
private class RemoveIsFix(isPattern: KtWhenConditionIsPattern) : KotlinQuickFixAction<KtWhenConditionIsPattern>(isPattern) {
override fun getText() = KotlinBundle.message("remove.expression", "is")
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val typeReference = element?.typeReference?.text ?: return
element?.replace(KtPsiFactory(project).createWhenCondition(typeReference))
}
}
}
| apache-2.0 | 1d2c90668480298672bff5edb31285ab | 49.875 | 158 | 0.731368 | 5.151899 | false | false | false | false |
GunoH/intellij-community | platform/wsl-impl/src/com/intellij/execution/wsl/WslProxy.kt | 2 | 5437 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.execution.wsl
import com.intellij.openapi.Disposable
import com.intellij.openapi.diagnostic.Logger
import io.ktor.network.selector.ActorSelectorManager
import io.ktor.network.sockets.aSocket
import io.ktor.network.sockets.openReadChannel
import io.ktor.network.sockets.openWriteChannel
import io.ktor.utils.io.ByteReadChannel
import io.ktor.utils.io.ByteWriteChannel
import io.ktor.utils.io.close
import io.ktor.utils.io.jvm.javaio.toByteReadChannel
import io.ktor.utils.io.readUTF8Line
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.ClosedReceiveChannelException
import java.io.IOException
import java.net.InetAddress
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.coroutines.coroutineContext
/**
* The problem is covered here: PY-50689.
*
* Intellij debuggers opens port and waits debugee to connect to it.
* But Windows firewall blocks connections from WSL, so we launch special proxy process that accepts connections from Windows
* and debugee and connects them.
* See `wslproxy.c` readme and there is also svg file there which covers this process.
*
* If you listen [applicationPort] on Windows, create object of this class to open port on WSL [wslIngressPort].
* One instance -- one ingress port
* Any WSL process can connect to [wslIngressPort] and data will be forwarded to your [applicationPort].
* [dispose] this object to stop forwarding.
*
*/
class WslProxy(distro: AbstractWslDistribution, private val applicationPort: Int) : Disposable {
private companion object {
suspend fun connectChannels(source: ByteReadChannel, dest: ByteWriteChannel) {
val buffer = ByteBuffer.allocate(4096)
while (coroutineContext.isActive) {
buffer.rewind()
val bytesRead = source.readAvailable(buffer)
if (bytesRead < 1) {
dest.close()
return
}
buffer.rewind()
try {
dest.writeFully(buffer.array(), 0, bytesRead)
}
catch (e: IOException) {
dest.close()
return
}
}
}
private fun Process.destroyWslProxy() {
try {
outputStream.close() // Closing stream should stop process
}
catch (e: Exception) {
Logger.getInstance(WslProxy::class.java).warn(e)
}
CoroutineScope(Dispatchers.IO).launch {
// Wait for process to die. If not -- kill it
delay(1000)
if (isAlive) {
Logger.getInstance(WslProxy::class.java).warn("Process still alive, destroying")
destroy()
}
val exitCode = exitValue()
if (exitCode != 0) {
Logger.getInstance(WslProxy::class.java).warn("Exit code was $exitCode")
}
}
}
}
val wslIngressPort: Int
private var wslLinuxIp: String
private val scope = CoroutineScope(Dispatchers.IO)
private suspend fun readToBuffer(channel: ByteReadChannel, bufferSize: Int): ByteBuffer {
val buffer = ByteBuffer.allocate(bufferSize).order(ByteOrder.LITTLE_ENDIAN)
try {
channel.readFully(buffer)
}
catch (e: ClosedReceiveChannelException) {
throw Exception("wslproxy closed stream unexpectedly. See idea.log for errors", e)
}
buffer.rewind()
return buffer
}
private suspend fun readPortFromChannel(channel: ByteReadChannel): Int = readToBuffer(channel, 2).short.toUShort().toInt()
init {
val wslCommandLine = runBlocking { distro.getTool("wslproxy") }
val process = Runtime.getRuntime().exec(wslCommandLine.commandLineString)
val log = Logger.getInstance(WslProxy::class.java)
scope.launch {
process.errorStream.toByteReadChannel().readUTF8Line()?.let {
// Collect stderr
log.error(it)
}
}
try {
val stdoutChannel = process.inputStream.toByteReadChannel()
wslLinuxIp = runBlocking {
readToBuffer(stdoutChannel, 4)
}.let { InetAddress.getByAddress(it.array()).hostAddress }
wslIngressPort = runBlocking {
readPortFromChannel(stdoutChannel)
}
// wslproxy.c reports egress port, connect to it
scope.launch {
while (isActive) {
val linuxEgressPort = readPortFromChannel(stdoutChannel)
clientConnected(linuxEgressPort)
}
}.invokeOnCompletion {
process.destroyWslProxy()
}
}
catch (e: Exception) {
process.destroyWslProxy()
scope.cancel()
throw e
}
}
private suspend fun clientConnected(linuxEgressPort: Int) {
val winToLin = scope.async {
aSocket(ActorSelectorManager(scope.coroutineContext)).tcp().connect(wslLinuxIp, linuxEgressPort)
}
val winToWin = scope.async {
aSocket(ActorSelectorManager(scope.coroutineContext)).tcp().connect("127.0.0.1", applicationPort)
}
scope.launch {
val winToLinSocket = winToLin.await()
val winToWinSocket = winToWin.await()
launch(CoroutineName("WinWin->WinLin $linuxEgressPort")) {
connectChannels(winToWinSocket.openReadChannel(), winToLinSocket.openWriteChannel(true))
}
launch(CoroutineName("WinLin->WinWin $applicationPort")) {
connectChannels(winToLinSocket.openReadChannel(), winToWinSocket.openWriteChannel(true))
}
}
}
override fun dispose() {
scope.cancel()
}
}
| apache-2.0 | 89d1c3d7ac4aafa63f5175955fa648f5 | 32.98125 | 125 | 0.69211 | 4.264314 | false | false | false | false |
siosio/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/VcsLogDiffPreview.kt | 1 | 8237 | // 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.vcs.log.ui.frame
import com.intellij.diff.chains.DiffRequestChain
import com.intellij.diff.chains.SimpleDiffRequestChain
import com.intellij.diff.impl.DiffRequestProcessor
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionToolbar
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Splitter
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.changes.*
import com.intellij.openapi.vcs.changes.EditorTabPreview.Companion.registerEscapeHandler
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager
import com.intellij.openapi.vcs.changes.ui.VcsTreeModelData
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.ui.OnePixelSplitter
import com.intellij.util.ui.JBUI
import com.intellij.vcs.log.VcsLogBundle
import com.intellij.vcs.log.impl.CommonUiProperties
import com.intellij.vcs.log.impl.MainVcsLogUiProperties
import com.intellij.vcs.log.impl.VcsLogUiProperties
import com.intellij.vcs.log.impl.VcsLogUiProperties.PropertiesChangeListener
import com.intellij.vcs.log.impl.VcsLogUiProperties.VcsLogUiProperty
import com.intellij.vcs.log.util.VcsLogUiUtil
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import javax.swing.JComponent
import kotlin.math.roundToInt
private fun toggleDiffPreviewOnPropertyChange(uiProperties: VcsLogUiProperties,
parent: Disposable,
showDiffPreview: (Boolean) -> Unit) =
onBooleanPropertyChange(uiProperties, CommonUiProperties.SHOW_DIFF_PREVIEW, parent, showDiffPreview)
private fun toggleDiffPreviewOrientationOnPropertyChange(uiProperties: VcsLogUiProperties,
parent: Disposable,
changeShowDiffPreviewOrientation: (Boolean) -> Unit) =
onBooleanPropertyChange(uiProperties, MainVcsLogUiProperties.DIFF_PREVIEW_VERTICAL_SPLIT, parent, changeShowDiffPreviewOrientation)
private fun onBooleanPropertyChange(uiProperties: VcsLogUiProperties,
property: VcsLogUiProperty<Boolean>,
parent: Disposable,
onPropertyChangeAction: (Boolean) -> Unit) {
val propertiesChangeListener: PropertiesChangeListener = object : PropertiesChangeListener {
override fun <T> onPropertyChanged(p: VcsLogUiProperty<T>) {
if (property == p) {
onPropertyChangeAction(uiProperties.get(property))
}
}
}
uiProperties.addChangeListener(propertiesChangeListener)
Disposer.register(parent, Disposable { uiProperties.removeChangeListener(propertiesChangeListener) })
}
abstract class FrameDiffPreview<D : DiffRequestProcessor>(protected val previewDiff: D,
uiProperties: VcsLogUiProperties,
mainComponent: JComponent,
@NonNls splitterProportionKey: String,
vertical: Boolean = false,
defaultProportion: Float = 0.7f) {
private val previewDiffSplitter: Splitter = OnePixelSplitter(vertical, splitterProportionKey, defaultProportion)
val mainComponent: JComponent
get() = previewDiffSplitter
init {
previewDiffSplitter.firstComponent = mainComponent
toggleDiffPreviewOnPropertyChange(uiProperties, previewDiff, ::showDiffPreview)
toggleDiffPreviewOrientationOnPropertyChange(uiProperties, previewDiff, ::changeDiffPreviewOrientation)
invokeLater { showDiffPreview(uiProperties.get(CommonUiProperties.SHOW_DIFF_PREVIEW)) }
}
abstract fun updatePreview(state: Boolean)
private fun showDiffPreview(state: Boolean) {
previewDiffSplitter.secondComponent = if (state) previewDiff.component else null
previewDiffSplitter.secondComponent?.let {
val defaultMinimumSize = it.minimumSize
val actionButtonSize = ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE
it.minimumSize = JBUI.size(defaultMinimumSize.width.coerceAtMost((actionButtonSize.width * 1.5f).roundToInt()),
defaultMinimumSize.height.coerceAtMost((actionButtonSize.height * 1.5f).roundToInt()))
}
updatePreview(state)
}
private fun changeDiffPreviewOrientation(bottom: Boolean) {
previewDiffSplitter.orientation = bottom
}
}
abstract class EditorDiffPreview(protected val project: Project,
private val owner: Disposable) : DiffPreviewProvider, DiffPreview {
private val previewFileDelegate = lazy { PreviewDiffVirtualFile(this) }
private val previewFile by previewFileDelegate
protected fun init() {
@Suppress("LeakingThis")
addSelectionListener {
if (VcsLogUiUtil.isDiffPreviewInEditor(project) && Registry.`is`("show.diff.preview.as.editor.tab.with.single.click")) {
openPreviewInEditor(false)
}
else {
updatePreview(true)
}
}
}
override fun updatePreview(fromModelRefresh: Boolean) {
if (previewFileDelegate.isInitialized()) {
FileEditorManagerEx.getInstanceEx(project).updateFilePresentation(previewFile)
}
}
override fun setPreviewVisible(isPreviewVisible: Boolean, focus: Boolean) {
if (isPreviewVisible) openPreviewInEditor(focus) else closePreview()
}
fun openPreviewInEditor(focusEditor: Boolean) {
val escapeHandler = Runnable {
closePreview()
val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ChangesViewContentManager.TOOLWINDOW_ID)
toolWindow?.activate({ IdeFocusManager.getInstance(project).requestFocus(getOwnerComponent(), true) }, false)
}
registerEscapeHandler(previewFile, escapeHandler)
EditorTabPreview.openPreview(project, previewFile, focusEditor)
}
fun closePreview() {
if (previewFileDelegate.isInitialized()) {
FileEditorManager.getInstance(project).closeFile(previewFile)
}
}
override fun getOwner(): Disposable = owner
abstract fun getOwnerComponent(): JComponent
abstract fun addSelectionListener(listener: () -> Unit)
}
class VcsLogEditorDiffPreview(project: Project, private val changesBrowser: VcsLogChangesBrowser) :
EditorDiffPreview(project, changesBrowser), ChainBackedDiffPreviewProvider {
init {
init()
}
override fun createDiffRequestProcessor(): DiffRequestProcessor {
val preview = changesBrowser.createChangeProcessor(true)
preview.updatePreview(true)
return preview
}
override fun getEditorTabName(): @Nls String {
val change = VcsLogChangeProcessor.getSelectedOrAll(changesBrowser).userObjectsStream(Change::class.java).findFirst().orElse(null)
return if (change == null) VcsLogBundle.message("vcs.log.diff.preview.editor.empty.tab.name")
else VcsLogBundle.message("vcs.log.diff.preview.editor.tab.name", ChangesUtil.getFilePath(change).name)
}
override fun getOwnerComponent(): JComponent = changesBrowser.preferredFocusedComponent
override fun addSelectionListener(listener: () -> Unit) {
changesBrowser.viewer.addSelectionListener(Runnable {
if (changesBrowser.selectedChanges.isNotEmpty()) {
listener()
}
}, owner)
changesBrowser.addListener(VcsLogChangesBrowser.Listener { updatePreview(true) }, owner)
}
override fun createDiffRequestChain(): DiffRequestChain? {
val producers = VcsTreeModelData.getListSelectionOrAll(changesBrowser.viewer).map {
changesBrowser.getDiffRequestProducer(it, false)
}
return SimpleDiffRequestChain.fromProducers(producers.list, producers.selectedIndex)
}
}
| apache-2.0 | f25e53d91d0c84cbf835f36471f8ef6d | 42.582011 | 140 | 0.730484 | 5.256541 | false | false | false | false |
jwren/intellij-community | platform/lang-impl/src/com/intellij/lang/documentation/ide/ui/ui.kt | 1 | 4137 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("TestOnlyProblems", "DEPRECATION") // KTIJ-19938
package com.intellij.lang.documentation.ide.ui
import com.intellij.codeInsight.documentation.CornerAwareScrollPaneLayout
import com.intellij.codeInsight.documentation.DocumentationManager
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.lang.documentation.LinkData
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.ui.IdeBorderFactory
import com.intellij.ui.SideBorder
import com.intellij.ui.components.JBLayeredPane
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.Nls
import java.awt.Dimension
import javax.swing.JComponent
import javax.swing.JLayeredPane
import javax.swing.JScrollPane
internal val LOG: Logger = Logger.getInstance("#com.intellij.lang.documentation.ide.ui")
/**
* @see com.intellij.find.actions.ShowUsagesAction.ourPopupDelayTimeout
*/
internal const val DEFAULT_UI_RESPONSE_TIMEOUT: Long = 300
@JvmField
internal val FORCED_WIDTH = Key.create<Int>("WidthBasedLayout.width")
internal typealias UISnapshot = () -> Unit
internal fun toolbarComponent(actions: ActionGroup, contextComponent: JComponent): JComponent {
val toolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.JAVADOC_TOOLBAR, actions, true).also {
it.setSecondaryActionsIcon(AllIcons.Actions.More, true)
it.setTargetComponent(contextComponent)
}
return toolbar.component.also {
it.border = IdeBorderFactory.createBorder(UIUtil.getTooltipSeparatorColor(), SideBorder.BOTTOM)
}
}
internal fun actionButton(actions: ActionGroup, contextComponent: JComponent): JComponent {
val presentation = Presentation().also {
it.icon = AllIcons.Actions.More
it.putClientProperty(ActionButton.HIDE_DROPDOWN_ICON, true)
}
val button = object : ActionButton(actions, presentation, ActionPlaces.UNKNOWN, Dimension(20, 20)) {
override fun getDataContext(): DataContext = DataManager.getInstance().getDataContext(contextComponent)
}
button.setNoIconsInPopup(true)
return button
}
internal fun scrollPaneWithCorner(parent: Disposable, scrollPane: JScrollPane, corner: JComponent): JComponent {
val defaultLayout = scrollPane.layout
scrollPane.layout = CornerAwareScrollPaneLayout(corner)
Disposer.register(parent) {
scrollPane.layout = defaultLayout
}
val layeredPane: JLayeredPane = object : JBLayeredPane() {
override fun doLayout() {
val r = bounds
for (component in components) {
if (component === scrollPane) {
component.setBounds(0, 0, r.width, r.height)
}
else if (component === corner) {
val d = component.preferredSize
component.setBounds(r.width - d.width - 2, r.height - d.height - 2, d.width, d.height)
}
else {
error("can't layout unexpected component: $component")
}
}
}
override fun getPreferredSize(): Dimension {
return scrollPane.preferredSize
}
}
layeredPane.setLayer(scrollPane, JLayeredPane.DEFAULT_LAYER)
layeredPane.add(scrollPane)
layeredPane.setLayer(corner, JLayeredPane.PALETTE_LAYER)
layeredPane.add(corner)
return layeredPane
}
internal fun linkChunk(presentableText: @Nls String, links: LinkData): HtmlChunk? {
val externalUrl = links.externalUrl
if (externalUrl != null) {
return DocumentationManager.getLink(presentableText, externalUrl)
?: DocumentationManager.getGenericExternalDocumentationLink(presentableText)
}
val linkUrls = links.linkUrls
if (linkUrls.isNotEmpty()) {
return DocumentationManager.getExternalLinks(presentableText, linkUrls)
?: DocumentationManager.getGenericExternalDocumentationLink(presentableText)
}
return null
}
| apache-2.0 | 0d5a03915e2c61b297214fa53e67a64b | 36.954128 | 120 | 0.766497 | 4.401064 | false | false | false | false |
vovagrechka/fucking-everything | phizdets/phizdetslib/src/phizdets-lib.kt | 1 | 3511 | package phizdetslib
external fun phiEval(code: String): Any?
external fun phiEvalToNative(code: String): Any?
external fun header(x: String)
external fun error_log(message: String, messageType: Int, destination: String)
external fun phiBreakDebugger()
fun phiEvalStar(code: String): Any? {
val code2 = code.replace("*", "$")
return phiEval(code2)
}
//fun <T> phiEval(code: String): T {
// throw UnsupportedOperationException("pizda 5b4295a4-9059-47af-96fc-736e5921dc09")
//}
class PHPArray(val nativeValue: Any?) {
private val path = "Phi::getCurrentEnv()->thisValue->getProperty('nativeValue')->value"
val count: Int get() {
// phiBreakDebugger()
// phiEval("phiPrintln(phiShitToString(Phi::getCurrentEnv()->thisValue->getProperty('nativeValue')->value));")
return phiEval("return count($path);") as Int
}
}
object PhiTools {
inline fun currentEnv(): dynamic {
return phiEvalToNative("return Phi::getCurrentEnv();")
}
fun varCode(name: String): String {
return "Phi::getCurrentEnv()->vars['$name']"
}
inline fun evalExpr(code: String): Any? {
return phiEval("return $code;")
}
inline fun evalExprToNative(code: String): Any? {
return phiEvalToNative("return $code;")
}
fun dumpEnvAndDie(env: dynamic) {
dumpEnv(env)
println("Marvels of bullshit")
exit()
}
fun dumpEnv(env: dynamic) {
val vars = evalExprToNative("${varCode("env")}->vars")
val keys = evalExprToNative("array_keys(${varCode("vars")})")
val keyCount = evalExpr("count(${varCode("keys")})") as Int
for (i in 0 until keyCount) {
val key = evalExpr("${varCode("keys")}[$i]") as String
val value = evalExprToNative("${varCode("vars")}[${varCode("key")}->value]")
val valueClass = evalExpr("get_class(${varCode("value")})") as String
println("key = $key; valueClass = $valueClass")
if (valueClass == "PhiString") {
val string = evalExpr("${varCode("value")}->value") as String
println("string = '$string'")
}
}
}
fun dumpNativeShitAndDie(shit: dynamic) {
dumpNativeShit(shit)
println("Magnificent shit")
exit()
val vars = PHPArray(phiEval("return array_keys(Phi::getCurrentEnv()->vars);"))
log("vars.count = ${vars.count}")
exit()
phiEval("Phi::getCurrentEnv()->shit->keys = array_keys(Phi::getCurrentEnv()->vars);")
val count = phiEval("return count(Phi::getCurrentEnv()->shit->keys);") as Int
for (i in 0 until count) {
val key = phiEval("return Phi::getCurrentEnv()->shit->keys[$i];") as String
log("key = $key")
}
// log("varCount = " + count)
// val shit = phiEval("return var_export(count(Phi::getCurrentEnv()->vars), true);") as String
// log(shit)
log("Waaaaat?")
exit()
}
private fun dumpNativeShit(shit: dynamic) {
val className = evalExpr("get_class(${varCode("shit")})")
check(className == "PhiNativeValue") {"c6cc3ce5-d499-4490-a2d7-9f9cf1c9b957"}
val type = evalExpr("gettype(${varCode("shit")}->value)")
println("type = $type")
}
private fun exit() {
phiEval("exit();")
}
fun log(s: String) {
val logFile = phiEval("return MY_FUCKING_LOG;") as String
error_log(s + "\n", 3, logFile)
}
}
| apache-2.0 | 14e7e39082193c7b84dd06eb84fe4e8a | 29.798246 | 117 | 0.591569 | 3.688025 | false | false | false | false |
YutaKohashi/FakeLineApp | app/src/main/java/jp/yuta/kohashi/fakelineapp/views/adapter/ImageRecyclerViewAdapter.kt | 1 | 2960 | package jp.yuta.kohashi.fakelineapp.views.adapter
import android.content.Context
import android.support.v4.view.ViewCompat
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import jp.yuta.kohashi.fakelineapp.R
import jp.yuta.kohashi.fakelineapp.models.ImageRecyclerItem
import jp.yuta.kohashi.fakelineapp.utils.Util
/**
* Author : yutakohashi
* Project name : FakeLineApp
* Date : 02 / 09 / 2017
*/
class ImageRecyclerViewAdapter(context: Context, items: MutableList<ImageRecyclerItem>) : RecyclerView.Adapter<ImageRecyclerViewAdapter.ImageViewHolder>() {
var mItems: MutableList<ImageRecyclerItem> = items
private val mContext = context
private val mInflater: LayoutInflater = LayoutInflater.from(context)
private var clickAction: ((View, MutableList<ImageRecyclerItem>, Int) -> Unit?)? = null
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ImageViewHolder {
return ImageViewHolder(mInflater.inflate(R.layout.cell_recycler_image, parent, false), viewType)
}
override fun onBindViewHolder(holder: ImageViewHolder, position: Int) {
// TODO UTIL化
Util.strToUri(mItems[position].imgPath, "file")?.let {
Glide.with(mContext).load(it).apply(RequestOptions().apply {
// override(DisplayUtil.displayWidthPixels /2,DisplayUtil.displayHeightPixels/3)
// centerInside()
}).into(holder.imageView)
}
holder.textView.text = mItems[position].title
ViewCompat.setTransitionName(holder.imageView, "image_view" + position.toString())
holder.itemView.setOnClickListener { clickAction?.invoke(holder.itemView, mItems, holder.adapterPosition) }
}
fun setOnClickListener(action: (View, MutableList<ImageRecyclerItem>, Int) -> Unit) {
clickAction = action
}
override fun getItemCount(): Int {
return mItems.size
}
fun add(item: ImageRecyclerItem, notifyDataChanged: Boolean = false) {
mItems.add(item)
if (notifyDataChanged) notifyDataSetChanged()
// mDataChangeAction?.invoke(itemCount)
}
fun clear(notifyDataChanged: Boolean = false) {
mItems.clear()
if (notifyDataChanged) notifyDataSetChanged()
// mDataChangeAction?.invoke(itemCount)
}
fun swap(items: MutableList<ImageRecyclerItem>, notifyDataChanged: Boolean = true) {
mItems = items
if (notifyDataChanged) notifyDataSetChanged()
}
class ImageViewHolder(itemView: View, viewType: Int) : RecyclerView.ViewHolder(itemView) {
val textView: TextView = itemView.findViewById(R.id.textView)
val imageView: ImageView = itemView.findViewById(R.id.imageView)
}
}
| mit | 330fb0c7f947b23be8cba1b50a28e987 | 36.923077 | 156 | 0.717715 | 4.434783 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/propertyAssignmentNoReceiver.kt | 9 | 284 | // "Replace with 'new'" "true"
// WITH_STDLIB
class A {
@Deprecated("msg", ReplaceWith("new"))
var old
get() = new
set(value) {
new = value
}
var new = ""
}
fun foo() {
val a = A()
a.apply {
<caret>old = "foo"
}
} | apache-2.0 | 40bb9a3cd94e434bfa3c16ae536922fb | 13.25 | 42 | 0.433099 | 3.264368 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspections/dfa/Strings.kt | 2 | 424 | // WITH_STDLIB
fun concat(x : Int) {
val data = "Value = " + x
if (<warning descr="Condition 'data.length > 5' is always true">data.length > 5</warning>) { }
}
fun String.removeSuffix(c: Char): String {
val n = this.length
if (n > 1) return this.substring(0, n - 2)
else if (this[<warning descr="Index is always out of bounds">n - 2</warning>] == c) return this.substring(0, n - 2)
else return this
} | apache-2.0 | 8a58ff9e85ab32d5f91e13712a04b2e5 | 37.636364 | 119 | 0.622642 | 3.18797 | false | false | false | false |
Cognifide/gradle-aem-plugin | src/main/kotlin/com/cognifide/gradle/aem/common/instance/service/repository/Node.kt | 1 | 18155 | package com.cognifide.gradle.aem.common.instance.service.repository
import com.cognifide.gradle.aem.common.pkg.PackageDefinition
import com.cognifide.gradle.aem.common.utils.JcrUtil
import com.cognifide.gradle.aem.common.utils.filterNotNull
import com.cognifide.gradle.common.CommonException
import com.cognifide.gradle.common.utils.Formats
import com.fasterxml.jackson.annotation.JsonIgnore
import org.apache.commons.io.FilenameUtils
import org.apache.http.HttpStatus
import java.io.File
import java.io.InputStream
import java.io.Serializable
import java.util.*
/**
* Represents a node stored in JCR content repository.
*/
@Suppress("TooManyFunctions")
class Node(val repository: Repository, val path: String, props: Map<String, Any>? = null) : Serializable {
private val instance = repository.instance
private val http = repository.http
private val project = repository.aem.project
/**
* Cached properties of node.
*/
private var propertiesLoaded = props?.let { Properties(this, filterMetaProperties(props)) }
/**
* Cached node existence check result.
*/
private var existsCheck: Boolean? = null
/**
* Node name
*/
val name: String get() = path.substringAfterLast("/")
/**
* File node base name.
*/
@get:JsonIgnore
val baseName: String get() = FilenameUtils.getBaseName(name)
/**
* File node extension.
*/
@get:JsonIgnore
val extension: String get() = FilenameUtils.getExtension(name)
/**
* JCR node properties.
*
* Keep in mind that these values are loaded lazily and sometimes it is needed to reload them
* using dedicated method.
*/
val properties: Properties get() = propertiesLoaded ?: reloadProperties()
/**
* JCR primary type of node.
*/
@get:JsonIgnore
val type: String get() = properties.string("jcr:primaryType")!!
/**
* Parent node.
*/
@get:JsonIgnore
val parent: Node get() = Node(repository, path.substringBeforeLast("/").ifEmpty { "/" })
@get:JsonIgnore
val root: Boolean get() = path == "/"
/**
* Get all parent nodes.
*/
fun parents(): Sequence<Node> = sequence {
var current = this@Node
while (!current.root) {
current = current.parent
yield(current)
}
}
@get:JsonIgnore
val parents: List<Node> get() = parents.toList()
/**
* Get child node by name.
*/
fun child(name: String) = Node(repository, "$path/$name")
/**
* Check if child node exists.
*/
fun hasChild(name: String) = child(name).exists
/**
* Get all child nodes.
*
* Because of performance issues, using method is more preferred.
*/
@get:JsonIgnore
val children: List<Node> get() = children().toList()
/**
* Loop over all node child nodes.
*/
@Suppress("unchecked_cast")
fun children(): Sequence<Node> {
log("Reading child nodes of repository node '$path' on $instance")
return try {
http.get("$path.harray.1.json") { asJson(it) }
.run {
if (has(Property.CHILDREN.value)) get(Property.CHILDREN.value).asIterable()
else listOf()
}
.map { child -> Formats.toMapFromJson(child) }
.map { props -> Node(repository, "$path/${props[Property.NAME.value]}", props.filterNotNull()) }
.asSequence()
} catch (e: CommonException) {
throw RepositoryException("Cannot read children of node '$path' on $instance. Cause: ${e.message}", e)
}
}
fun descendants(): Sequence<Node> = traverse(false)
@get:JsonIgnore
val siblings: List<Node> get() = siblings().toList()
fun siblings() = parent.children().filter { it != this }
fun sibling(name: String) = parent.child(name)
/**
* Check if node exists.
*
* Not checks again if properties of node are already loaded (skips extra HTTP request / optimization).
*/
val exists: Boolean get() = propertiesLoaded != null || exists()
/**
* Check if node exists.
*/
fun exists(recheck: Boolean = false): Boolean {
if (recheck || existsCheck == null) {
existsCheck = try {
log("Checking repository node '$path' existence on $instance")
http.head("$path.json") {
when (val status = it.statusLine.statusCode) {
HttpStatus.SC_OK -> true
HttpStatus.SC_NOT_FOUND, HttpStatus.SC_FORBIDDEN, HttpStatus.SC_UNAUTHORIZED -> false
else -> throw RepositoryException("Unexpected status code '$status' while checking node '$path' existence on $instance!")
}
}
} catch (e: CommonException) {
throw RepositoryException("Cannot check repository node existence: $path on $instance. Cause: ${e.message}", e)
}
}
return existsCheck!!
}
/**
* Create or update node in repository.
*/
fun save(properties: Map<String, Any?>): RepositoryResult = try {
log("Saving repository node '$path' using properties '$properties' on $instance")
http.postMultipart(path, postProperties(properties) + operationProperties("")) {
asObjectFromJson(it, RepositoryResult::class.java)
}
} catch (e: CommonException) {
throw RepositoryException("Cannot save repository node '$path' on $instance. Cause: ${e.message}", e)
}
/**
* Import node into repository.
*
* Effectively may be an alternative method for saving node supporting dots in node names.
*/
fun import(
properties: Map<String, Any?>,
name: String? = null,
replace: Boolean = false,
replaceProperties: Boolean = false
) = import(Formats.toJson(properties), name, replace, replaceProperties)
/**
* Import node into repository.
*
* Effectively may be an alternative method for saving node supporting dots in node names.
*/
fun import(
json: String,
name: String? = null,
replace: Boolean = false,
replaceProperties: Boolean = false
) = importInternal(importParams(json, null, name, replace, replaceProperties))
/**
* Import content structure defined in JSON file into repository.
*/
fun import(
file: File,
name: String? = null,
replace: Boolean = false,
replaceProperties: Boolean = false
): RepositoryResult {
if (!file.exists()) {
throw RepositoryException("File containing JSON content for node import does not exist: $file!")
}
return importInternal(importParams(null, file, name, replace, replaceProperties))
}
private fun importInternal(params: Map<String, Any?>) = try {
log("Importing node '$name' into repository node '$path' on $instance")
http.postMultipart(path, params) {
asObjectFromJson(it, RepositoryResult::class.java)
}
} catch (e: CommonException) {
throw RepositoryException("Cannot import node '$name' into repository node '$path' on $instance. Cause: ${e.message}", e)
}
private fun importParams(
json: String? = null,
file: File? = null,
name: String? = null,
replace: Boolean = false,
replaceProperties: Boolean = false
): Map<String, Any?> {
return mutableMapOf<String, Any?>().apply {
putAll(operationProperties("import"))
putAll(mapOf(
":replace" to replace,
":replaceProperties" to replaceProperties,
":contentType" to "json"
))
name?.let { put(":name", it) }
json?.let { put(":content", json) }
file?.let { put(":contentFile", file) }
}
}
/**
* Delete node and all children from repository.
*/
fun delete(): RepositoryResult = try {
log("Deleting repository node '$path' on $instance")
http.postMultipart(path, operationProperties("delete")) {
asObjectFromJson(it, RepositoryResult::class.java)
}
} catch (e: CommonException) {
throw RepositoryException("Cannot delete repository node '$path' on $instance. Cause: ${e.message}", e)
}
/**
* Delete node and creates it again. Use with caution!
*/
fun replace(properties: Map<String, Any?>): RepositoryResult {
delete()
return save(properties)
}
/**
* Synchronize on demand previously loaded properties of node (by default properties are loaded lazily).
* Useful when saving and working on same node again (without instantiating separate variable).
*/
fun reload() {
reloadProperties()
}
/**
* Copy node to from source path to destination path.
*/
fun copy(targetPath: String): Node = try {
http.postUrlencoded(path, operationProperties("copy") + mapOf(
":dest" to targetPath
)) { checkStatus(it, HttpStatus.SC_CREATED) }
Node(repository, targetPath)
} catch (e: CommonException) {
throw RepositoryException("Cannot copy repository node from '$path' to '$targetPath' on $instance. Cause: '${e.message}'")
}
/**
* Move node from source path to destination path.
*/
fun move(targetPath: String, replace: Boolean = false): Node = try {
http.postUrlencoded(path, operationProperties("move") + mapOf(
":dest" to targetPath,
":replace" to replace
)) { checkStatus(it, listOf(HttpStatus.SC_CREATED, HttpStatus.SC_OK)) }
Node(repository, targetPath)
} catch (e: CommonException) {
throw RepositoryException("Cannot move repository node from '$path' to '$targetPath' on $instance. Cause: '${e.message}'")
}
/**
* Change node name (effectively moves node).
*/
fun rename(newName: String, replace: Boolean = false) = move("${parent.path}/$newName", replace)
/**
* Copy node to path pointing to folder with preserving original node name.
*/
fun copyTo(targetDir: String) = copy("$targetDir/$name")
/**
* Copy node from other path to current path.
*/
fun copyFrom(sourcePath: String) = Node(repository, sourcePath).copy(path)
/**
* Search nodes by traversing a node tree.
* Use sequence filter method to find desired nodes.
*/
fun traverse(self: Boolean = false): Sequence<Node> = sequence {
val stack = Stack<Node>()
if (self) {
stack.add(this@Node)
} else {
stack.addAll(children)
}
while (stack.isNotEmpty()) {
val current = stack.pop()
stack.addAll(current.children)
yield(current)
}
}
/**
* Search nodes by querying repository under node path.
*/
fun query(criteria: QueryCriteria.() -> Unit) = query(QueryCriteria().apply(criteria))
/**
* Search nodes by querying repository under node path.
*
* Note that this method is automatically querying more results (incrementing offset internally).
*/
fun query(criteria: QueryCriteria): Sequence<Node> = repository.query(criteria.apply { path([email protected]) }).nodeSequence()
/**
* Update only single property of node.
*/
fun saveProperty(name: String, value: Any?): RepositoryResult = save(mapOf(name to value))
/**
* Delete single property from node.
*/
fun deleteProperty(name: String): RepositoryResult = deleteProperties(listOf(name))
/**
* Delete multiple properties from node.
*/
fun deleteProperties(vararg names: String) = deleteProperties(names.asIterable())
/**
* Delete multiple properties from node.
*/
fun deleteProperties(names: Iterable<String>): RepositoryResult {
return save(names.fold(mutableMapOf()) { props, name -> props[name] = null; props })
}
/**
* Check if node has property.
*/
fun hasProperty(name: String): Boolean = properties.containsKey(name)
/**
* Check if node has properties.
*/
fun hasProperties(vararg names: String) = hasProperties(names.asIterable())
/**
* Check if node has properties.
*/
fun hasProperties(names: Iterable<String>): Boolean = names.all { properties.containsKey(it) }
private fun reloadProperties(): Properties {
log("Reading properties of repository node '$path' on $instance")
return try {
http.get("$path.json") { response ->
val props = asMapFromJson(response)
Properties(this@Node, props.filterNotNull()).apply { propertiesLoaded = this }
}
} catch (e: CommonException) {
throw RepositoryException("Cannot read properties of node '$path' on $instance. Cause: ${e.message}", e)
}
}
/**
* Implementation for supporting "Controlling Content Updates with @ Suffixes"
* @see <https://sling.apache.org/documentation/bundles/manipulating-content-the-slingpostservlet-servlets-post.html>
*/
private fun postProperties(properties: Map<String, Any?>): Map<String, Any?> {
return properties.entries.fold(mutableMapOf()) { props, (name, value) ->
when (value) {
null -> props["$name@Delete"] = ""
else -> {
props[name] = RepositoryType.normalize(value)
if (repository.typeHints.get()) {
RepositoryType.hint(value)?.let { props["$name@TypeHint"] = it }
}
}
}
props
}
}
private fun operationProperties(operation: String): Map<String, Any?> = mapOf(
":operation" to operation,
":http-equiv-accept" to "application/json"
)
private fun filterMetaProperties(properties: Map<String, Any>): Map<String, Any> {
return properties.filterKeys { p -> !Property.values().any { it.value == p } }
}
private fun log(message: String, e: Throwable? = null) = repository.log(message, e)
@get:JsonIgnore
val json: String get() = Formats.toJson(this)
/**
* Upload file to node.
*
* If node path points to DAM, separate / dedicated endpoint is used automatically,
* so that metadata and renditions are generated immediately.
*/
fun upload(file: File) = when {
repository.damUploads.get() && path.startsWith("$DAM_PATH/") -> uploadDamAsset(file)
else -> uploadFile(file)
}
/**
* Upload asset using default Sling endpoint.
*/
fun uploadFile(file: File) {
log("Uploading file '$file' to repository node '$path' on $instance")
return try {
http.postMultipart(parent.path, mapOf(name to file))
} catch (e: CommonException) {
throw RepositoryException("Cannot upload file '$file' to node '$path' on $instance. Cause: ${e.message}", e)
}
}
/**
* Upload asset using dedicated DAM endpoint.
*/
fun uploadDamAsset(file: File) {
log("Uploading DAM asset '$file' to repository node '$path' on $instance")
return try {
http.postMultipart("${parent.path}$DAM_UPLOAD_SUFFIX", mapOf(
"file" to file,
"fileName" to name
))
} catch (e: CommonException) {
throw RepositoryException("Cannot upload DAM asset '$file' to node '$path' on $instance. Cause: ${e.message}", e)
}
}
/**
* Upload file to current folder node with preserving original file name.
*/
fun uploadTo(file: File) = repository.node("$path/${file.name}").apply { upload(file) }
/**
* Read file stored in node.
*/
fun <T> read(reader: (InputStream) -> T) = http.get(path) { reader(asStream(it)) }
/**
* Download file stored in node to specified local file.
*/
fun download(targetFilePath: String) = download(project.file(targetFilePath))
/**
* Download file stored in node to specified local file.
*/
fun download(targetFile: File) {
read { input -> targetFile.outputStream().use { output -> input.copyTo(output) } }
}
/**
* Download file stored in node to temporary directory with preserving file name.
*/
fun download() = downloadTo(repository.aem.common.temporaryDir)
/**
* Download file stored in node to specified local directory with preserving file name.
*/
fun downloadTo(targetDirPath: String) = downloadTo(project.file(targetDirPath))
/**
* Download file stored in node to specified local directory with preserving file name.
*/
fun downloadTo(targetDir: File) = targetDir.resolve(name).apply { download(this) }
/**
* Download node as CRX package.
*/
fun downloadPackage(options: PackageDefinition.() -> Unit = {}) = repository.sync.packageManager.download {
archiveBaseName.set(JcrUtil.manglePath([email protected]))
filter([email protected])
options()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Node
if (path != other.path) return false
return true
}
override fun hashCode(): Int = path.hashCode()
override fun toString(): String = when {
exists -> "Node(path='$path', properties=$properties)"
else -> "Node(path='$path')"
}
enum class Property(val value: String) {
PATH("jcr:path"),
SCORE("jcr:score"),
CHILDREN("__children__"),
NAME("__name__")
}
companion object {
val TYPE_UNSTRUCTURED = "jcr:primaryType" to "nt:unstructured"
const val DAM_PATH = "/content/dam"
const val DAM_UPLOAD_SUFFIX = ".createasset.html"
}
}
| apache-2.0 | aa44d84871a81e7bf1a86c06c3f7a2bb | 31.652878 | 145 | 0.603746 | 4.478293 | false | false | false | false |
MartinStyk/AndroidApkAnalyzer | app/src/main/java/sk/styk/martin/apkanalyzer/views/LoadingBarView.kt | 1 | 1015 | package sk.styk.martin.apkanalyzer.views
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.RelativeLayout
import androidx.databinding.BindingAdapter
import sk.styk.martin.apkanalyzer.databinding.ViewLoadingBarBinding
class LoadingBarView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : RelativeLayout(context, attrs) {
private val binding = ViewLoadingBarBinding.inflate(LayoutInflater.from(context), this, true)
fun setProgress(currentProgress: Int, maxProgress: Int) {
if (binding.loadingProgressBar.max != maxProgress)
binding.loadingProgressBar.max = maxProgress
binding.loadingProgressBar.progress = currentProgress
}
}
@BindingAdapter("currentProgress", "maxProgress")
fun LoadingBarView.setProgress(currentProgress: Int?, maxProgress: Int?) {
if (currentProgress != null && maxProgress != null) {
this.setProgress(currentProgress, maxProgress)
}
} | gpl-3.0 | a4649583432793631bc97909f18d7dce | 35.285714 | 128 | 0.775369 | 4.856459 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/shortcuts/TriggerShortcutManager.kt | 1 | 885 | package ch.rmy.android.http_shortcuts.scripting.shortcuts
import ch.rmy.android.http_shortcuts.data.domains.shortcuts.ShortcutId
import java.util.regex.Pattern
object TriggerShortcutManager {
private const val REGEX = """(?:triggerShortcut|enqueueShortcut)\(/\*\[shortcut]\*/"([^"]+)"/\*\[/shortcut]\*/\);"""
private val PATTERN = Pattern.compile(REGEX)
fun getTriggeredShortcutIdsFromCode(code: String): List<ShortcutId> =
buildList {
val matcher = PATTERN.matcher(code)
while (matcher.find()) {
val shortcutId = matcher.group(1) ?: ""
add(shortcutId)
}
}
fun getCodeFromTriggeredShortcutIds(shortcutIds: List<ShortcutId>): String =
shortcutIds.joinToString("\n") { shortcutId ->
"""enqueueShortcut(/*[shortcut]*/"$shortcutId"/*[/shortcut]*/);"""
}
}
| mit | fbf0a686a45002f7200e7a35b11ae971 | 35.875 | 120 | 0.629379 | 4.447236 | false | false | false | false |
marverenic/Paper | app/src/main/java/com/marverenic/reader/data/FeedlyAuthenticationManager.kt | 1 | 2464 | package com.marverenic.reader.data
import android.net.Uri
import com.marverenic.reader.BuildConfig
import com.marverenic.reader.data.service.AuthCodeActivationRequest
import com.marverenic.reader.data.service.BASE_URL
import com.marverenic.reader.data.service.FeedlyService
import io.reactivex.Single
class FeedlyAuthenticationManager(
private val service: FeedlyService,
private val prefs: PreferenceStore
) : AuthenticationManager {
private val clientId = BuildConfig.CLIENT_ID
private val clientSecret = BuildConfig.CLIENT_SECRET
private val redirectUri = "urn:ietf:wg:oauth:2.0:oob"
override val loginUrl = BASE_URL + "auth/auth?response_type=code&client_id=$clientId&redirect_uri=${Uri.encode(redirectUri)}&scope=${Uri.encode("https://cloud.feedly.com/subscriptions")}"
override val redirectUrlPrefix = redirectUri
// TODO: Check if a user has revoked our auth token
override fun isLoggedIn() = Single.just(prefs.userId != null)
override fun getFeedlyAuthToken() = prefs.authToken?.let { Single.just(it) }
?: throw IllegalStateException("User is not logged in")
override fun getFeedlyUserId() = prefs.userId?.let { Single.just(it) }
?: throw IllegalStateException("User is not logged in")
override fun logIn(callbackUrl: String): Single<Boolean> {
val uri = Uri.parse(callbackUrl.substringAfter(redirectUri))
if (uri.getQueryParameter("error") != null || uri.getQueryParameter("code") == null) {
return Single.just(false)
}
return service.activateAuthCode(
AuthCodeActivationRequest(
code = uri.getQueryParameter("code"),
client_id = clientId,
client_secret = clientSecret,
redirect_uri = redirectUri))
.doOnSuccess { response ->
if (response.isSuccessful) {
response.body()?.let {
prefs.apply {
userId = it.id
authToken = it.access_token
refreshToken = it.refresh_token
authTokenExpirationTimestamp = System.currentTimeMillis() + it.expires_in * 1000
}
}
}
}
.map { it.isSuccessful }
}
} | apache-2.0 | 50e804941ee77cbaf0b1a8ed75253a98 | 40.779661 | 191 | 0.602679 | 4.987854 | false | true | false | false |
mapzen/eraser-map | app/src/main/kotlin/com/mapzen/erasermap/model/ValhallaRouteManager.kt | 1 | 4005 | package com.mapzen.erasermap.model
import android.content.Context
import com.mapzen.android.core.GenericHttpHandler
import com.mapzen.android.core.GenericHttpHandler.LogLevel.BODY
import com.mapzen.android.core.GenericHttpHandler.LogLevel.NONE
import com.mapzen.android.routing.MapzenRouter
import com.mapzen.android.routing.MapzenRouterHttpHandler
import com.mapzen.erasermap.BuildConfig
import com.mapzen.model.ValhallaLocation
import com.mapzen.pelias.SimpleFeature
import com.mapzen.pelias.gson.Feature
import com.mapzen.valhalla.Route
import com.mapzen.valhalla.RouteCallback
import com.mapzen.valhalla.Router
import okhttp3.logging.HttpLoggingInterceptor
class ValhallaRouteManager(val settings: AppSettings,
val routerFactory: RouterFactory, val context: Context) : RouteManager {
override var origin: ValhallaLocation? = null
override var destination: Feature? = null
override var type: Router.Type = Router.Type.DRIVING
override var reverse: Boolean = false
override var route: Route? = null
override var bearing: Float? = null
override var currentRequest: RouteCallback? = null
override fun fetchRoute(callback: RouteCallback) {
currentRequest = callback
if (reverse) {
fetchReverseRoute(callback)
} else {
fetchForwardRoute(callback)
}
}
override fun toggleReverse() {
this.reverse = !reverse
}
private fun fetchForwardRoute(callback: RouteCallback) {
val location = origin
val simpleFeature = SimpleFeature.fromFeature(destination)
if (location is ValhallaLocation) {
val start: DoubleArray = doubleArrayOf(location.latitude, location.longitude)
val dest: DoubleArray = doubleArrayOf(simpleFeature.lat(), simpleFeature.lng())
val units: MapzenRouter.DistanceUnits = settings.distanceUnits
var name: String? = null
if (!simpleFeature.isAddress) {
name = simpleFeature.name()
}
val street = simpleFeature.name()
val city = simpleFeature.localAdmin()
val state = simpleFeature.region()
val router = getInitializedRouter(type)
if (location.hasBearing()) {
router.setLocation(start, location.bearing.toInt())
} else {
router.setLocation(start)
}
router.setLocation(dest, name, street, city, state)
.setDistanceUnits(units)
.setCallback(callback)
.fetch()
}
}
private fun fetchReverseRoute(callback: RouteCallback) {
val location = origin
val simpleFeature = SimpleFeature.fromFeature(destination)
if (location is ValhallaLocation) {
val start: DoubleArray = doubleArrayOf(simpleFeature.lat(), simpleFeature.lng())
val dest: DoubleArray = doubleArrayOf(location.latitude, location.longitude)
val units: MapzenRouter.DistanceUnits = settings.distanceUnits
getInitializedRouter(type)
.setLocation(start)
.setLocation(dest)
.setDistanceUnits(units)
.setCallback(callback)
.fetch()
}
}
private fun getInitializedRouter(type: Router.Type): MapzenRouter {
val endpoint = BuildConfig.ROUTE_BASE_URL ?: MapzenRouterHttpHandler.DEFAULT_URL
val logLevel = if (BuildConfig.DEBUG) BODY else NONE
val httpHandler = ValhallaHttpHandler(context, endpoint, logLevel)
val router = routerFactory.getRouter(context)
router.setHttpHandler(httpHandler)
when(type) {
Router.Type.DRIVING -> return router.setDriving()
Router.Type.WALKING -> return router.setWalking()
Router.Type.BIKING -> return router.setBiking()
Router.Type.MULTIMODAL -> return router.setMultimodal()
}
}
}
| gpl-3.0 | 6a86a1451db65e354b6456702ff4c163 | 38.264706 | 92 | 0.661174 | 4.734043 | false | false | false | false |
aosp-mirror/platform_frameworks_support | room/compiler/src/test/kotlin/androidx/room/vo/EntityTest.kt | 1 | 4531 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.vo
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.mockito.Mockito.mock
import javax.lang.model.element.Element
import javax.lang.model.element.ExecutableElement
import javax.lang.model.element.TypeElement
import javax.lang.model.type.DeclaredType
@RunWith(JUnit4::class)
class EntityTest {
@Test
fun shouldBeDeletedAfter() {
val child = createEntity("Child", listOf(
createForeignKey("NoAction", ForeignKeyAction.NO_ACTION, false),
createForeignKey("NoActionDeferred", ForeignKeyAction.NO_ACTION, true),
createForeignKey("Restrict", ForeignKeyAction.RESTRICT, false),
createForeignKey("RestrictDeferred", ForeignKeyAction.RESTRICT, true),
createForeignKey("SetNull", ForeignKeyAction.SET_NULL, false),
createForeignKey("SetNullDeferred", ForeignKeyAction.SET_NULL, true),
createForeignKey("SetDefault", ForeignKeyAction.SET_DEFAULT, false),
createForeignKey("SetDefaultDeferred", ForeignKeyAction.SET_DEFAULT, true),
createForeignKey("Cascade", ForeignKeyAction.CASCADE, false),
createForeignKey("CascadeDeferred", ForeignKeyAction.CASCADE, true)))
val noAction = createEntity("NoAction")
val noActionDeferred = createEntity("NoActionDeferred")
val restrict = createEntity("Restrict")
val restrictDeferred = createEntity("RestrictDeferred")
val setNull = createEntity("SetNull")
val setNullDeferred = createEntity("SetNullDeferred")
val setDefault = createEntity("SetDefault")
val setDefaultDeferred = createEntity("SetDefaultDeferred")
val cascade = createEntity("Cascade")
val cascadeDeferred = createEntity("CascadeDeferred")
val irrelevant = createEntity("Irrelevant")
assertThat(child.shouldBeDeletedAfter(noAction), `is`(true))
assertThat(child.shouldBeDeletedAfter(noActionDeferred), `is`(false))
assertThat(child.shouldBeDeletedAfter(restrict), `is`(true))
assertThat(child.shouldBeDeletedAfter(restrictDeferred), `is`(true))
assertThat(child.shouldBeDeletedAfter(setNull), `is`(false))
assertThat(child.shouldBeDeletedAfter(setNullDeferred), `is`(false))
assertThat(child.shouldBeDeletedAfter(setDefault), `is`(false))
assertThat(child.shouldBeDeletedAfter(setDefaultDeferred), `is`(false))
assertThat(child.shouldBeDeletedAfter(cascade), `is`(false))
assertThat(child.shouldBeDeletedAfter(cascadeDeferred), `is`(false))
assertThat(child.shouldBeDeletedAfter(irrelevant), `is`(false))
}
private fun createEntity(
tableName: String,
foreignKeys: List<ForeignKey> = emptyList()): Entity {
return Entity(
element = mock(TypeElement::class.java),
tableName = tableName,
type = mock(DeclaredType::class.java),
fields = emptyList(),
embeddedFields = emptyList(),
primaryKey = PrimaryKey(mock(Element::class.java), emptyList(), false),
indices = emptyList(),
foreignKeys = foreignKeys,
constructor = Constructor(mock(ExecutableElement::class.java), emptyList()))
}
private fun createForeignKey(
parentTable: String,
onDelete: ForeignKeyAction,
deferred: Boolean): ForeignKey {
return ForeignKey(
parentTable = parentTable,
parentColumns = emptyList(),
childFields = emptyList(),
onDelete = onDelete,
onUpdate = ForeignKeyAction.NO_ACTION,
deferred = deferred)
}
}
| apache-2.0 | 124014ed769b0164a195bfbcaf8fb902 | 45.71134 | 92 | 0.67601 | 4.984598 | false | false | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/ui/notes/query/search/SearchFragment.kt | 1 | 10912 | package com.orgzly.android.ui.notes.query.search
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.orgzly.BuildConfig
import com.orgzly.R
import com.orgzly.android.db.entity.NoteView
import com.orgzly.android.prefs.AppPreferences
import com.orgzly.android.sync.SyncRunner
import com.orgzly.android.ui.OnViewHolderClickListener
import com.orgzly.android.ui.SelectableItemAdapter
import com.orgzly.android.ui.main.setupSearchView
import com.orgzly.android.ui.notes.ItemGestureDetector
import com.orgzly.android.ui.notes.NoteItemViewHolder
import com.orgzly.android.ui.notes.NotePopup
import com.orgzly.android.ui.notes.query.QueryFragment
import com.orgzly.android.ui.notes.query.QueryViewModel
import com.orgzly.android.ui.notes.query.QueryViewModel.Companion.APP_BAR_DEFAULT_MODE
import com.orgzly.android.ui.notes.query.QueryViewModel.Companion.APP_BAR_SELECTION_MODE
import com.orgzly.android.ui.notes.query.QueryViewModelFactory
import com.orgzly.android.ui.settings.SettingsActivity
import com.orgzly.android.ui.util.ActivityUtils
import com.orgzly.android.ui.util.setDecorFitsSystemWindowsForBottomToolbar
import com.orgzly.android.ui.util.setup
import com.orgzly.android.util.LogUtils
import com.orgzly.databinding.FragmentQuerySearchBinding
/**
* Displays search results.
*/
class SearchFragment : QueryFragment(), OnViewHolderClickListener<NoteView> {
private lateinit var binding: FragmentQuerySearchBinding
private lateinit var viewAdapter: SearchAdapter
private val appBarBackPressHandler = object : OnBackPressedCallback(false) {
override fun handleOnBackPressed() {
viewModel.appBar.handleOnBackPressed()
}
}
override fun getAdapter(): SelectableItemAdapter? {
return if (::viewAdapter.isInitialized) viewAdapter else null
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val factory = QueryViewModelFactory.forQuery(dataRepository)
viewModel = ViewModelProvider(this, factory).get(QueryViewModel::class.java)
requireActivity().onBackPressedDispatcher.addCallback(this, appBarBackPressHandler)
requireActivity().onBackPressedDispatcher.addCallback(this, notePopupDismissOnBackPress)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, savedInstanceState)
binding = FragmentQuerySearchBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, savedInstanceState)
viewAdapter = SearchAdapter(binding.root.context, this)
viewAdapter.setHasStableIds(true)
// Restores selection, requires adapter
super.onViewCreated(view, savedInstanceState)
val layoutManager = LinearLayoutManager(context)
val dividerItemDecoration = DividerItemDecoration(context, layoutManager.orientation)
binding.fragmentQuerySearchRecyclerView.let { rv ->
rv.layoutManager = layoutManager
rv.adapter = viewAdapter
rv.addItemDecoration(dividerItemDecoration)
rv.addOnItemTouchListener(ItemGestureDetector(rv.context, object: ItemGestureDetector.Listener {
override fun onSwipe(direction: Int, e1: MotionEvent, e2: MotionEvent) {
rv.findChildViewUnder(e1.x, e2.y)?.let { itemView ->
rv.findContainingViewHolder(itemView)?.let { vh ->
(vh as? NoteItemViewHolder)?.let {
showPopupWindow(vh.itemId, NotePopup.Location.QUERY, direction, itemView, e1, e2) { noteId, buttonId ->
handleActionItemClick(setOf(noteId), buttonId)
}
}
}
}
}
}))
}
binding.swipeContainer.setup()
}
override fun onResume() {
super.onResume()
sharedMainActivityViewModel.setCurrentFragment(FRAGMENT_TAG)
}
private fun topToolbarToDefault() {
viewAdapter.clearSelection()
binding.topToolbar.run {
menu.clear()
inflateMenu(R.menu.query_actions)
ActivityUtils.keepScreenOnUpdateMenuItem(activity, menu)
setNavigationIcon(R.drawable.ic_menu)
setNavigationOnClickListener {
sharedMainActivityViewModel.openDrawer()
}
setOnMenuItemClickListener { menuItem ->
when (menuItem.itemId) {
R.id.sync -> {
SyncRunner.startSync()
}
R.id.activity_action_settings -> {
startActivity(Intent(context, SettingsActivity::class.java))
}
R.id.keep_screen_on -> {
dialog = ActivityUtils.keepScreenOnToggle(activity, menuItem)
}
}
true
}
requireActivity().setupSearchView(menu)
setOnClickListener {
binding.topToolbar.menu.findItem(R.id.search_view)?.expandActionView()
}
title = getString(R.string.search)
subtitle = currentQuery
}
}
private fun bottomToolbarToDefault() {
binding.bottomToolbar.visibility = View.GONE
activity?.setDecorFitsSystemWindowsForBottomToolbar(binding.bottomToolbar.visibility)
}
private fun topToolbarToMainSelection() {
binding.topToolbar.run {
menu.clear()
inflateMenu(R.menu.query_cab_top)
// Hide buttons that can't be used when multiple notes are selected
listOf(R.id.focus).forEach { id ->
menu.findItem(id)?.isVisible = viewAdapter.getSelection().count == 1
}
setNavigationIcon(R.drawable.ic_arrow_back)
setNavigationOnClickListener {
viewModel.appBar.toMode(APP_BAR_DEFAULT_MODE)
}
setOnMenuItemClickListener { menuItem ->
handleActionItemClick(viewAdapter.getSelection().getIds(), menuItem.itemId)
true
}
// Number of selected notes as a title
title = viewAdapter.getSelection().count.toString()
subtitle = null
}
}
private fun bottomToolbarToMainSelection() {
binding.bottomToolbar.run {
menu.clear()
inflateMenu(R.menu.query_cab_bottom)
setOnMenuItemClickListener { menuItem ->
handleActionItemClick(viewAdapter.getSelection().getIds(), menuItem.itemId)
true
}
visibility = View.VISIBLE
activity?.setDecorFitsSystemWindowsForBottomToolbar(visibility)
}
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, savedInstanceState)
viewModel.viewState.observe(viewLifecycleOwner, Observer { state ->
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, "Observed load state: $state")
binding.fragmentQuerySearchViewFlipper.apply {
displayedChild = when (state) {
QueryViewModel.ViewState.LOADING -> 0
QueryViewModel.ViewState.LOADED -> 1
QueryViewModel.ViewState.EMPTY -> 2
else -> 1
}
}
})
viewModel.data.observe(viewLifecycleOwner, Observer { notes ->
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, "Observed notes: ${notes.size}")
viewAdapter.submitList(notes)
val ids = notes.mapTo(hashSetOf()) { it.note.id }
viewAdapter.getSelection().removeNonExistent(ids)
viewModel.appBar.toModeFromSelectionCount(viewAdapter.getSelection().count)
})
viewModel.refresh(currentQuery, AppPreferences.defaultPriority(context))
viewModel.appBar.mode.observeSingle(viewLifecycleOwner) { mode ->
when (mode) {
APP_BAR_DEFAULT_MODE, null -> {
topToolbarToDefault()
bottomToolbarToDefault()
sharedMainActivityViewModel.unlockDrawer()
appBarBackPressHandler.isEnabled = false
}
APP_BAR_SELECTION_MODE -> {
topToolbarToMainSelection()
bottomToolbarToMainSelection()
sharedMainActivityViewModel.lockDrawer()
appBarBackPressHandler.isEnabled = true
}
}
}
}
override fun onClick(view: View, position: Int, item: NoteView) {
if (!AppPreferences.isReverseNoteClickAction(context)) {
if (viewAdapter.getSelection().count > 0) {
toggleNoteSelection(position, item)
} else {
openNote(item.note.id)
}
} else {
toggleNoteSelection(position, item)
}
}
override fun onLongClick(view: View, position: Int, item: NoteView) {
if (!AppPreferences.isReverseNoteClickAction(context)) {
toggleNoteSelection(position, item)
} else {
openNote(item.note.id)
}
}
private fun openNote(id: Long) {
listener?.onNoteOpen(id)
}
private fun toggleNoteSelection(position: Int, item: NoteView) {
val noteId = item.note.id
viewAdapter.getSelection().toggle(noteId)
viewAdapter.notifyItemChanged(position)
viewModel.appBar.toModeFromSelectionCount(viewAdapter.getSelection().count)
}
companion object {
private val TAG = SearchFragment::class.java.name
/** Name used for [android.app.FragmentManager]. */
@JvmField
val FRAGMENT_TAG: String = SearchFragment::class.java.name
@JvmStatic
fun getInstance(query: String): QueryFragment {
val fragment = SearchFragment()
val args = Bundle()
args.putString(ARG_QUERY, query)
fragment.arguments = args
return fragment
}
}
}
| gpl-3.0 | 3d2d21a51573a1cfc7a1cb07f4c02abe | 33.531646 | 135 | 0.636913 | 5.241114 | false | false | false | false |
kpspemu/kpspemu | src/commonMain/kotlin/com/soywiz/kpspemu/util/AsyncPool2.kt | 1 | 1109 | package com.soywiz.kpspemu.util
import com.soywiz.korio.async.*
//import kotlinx.atomicfu.*
interface Resetable {
fun reset(): Unit
}
interface PoolItem : Resetable {
val id: Int
}
/*
class AsyncPool2<T : PoolItem>(val maxItems: Int = Int.MAX_VALUE, var initId: Int = 0, val create: suspend (Int) -> T) {
var createdItems = atomic(0)
private val freedItem = ProduceConsumer<T>()
val allocatedItems = LinkedHashMap<Int, T>()
operator fun get(id: Int): T? = allocatedItems[id]
suspend fun <TR> tempAlloc(callback: suspend (T) -> TR): TR {
val item = alloc()
try {
return callback(item)
} finally {
free(item)
}
}
suspend fun alloc(): T {
val res = if (createdItems.value >= maxItems) {
freedItem.consume()!!
} else {
createdItems.addAndGet(1)
create(initId++)
}
res.reset()
allocatedItems[res.id] = res
return res
}
fun free(item: T) {
freedItem.produce(item)
allocatedItems.remove(item.id)
}
}
s*/
| mit | e4c36a99dd93463f5c47f51ce7c4924c | 22.104167 | 120 | 0.57349 | 3.70903 | false | false | false | false |
Szewek/Minecraft-Flux | src/main/java/szewek/mcflux/render/EnergyMachineRenderer.kt | 1 | 902 | package szewek.mcflux.render
import net.minecraft.client.Minecraft
import net.minecraft.client.renderer.BlockRendererDispatcher
import net.minecraft.client.renderer.BufferBuilder
import net.minecraftforge.client.model.animation.FastTESR
import szewek.mcflux.tileentities.TileEntityEnergyMachine
class EnergyMachineRenderer : FastTESR<TileEntityEnergyMachine>() {
private var renderBlock: BlockRendererDispatcher? = null
override fun renderTileEntityFast(te: TileEntityEnergyMachine, x: Double, y: Double, z: Double, partialTicks: Float, destroyStage: Int, partial: Float, bb: BufferBuilder) {
if (renderBlock == null) renderBlock = Minecraft.getMinecraft().blockRendererDispatcher
val bp = te.pos
val ibs = te.cachedState
bb.setTranslation(x - bp.x, y - bp.y, z - bp.z)
renderBlock!!.blockModelRenderer.renderModel(te.world, renderBlock!!.getModelForState(ibs), ibs, bp, bb, false)
}
}
| mit | 70c2f867ac783a294ae502fa9a449a58 | 46.473684 | 173 | 0.799335 | 3.774059 | false | false | false | false |
outersky/httpproxy | src/main/java/ui.kt | 1 | 8333 | package cn.hillwind.app.proxy.ui
import javax.swing.JFrame
import javax.swing.JTextPane
import javax.swing.JTable
import javax.swing.JTabbedPane
import java.awt.BorderLayout
import javax.swing.JPanel
import javax.swing.JSplitPane
import java.awt.Dimension
import javax.swing.table.AbstractTableModel
import javax.swing.table.TableRowSorter
import javax.swing.ListSelectionModel
import javax.swing.JScrollPane
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import javax.swing.SwingUtilities
import javax.swing.JToolBar
import javax.swing.JButton
import javax.swing.Action
import javax.swing.AbstractAction
import java.awt.event.ActionEvent
import javax.swing.JFileChooser
import java.io.FileOutputStream
import javax.swing.UIManager
import javax.swing.JLabel
import java.awt.CardLayout
import javax.swing.ImageIcon
import java.util.zip.GZIPInputStream
import kotlin.swing.*
import cn.hillwind.app.proxy.*
class HttpTableModel() : AbstractTableModel() {
private val headers = array("#","ID","HOST","URL","METHOD","STATUS","LENGTH","START_TIME")
override fun getColumnCount():Int { return 8 }
override fun getRowCount():Int { return entities.size }
private val entities = arrayListOf<HttpEntity>()
fun get(index:Int):HttpEntity = entities[index]
fun setHttpEntities(list : List<HttpEntity>){
entities.clear()
entities.addAll(list)
fireTableDataChanged()
}
override fun getValueAt(row:Int, col:Int):Any? {
val entry = entities[row]
// array("#","ID","HOST","URL","METHOD","STATUS","LENGTH","TIME")
return when(col){
0 -> Integer(row+1)
1 -> entry.id
2 -> entry.host
3 -> entry.url
4 -> entry.method
5 -> entry.status
6 -> entry.length
7 -> entry.startTime.longFormat()
else -> ""
}
}
override fun getColumnName(column:Int):String{
return headers[column]
}
override fun getColumnClass(columnIndex:Int) : Class<*> {
return when(columnIndex){
0,1,5,6 -> javaClass<Int>()
else -> javaClass<String>()
}
}
override fun isCellEditable(rowIndex:Int,columnIndex:Int):Boolean = false
}
class PreviewPanel : JPanel(){
val label = JLabel()
val text = JTextPane()
val layout = CardLayout();
{
setLayout(layout)
add(JScrollPane(label))
add(JScrollPane(text))
}
fun previewText(content:String){
text.setText(content)
layout.last(this)
}
fun previewImage(content:ByteArray){
label.setIcon(ImageIcon(content))
layout.first(this)
}
}
class MainFrame(val title:String) : JFrame(title){
val frame = this
val dataModel = HttpTableModel()
val sqlText = JTextPane() me {
setText("where ID>0 order by START_TIME")
addKeyListener(object : KeyAdapter(){
override fun keyPressed(p0: KeyEvent) {
if(p0.getKeyCode()==KeyEvent.VK_ENTER && p0.isControlDown()){
query()
return
}
super<KeyAdapter>.keyTyped(p0)
}
})
}
val rsTable = JTable(dataModel) me {
setRowSorter(TableRowSorter(dataModel))
setColumnSelectionAllowed(false)
setCellSelectionEnabled(false)
setRowSelectionAllowed(true)
setSelectionMode(ListSelectionModel.SINGLE_SELECTION)
val columnModel = getColumnModel()!!
0..columnModel.getColumnCount()-1 forEach { i ->
val col = columnModel.getColumn(i)!!
// array("#","ID","HOST","URL","METHOD","STATUS","LENGTH","START_TIME")
when(i){
0 -> { col.setPreferredWidth(40);col.setMaxWidth(50) }
1 -> { col.setPreferredWidth(40);col.setMaxWidth(50) }
2 -> { col.setPreferredWidth(120);col.setMaxWidth(300) }
3 -> { }
4 -> { col.setPreferredWidth(30);col.setMaxWidth(50) }
5 -> { col.setPreferredWidth(60);col.setMaxWidth(100) }
6 -> { col.setPreferredWidth(70);col.setMaxWidth(70) }
7 -> { col.setPreferredWidth(150);col.setMaxWidth(150)}
else -> {}
}
}
getSelectionModel()?.addListSelectionListener { e ->
SwingUtilities.invokeLater {
getSelectedRows().forEach {
fill(convertRowIndexToModel(it))
}
}
}
}
val requestHeaderText = JTextPane()
val ResponseHeaderText = JTextPane()
val previewPanel = PreviewPanel()
val detailPanel = JTabbedPane() me {
addTab("RequestHeader",JScrollPane(requestHeaderText))
addTab("ResponseHeader",JScrollPane(ResponseHeaderText))
addTab("Response",previewPanel)
}
var proxy:jProxy? = null
val proxyAction:Action = action("Start Proxy"){
if(proxy!=null && proxy!!.isRunning()){
proxy!!.closeSocket()
proxyAction.putValue(Action.NAME,"Start Proxy")
}else{
proxy = jProxy(18888, "", 0, 20000)
proxy!!.start()
proxyAction.putValue(Action.NAME,"Stop Proxy")
}
}
var monitoring = false
val monitorAction:Action = action("Start Monitor"){
if(monitoring){
// stop
monitoring = false
monitorAction.putValue(Action.NAME,"Start Monitor")
}else{
// start
monitoring = true
monitorAction.putValue(Action.NAME,"Stop Monitor")
}
}
val dumpAction = action("Dump"){
if(rsTable.getSelectedRow()>=0) {
val fileChooser = JFileChooser()
val index = rsTable.convertRowIndexToModel( rsTable.getSelectedRow() )
val returnVal = fileChooser.showSaveDialog(frame)
if(returnVal == JFileChooser.APPROVE_OPTION) {
dataModel[index].dump(FileOutputStream(fileChooser.getSelectedFile()!!))
}
}
}
val queryAction = action("Run SQL"){
query()
}
val consoleAction = action("Database Console"){
org.h2.tools.Console.main()
}
val toolbar = JToolBar() me {
add(JButton(proxyAction))
add(JLabel(" "))
add(JButton(monitorAction))
addSeparator()
add(JButton(queryAction))
addSeparator()
add(JButton(dumpAction))
addSeparator()
add(JButton(consoleAction))
}
fun init(){
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
setSize(900,600)
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
setLayout(BorderLayout())
add(toolbar ,BorderLayout.NORTH)
add(JSplitPane() me {
setOrientation(JSplitPane.VERTICAL_SPLIT)
setDividerLocation(100)
// setDividerSize(8)
setOneTouchExpandable(true)
setTopComponent(JScrollPane(sqlText) me { setPreferredSize(Dimension(100,100)) } )
setBottomComponent( JSplitPane() me {
setOrientation(JSplitPane.VERTICAL_SPLIT)
setDividerLocation(100)
// setDividerSize(8)
setOneTouchExpandable(true)
setTopComponent(JScrollPane(rsTable) me { setPreferredSize(Dimension(100,100)) })
setBottomComponent(detailPanel me { setPreferredSize(Dimension(100,100)) } )
})
},BorderLayout.CENTER)
}
fun query(){
dataModel setHttpEntities Db.find(sqlText.getText()!!)
}
fun fill(index:Int){
dataModel[index] self { he ->
requestHeaderText.setText(he.requestHeader)
ResponseHeaderText.setText(he.responseHeader)
he.content ifNotNull {
if (he.contentType.indexOf("image") >= 0) {
previewPanel.previewImage(he.realContent()!!)
}else{
previewPanel.previewText(String(he.realContent()!!))
}
}
}
}
}
fun main(args:Array<String>){
val frame = MainFrame("HttpProxy")
Db.init()
frame.init()
frame.query()
frame.setVisible(true)
}
| mit | c8a6607321d1f80bbf80a2b33e058517 | 28.136364 | 97 | 0.599184 | 4.531267 | false | false | false | false |
cretz/asmble | compiler/src/main/kotlin/asmble/compile/jvm/TypeRef.kt | 1 | 595 | package asmble.compile.jvm
import org.objectweb.asm.Type
data class TypeRef(val asm: Type) {
val asmName: String get() = asm.internalName
val asmDesc: String get() = asm.descriptor
fun asMethodRetDesc(vararg args: TypeRef) = Type.getMethodDescriptor(asm, *args.map { it.asm }.toTypedArray())
val stackSize: Int get() = if (asm == Type.DOUBLE_TYPE || asm == Type.LONG_TYPE) 2 else 1
fun equivalentTo(other: TypeRef) = this == other || this == Unknown || other == Unknown
object UnknownType
companion object {
val Unknown = UnknownType::class.ref
}
} | mit | 4e2d8b106025138e05dc5779d2676c08 | 28.8 | 114 | 0.677311 | 3.863636 | false | false | false | false |
crunchersaspire/worshipsongs | app/src/main/java/org/worshipsongs/activity/SplashScreenActivity.kt | 3 | 8241 | package org.worshipsongs.activity
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.content.SharedPreferences
import android.content.res.Configuration
import android.net.Uri
import android.os.Bundle
import android.util.Base64
import android.util.Log
import android.view.WindowManager
import androidx.appcompat.app.AlertDialog
import androidx.preference.PreferenceManager
import org.worshipsongs.CommonConstants
import org.worshipsongs.R
import org.worshipsongs.domain.Song
import org.worshipsongs.domain.SongDragDrop
import org.worshipsongs.service.DatabaseService
import org.worshipsongs.service.FavouriteService
import org.worshipsongs.service.SongService
import org.worshipsongs.utils.CommonUtils
import org.worshipsongs.utils.PropertyUtils
import java.io.File
import java.util.ArrayList
import java.util.Arrays
import java.util.Locale
/**
* @Author : Seenivasan
* @Version : 1.0
*/
class SplashScreenActivity : AbstractAppCompactActivity()
{
private var databaseService: DatabaseService? = null
private var sharedPreferences: SharedPreferences? = null
private var favouriteService: FavouriteService? = null
private var songService: SongService? = null
private var favouriteName: String? = null
private var noOfImportedSongs = -1
private val languageList: Array<String>
get() = if (CommonUtils.isAboveKitkat) arrayOf(getString(R.string.tamil_key), getString(R.string.english_key))
else arrayOf(getString(R.string.english_key))
private val onItemClickListener: DialogInterface.OnClickListener
get() = DialogInterface.OnClickListener { dialog, which ->
sharedPreferences!!.edit().putInt(CommonConstants.LANGUAGE_INDEX_KEY, which).apply()
setLocale()
}
private val okButtonClickListener: DialogInterface.OnClickListener
get() = DialogInterface.OnClickListener { dialog, which ->
if (languageList.size == 1)
{
sharedPreferences!!.edit().putInt(CommonConstants.LANGUAGE_INDEX_KEY, 1).apply()
}
sharedPreferences!!.edit().putBoolean(CommonConstants.LANGUAGE_CHOOSED_KEY, true).apply()
dialog.cancel()
moveToMainActivity()
}
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.splash_screen)
initSetUp(this)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
migrateFavourites()
importFavourites()
loadDatabase()
}
private fun importFavourites()
{
val data = intent.data
if (data != null)
{
val encodedString = data.query
val decodedString = String(Base64.decode(encodedString, 0))
val favouriteIdArray = decodedString.split(";".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
if (favouriteIdArray != null && favouriteIdArray.size > 0)
{
favouriteName = favouriteIdArray[0]
val songDragDrops = ArrayList<SongDragDrop>()
for (i in 1 until favouriteIdArray.size)
{
try
{
val song = songService!!.findById(Integer.valueOf(favouriteIdArray[i]))
val songDragDrop = SongDragDrop(song!!.id.toLong(), song.title!!, false)
songDragDrop.tamilTitle = song.tamilTitle
songDragDrops.add(songDragDrop)
} catch (ex: Exception)
{
Log.e(SplashScreenActivity::class.java.simpleName, "Error occurred while finding song " + ex.message)
}
}
if (songDragDrops.isEmpty())
{
noOfImportedSongs = 0
} else
{
noOfImportedSongs = songDragDrops.size
favouriteService!!.save(favouriteName!!, songDragDrops)
}
Log.i(SplashScreenActivity::class.java.simpleName, favouriteName + " successfully imported with " + songDragDrops.size + " songs")
}
}
}
fun initSetUp(context: Context)
{
databaseService = DatabaseService(context)
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
favouriteService = FavouriteService()
songService = SongService(context)
}
private fun migrateFavourites()
{
if (sharedPreferences!!.getBoolean(CommonConstants.MIGRATION_KEY, true))
{
favouriteService!!.migration(this)
sharedPreferences!!.edit().putBoolean(CommonConstants.MIGRATION_KEY, false).apply()
}
}
private fun loadDatabase()
{
try
{
val context = this@SplashScreenActivity
val currentVersion = context.packageManager.getPackageInfo(context.packageName, 0).versionName
Log.i(SplashScreenActivity::class.java.simpleName, "Current version $currentVersion")
copyBundleDatabase(context, currentVersion)
} catch (e: Exception)
{
Log.e(this.javaClass.simpleName, "Error occurred while loading database")
}
}
override fun onBackPressed()
{
this.finish()
super.onBackPressed()
}
private fun copyBundleDatabase(context: SplashScreenActivity, currentVersion: String)
{
try
{
val commonPropertyFile = PropertyUtils.getPropertyFile(context, CommonConstants.COMMON_PROPERTY_TEMP_FILENAME)
val versionInPropertyFile = PropertyUtils.getProperty(CommonConstants.VERSION_KEY, commonPropertyFile!!)
Log.i(SplashScreenActivity::class.java.simpleName, "Version in property file $versionInPropertyFile")
if (CommonUtils.isNotImportedDatabase && CommonUtils.isNewVersion(versionInPropertyFile, currentVersion))
{
Log.i(SplashScreenActivity::class.java.simpleName, "Preparing to copy bundle database.")
databaseService!!.copyDatabase("", true)
databaseService!!.open()
PropertyUtils.setProperty(CommonConstants.VERSION_KEY, currentVersion, commonPropertyFile)
Log.i(SplashScreenActivity::class.java.simpleName, "Bundle database copied successfully.")
}
showLanguageSelectionDialog()
} catch (ex: Exception)
{
Log.e(this.javaClass.simpleName, "Error occurred while coping databases", ex)
}
}
private fun showLanguageSelectionDialog()
{
val languageChoosed = sharedPreferences!!.getBoolean(CommonConstants.LANGUAGE_CHOOSED_KEY, false)
val index = sharedPreferences!!.getInt(CommonConstants.LANGUAGE_INDEX_KEY, 0)
if (!languageChoosed)
{
val builder = AlertDialog.Builder(this)
val languageList = languageList
builder.setSingleChoiceItems(languageList, index, onItemClickListener)
builder.setPositiveButton(R.string.ok, okButtonClickListener)
builder.setTitle(R.string.language_title)
builder.setCancelable(false)
builder.show()
} else
{
moveToMainActivity()
}
}
private fun moveToMainActivity()
{
setLocale()
val intent = Intent(this@SplashScreenActivity, NavigationDrawerActivity::class.java)
intent.putExtra(CommonConstants.FAVOURITES_KEY, noOfImportedSongs)
startActivity(intent)
overridePendingTransition(R.anim.splash_fade_in, R.anim.splash_fade_out)
[email protected]()
}
private fun setLocale()
{
val index = sharedPreferences!!.getInt(CommonConstants.LANGUAGE_INDEX_KEY, 0)
val localeCode = if (index == 0) "ta" else "en"
val locale = Locale(localeCode)
Locale.setDefault(locale)
val config = Configuration()
config.locale = locale
resources.updateConfiguration(config, resources.displayMetrics)
}
} | apache-2.0 | f93bbf8c2458f26b29cb3fca741d337e | 37.157407 | 146 | 0.652348 | 5.163534 | false | false | false | false |
newbieandroid/AppBase | app/src/main/java/com/fuyoul/sanwenseller/ui/main/MainActivity.kt | 1 | 15542 | package com.fuyoul.sanwenseller.ui.main
import android.content.Intent
import android.os.Bundle
import android.view.View
import com.fuyoul.sanwenseller.R
import com.fuyoul.sanwenseller.base.BaseActivity
import com.fuyoul.sanwenseller.configs.TopBarOption
import com.fuyoul.sanwenseller.structure.model.EmptyM
import com.fuyoul.sanwenseller.structure.presenter.EmptyP
import com.fuyoul.sanwenseller.structure.view.EmptyV
import com.fuyoul.sanwenseller.ui.baby.EditBabyInfoActivity
import com.fuyoul.sanwenseller.ui.main.main.BabyManagerFragment
import com.fuyoul.sanwenseller.ui.main.main.MainFragment
import com.fuyoul.sanwenseller.ui.main.main.MyFragment
import com.fuyoul.sanwenseller.utils.AddFragmentUtils
import com.netease.nim.uikit.StatusBarUtils
import com.netease.nim.uikit.recent.RecentContactsFragment
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.includetopbar.*
import android.Manifest
import android.annotation.SuppressLint
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import com.alibaba.fastjson.JSON
import com.fuyoul.sanwenseller.helper.ActivityStateHelper
import com.fuyoul.sanwenseller.helper.LoginOutHelper
import com.fuyoul.sanwenseller.helper.MsgDialogHelper
import com.fuyoul.sanwenseller.im.reminder.ReminderItem
import com.fuyoul.sanwenseller.im.reminder.ReminderManager
import com.fuyoul.sanwenseller.im.reminder.SystemMessageUnreadManager
import com.fuyoul.sanwenseller.im.session.extension.StickerAttachment
import com.fuyoul.sanwenseller.ui.others.ActivityMsgListActivity
import com.fuyoul.sanwenseller.ui.others.SystemMsgListActivity
import com.fuyoul.sanwenseller.utils.NormalFunUtils
import com.fuyoul.sanwenseller.utils.NormalFunUtils.showToast
import com.netease.nim.uikit.NimUIKit
import com.netease.nim.uikit.common.badger.Badger
import com.netease.nim.uikit.recent.RecentContactsCallback
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.RequestCallback
import com.netease.nimlib.sdk.StatusCode
import com.netease.nimlib.sdk.auth.AuthServiceObserver
import com.netease.nimlib.sdk.msg.MsgService
import com.netease.nimlib.sdk.msg.MsgServiceObserve
import com.netease.nimlib.sdk.msg.SystemMessageService
import com.netease.nimlib.sdk.msg.attachment.MsgAttachment
import com.netease.nimlib.sdk.msg.constant.MsgDirectionEnum
import com.netease.nimlib.sdk.msg.constant.MsgStatusEnum
import com.netease.nimlib.sdk.msg.model.IMMessage
import com.netease.nimlib.sdk.msg.model.RecentContact
import com.netease.nimlib.sdk.uinfo.UserInfoProvider
import com.netease.nimlib.sdk.uinfo.UserService
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo
import permissions.dispatcher.*
import java.util.*
/**
* Auther: chen
* Creat at: 2017\10\10 0010
* Desc:
*/
@RuntimePermissions
class MainActivity : BaseActivity<EmptyM, EmptyV, EmptyP>(), ReminderManager.UnreadNumChangedCallback {
private var currentTag = ""
private val fragments = arrayListOf(MainFragment(), BabyManagerFragment(), RecentContactsFragment(), MyFragment())
private var addFragmentUtils: AddFragmentUtils? = null
override fun getPresenter(): EmptyP = EmptyP(initViewImpl())
override fun initViewImpl(): EmptyV = EmptyV()
override fun initTopBar(): TopBarOption = TopBarOption()
override fun setLayoutRes(): Int = R.layout.activity_main
override fun initData(savedInstanceState: Bundle?) {
toolbarBack.visibility = View.GONE
noThingWithPermissionCheck()
registIm()
requestSystemMessageUnreadCount()
addFragmentUtils = AddFragmentUtils(this, R.id.mainContentLayout)
}
override fun setListener() {
mainBottomLayout.setOnCheckedChangeListener { radioGroup, i ->
when (i) {
R.id.mainItem -> {
titBarLayout.visibility = View.VISIBLE
toolbarTitle.text = "三问"
toolbarChildTitle.visibility = View.GONE
StatusBarUtils.setTranslucentForImageView(this, titBarLayout)
StatusBarUtils.StatusBarLightMode(this, R.color.color_white)
msgItem.isChecked = false
currentTag = fragments[0].javaClass.name
addFragmentUtils?.showFragment(fragments[0], currentTag)
}
R.id.babyItem -> {
titBarLayout.visibility = View.VISIBLE
toolbarChildTitle.visibility = View.VISIBLE
toolbarTitle.text = "宝贝管理"
toolbarChildTitle.text = "发布宝贝"
toolbarChildTitle.setTextColor(resources.getColor(R.color.color_3CC5BC))
toolbarChildTitle.setOnClickListener {
EditBabyInfoActivity.start(this, null)
}
StatusBarUtils.setTranslucentForImageView(this, titBarLayout)
StatusBarUtils.StatusBarLightMode(this, R.color.color_white)
msgItem.isChecked = false
currentTag = fragments[1].javaClass.name
addFragmentUtils?.showFragment(fragments[1], currentTag)
}
R.id.msgItem -> {
titBarLayout.visibility = View.VISIBLE
toolbarTitle.text = "消息"
toolbarChildTitle.visibility = View.GONE
StatusBarUtils.setTranslucentForImageView(this, titBarLayout)
StatusBarUtils.StatusBarLightMode(this, R.color.color_white)
currentTag = fragments[2].javaClass.name
addFragmentUtils?.showFragment(fragments[2], currentTag)
}
R.id.myItem -> {
titBarLayout.visibility = View.GONE
msgItem.isChecked = false
currentTag = fragments[3].javaClass.name
addFragmentUtils?.showFragment(fragments[3], currentTag)
}
}
}
msgItem.setOnCheckedChangeListener { _, b ->
if (b) {
mainItem.isChecked = false
babyItem.isChecked = false
myItem.isChecked = false
mainBottomLayout.check(R.id.msgItem)
}
}
mainItem.isChecked = true
(fragments[2] as RecentContactsFragment).setCallback(object : RecentContactsCallback {
override fun onRecentContactsLoaded() {
}
override fun onUnreadCountChange(unreadCount: Int) {
ReminderManager.getInstance().updateSessionUnreadNum(unreadCount)
}
override fun onItemClick(recent: RecentContact?) {
//如果是系统通知或者活动公告
if (recent?.contactId.equals(NimUIKit.ACTIVITYCONTACTID)) {
startActivity(Intent(this@MainActivity, ActivityMsgListActivity::class.java))
} else if (recent?.contactId.equals(NimUIKit.NOTIFYCONTACTID)) {
startActivity(Intent(this@MainActivity, SystemMsgListActivity::class.java))
} else {
if (PermissionUtils.hasSelfPermissions(this@MainActivity, Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE)) {
NimUIKit.startP2PSession(this@MainActivity, recent?.contactId)
} else {
MsgDialogHelper.showNormalDialog(this@MainActivity, true, "缺少必要权限,是否前往开启?", "", "前往", object : MsgDialogHelper.DialogListener {
override fun onPositive() {
NormalFunUtils.goToAppDetailSettingIntent(this@MainActivity)
}
override fun onNagetive() {
}
})
}
}
}
override fun getDigestOfAttachment(recent: RecentContact?, attachment: MsgAttachment?): String? {
if (attachment is StickerAttachment) {
return "[贴图]"
}
return null
}
override fun getDigestOfTipMsg(recent: RecentContact?): String? {
val msgId = recent!!.recentMessageId
val uuids = ArrayList<String>(1)
uuids.add(msgId)
val msgs = NIMClient.getService(MsgService::class.java).queryMessageListByUuidBlock(uuids)
if (msgs != null && !msgs.isEmpty()) {
val msg = msgs[0]
val content = msg.remoteExtension
if (content != null && !content.isEmpty()) {
return content["content"] as String
}
}
return null
}
})
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
addFragmentUtils?.currentFragment?.onActivityResult(requestCode, resultCode, data)
}
@NeedsPermission(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE)
fun noThing() {
}
@SuppressLint("NeedOnRequestPermissionsResult")
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
onRequestPermissionsResult(requestCode, grantResults)
}
@OnShowRationale(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE)
fun noThingR(request: PermissionRequest) {
MsgDialogHelper.showSingleDialog(this@MainActivity, false, "温馨提示", "缺少必要权限,是否进行授权?", "确定", object : MsgDialogHelper.DialogListener {
override fun onPositive() {
request.proceed()
}
override fun onNagetive() {
request.cancel()
}
})
}
@OnPermissionDenied(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE)
fun noThingD() {
NormalFunUtils.showToast(this@MainActivity, "缺少必要权限,请前往权限管理中心开启对应权限")
}
@OnNeverAskAgain(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE)
fun noThingN() {
NormalFunUtils.showToast(this@MainActivity, "缺少必要权限,请前往权限管理中心开启对应权限")
}
var isFinish = false
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (isFinish) {
ActivityStateHelper.removeAll()
} else {
showToast(this, "提示:再按一次推出程序")
isFinish = true
Timer().schedule(object : TimerTask() {
override fun run() {
isFinish = false
}
}, 1500)
}
return true
}
return super.onKeyDown(keyCode, event)
}
//=========================消息相关
override fun onDestroy() {
unregistIm()
registMsgReveiver(false)
super.onDestroy()
}
/**
* 注册未读消息数量观察者
*/
private fun registerMsgUnreadInfoObserver(register: Boolean) {
if (register) {
ReminderManager.getInstance().registerUnreadNumChangedCallback(this)
} else {
ReminderManager.getInstance().unregisterUnreadNumChangedCallback(this)
}
}
override fun onUnreadNumChanged(item: ReminderItem?) {
setMsgNum(item!!.unread)
}
private fun registIm() {
NIMClient.getService(AuthServiceObserver::class.java).observeOnlineStatus(userStatusObserver, true)
registerMsgUnreadInfoObserver(true)
registMsgReveiver(true)
NIMClient.getService(MsgService::class.java).queryRecentContacts().setCallback(object : RequestCallback<List<RecentContact>> {
override fun onException(p0: Throwable?) {
}
override fun onFailed(p0: Int) {
}
override fun onSuccess(p0: List<RecentContact>?) {
val count = (0 until p0!!.size).sumBy { p0[it].unreadCount }
Log.e("csl", "----首页查询最近联系人未读消息条数------$count--")
setMsgNum(count)
}
})
}
private fun unregistIm() {
NIMClient.getService(AuthServiceObserver::class.java).observeOnlineStatus(userStatusObserver, false)
registerMsgUnreadInfoObserver(false)
registMsgReveiver(false)
}
//如果是异地登录
private val userStatusObserver = com.netease.nimlib.sdk.Observer<StatusCode> { code ->
if (code.wontAutoLogin()) {
LoginOutHelper.accountLoginOut(this@MainActivity, true)
}
}
/**
* 消息接收监听
*/
fun registMsgReveiver(isReg: Boolean) {
NIMClient.getService(MsgServiceObserve::class.java)
.observeReceiveMessage(incomingMessageObserver, isReg)
}
private fun requestSystemMessageUnreadCount() {
val unread = NIMClient.getService(SystemMessageService::class.java).querySystemMessageUnreadCountBlock()
SystemMessageUnreadManager.getInstance().sysMsgUnreadCount = unread
ReminderManager.getInstance().updateContactUnreadNum(unread)
}
private val incomingMessageObserver =
com.netease.nimlib.sdk.Observer<List<IMMessage>> { list ->
var unreadNum = getUnReadCount()
(0 until list.size)
.map { list[it] }
.filter { it.direct == MsgDirectionEnum.In && it.status == MsgStatusEnum.unread }
.forEach { unreadNum += 1 }
Log.e("csl", "---------首页收到新消息未读消息条数--$unreadNum-")
setMsgNum(unreadNum)
}
private fun getUnReadCount(): Int {
return try {
Integer.parseInt(if (TextUtils.isEmpty(msgCount.text.toString())) "0" else msgCount.text.toString())
} catch (e: NumberFormatException) {
100
}
}
private fun setMsgNum(num: Int) {
when {
num > 99 -> {
msgCount.visibility = View.VISIBLE
msgCount.text = "99+"
}
num in 1..99 -> {
msgCount.visibility = View.VISIBLE
msgCount.text = "$num"
}
else -> msgCount.visibility = View.GONE
}
Badger.updateBadgerCount(num)//桌面添加未读消息条数
}
} | apache-2.0 | 9eb480f9c960469325e0354b4d520265 | 35.332536 | 267 | 0.63901 | 4.634117 | false | false | false | false |
nickthecoder/tickle | tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/events/KeyInput.kt | 1 | 1184 | /*
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.events
import org.lwjgl.glfw.GLFW
import uk.co.nickthecoder.tickle.graphics.Window
class KeyInput(val key: Key, val state: ButtonState = ButtonState.PRESSED) : Input {
override fun isPressed(): Boolean {
return GLFW.glfwGetKey(Window.instance?.handle ?: 0, key.code) == GLFW.GLFW_PRESS
}
override fun matches(event: KeyEvent): Boolean {
return event.state == state && key == event.key
}
override fun toString() = "KeyInput key=$key state=$state"
}
| gpl-3.0 | 01bc7d86ad9a15cdcca66a1d6be65847 | 31.888889 | 89 | 0.744932 | 4.082759 | false | false | false | false |
Kotlin/anko | anko/library/static/commons/src/main/java/dialogs/Selectors.kt | 2 | 1854 | /*
* Copyright 2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("NOTHING_TO_INLINE", "unused")
package org.jetbrains.anko
import android.app.Fragment
import android.content.Context
import android.content.DialogInterface
inline fun <D : DialogInterface> AnkoContext<*>.selector(
noinline factory: AlertBuilderFactory<D>,
title: CharSequence? = null,
items: List<CharSequence>,
noinline onClick: (DialogInterface, CharSequence, Int) -> Unit
) = ctx.selector(factory, title, items, onClick)
@Deprecated(message = "Use support library fragments instead. Framework fragments were deprecated in API 28.")
inline fun <D : DialogInterface> Fragment.selector(
noinline factory: AlertBuilderFactory<D>,
title: CharSequence? = null,
items: List<CharSequence>,
noinline onClick: (DialogInterface, CharSequence, Int) -> Unit
) = activity.selector(factory, title, items, onClick)
fun <D : DialogInterface> Context.selector(
factory: AlertBuilderFactory<D>,
title: CharSequence? = null,
items: List<CharSequence>,
onClick: (DialogInterface, CharSequence, Int) -> Unit
) {
with(factory(this)) {
if (title != null) {
this.title = title
}
items(items, onClick)
show()
}
}
| apache-2.0 | 4c1eb2b80f4a72efa669c46860a6cfc1 | 34.653846 | 110 | 0.695254 | 4.352113 | false | false | false | false |
ujpv/intellij-rust | src/main/kotlin/org/rust/lang/doc/lexer/RustDocHighlightingLexer.kt | 1 | 1180 | package org.rust.lang.doc.lexer
import com.intellij.lexer.FlexAdapter
import com.intellij.lexer.Lexer
import com.intellij.lexer.MergeFunction
import com.intellij.lexer.MergingLexerAdapter
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.TokenType.WHITE_SPACE
import com.intellij.psi.tree.TokenSet
import org.rust.lang.doc.psi.RustDocElementTypes.*
import org.rust.lang.doc.psi.RustDocKind
class RustDocHighlightingLexer(kind: RustDocKind) :
MergingLexerAdapter(
FlexAdapter(_RustDocHighlightingLexer(null, kind.isBlock)),
TOKENS_TO_MERGE) {
override fun getMergeFunction() = MergeFunction { type, lexer ->
if (type == DOC_TEXT) {
while (lexer.tokenType == type || isOnNonEolWS(lexer)) {
lexer.advance()
}
type
} else {
super.getMergeFunction().merge(type, lexer)
}
}
private fun isOnNonEolWS(lexer: Lexer) =
lexer.tokenType == WHITE_SPACE && !StringUtil.containsLineBreak(lexer.tokenSequence)
companion object {
private val TOKENS_TO_MERGE = TokenSet.create(WHITE_SPACE, DOC_CODE_SPAN, DOC_CODE_FENCE)
}
}
| mit | 5989b50841b3045ebc099179891e8cc8 | 31.777778 | 97 | 0.694915 | 3.973064 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.